@codemem/server 0.40.0-alpha.1 → 0.40.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/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +236 -24
- package/dist/index.js.map +1 -1
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/sync.d.ts +28 -2
- package/dist/routes/sync.d.ts.map +1 -1
- package/package.json +2 -2
- package/static/app.js +17 -17
- package/static/app.js.br +0 -0
- package/static/app.js.gz +0 -0
package/static/app.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(){var Iu=Object.defineProperty,T_=(e,t)=>{let n={};for(var r in e)Iu(n,r,{get:e[r],enumerable:!0});return t||Iu(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 Le(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 Ru(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 N_(){return Le("/api/observer-status")}async function k_(){return Le("/api/config")}async function x_(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 No(){return Le("/api/coordinator/admin/status")}async function Du(e){return Le(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`)}async function P_(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 E_(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 A_(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 I_(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 R_(e,t=!1){const n=new URLSearchParams;t&&n.set("include_inactive","1");const r=n.size?`?${n.toString()}`:"";return Le(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes${r}`)}async function D_(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 L_(e,t,n=!1){const r=new URLSearchParams;n&&r.set("include_revoked","1");const i=r.size?`?${r.toString()}`:"";return Le(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members${i}`)}async function $_(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 M_(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 O_(e){const t=new URLSearchParams;return e&&t.set("group_id",e),Le(`/api/coordinator/admin/join-requests${t.size?`?${t.toString()}`:""}`)}async function Lu(e,t=!0){const n=new URLSearchParams;return e&&n.set("group_id",e),t&&n.set("include_disabled","1"),Le(`/api/coordinator/admin/devices${n.size?`?${n.toString()}`:""}`)}async function j_(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 F_(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 B_(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 U_(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 G_(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 $u(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 Mu(e,t){return Le(`/api/observations?${Ru(e,t?.limit,t?.offset,t?.scope)}`)}async function H_(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 K_(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 q_(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 Ou(e,t){return Le(`/api/summaries?${Ru(e,t?.limit,t?.offset,t?.scope)}`)}async function W_(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 V_(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 z_(){return Le("/api/runtime")}async function ko(){return(await Le("/api/projects")).projects||[]}async function J_(){return Le("/api/stats")}async function Y_(e){return Le(`/api/usage?project=${encodeURIComponent(e)}`)}async function X_(e){return Le(`/api/session?project=${encodeURIComponent(e)}`)}async function Q_(e){return Le(`/api/raw-events?project=${encodeURIComponent(e)}`)}async function Fs(e,t="",n){const r=new URLSearchParams;return e&&r.set("includeDiagnostics","1"),t&&r.set("project",t),n?.includeJoinRequests&&r.set("includeJoinRequests","1"),Le(`/api/sync/status${r.size?`?${r.toString()}`:""}`)}async function Bs(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 ju(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 Le("/api/sync/actors")}async function ew(e=!1){return Le(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`)}async function tw(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 Fu(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 Bu(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 nw(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 Uu=class extends Error{preview;constructor(e){super("Project forget confirmation required"),this.name="ProjectForgetConfirmationError",this.preview=e}},xo=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??[]}},Gu=class extends Error{preview;constructor(e){super("Legacy shared review confirmation required"),this.name="LegacySharedReviewConfirmationError",this.preview=e}},Hu=class extends Error{result;constructor(e){super("Recipient policy review source state changed"),this.name="RecipientPolicyReviewStaleError",this.result=e}},Us=class extends Error{result;constructor(e){super("Recipient policy changed after review"),this.name="RecipientPolicyEdgesStaleError",this.result=e}};function Gs(){return Le("/api/sync/recipient-policy/v1/intent")}function rw(){return Le("/api/sync/recipient-policy/v1/reconciliation-status")}async function Ku(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 Us(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 iw(e){return Ku("/api/sync/recipient-policy/v1/edges/preview",e)}function ow(e){return Ku("/api/sync/recipient-policy/v1/edges/commit",e)}async function qu(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 aw(e){return qu("/api/sync/recipient-policy/v1/invites/preview",e)}function sw(e){return qu("/api/sync/recipient-policy/v1/invites",e)}function cw(){return Le("/api/sync/recipient-policy/v1/review")}async function lw(e){const t=await fetch("/api/sync/recipient-policy/v1/review/resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await ye(t);if(!t.ok)throw t.status===409&&r?.status==="stale"?new Hu(r):new Error(ve(r)||n||"request failed");return r}async function dw(){return Le("/api/sync/sharing-domains/settings")}async function Po(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 Le(`/api/sync/projects${n?`?${n}`:""}`)}async function Wu(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 uw(e){return Wu("/api/sync/project-invites/preview",e)}function pw(e){return Wu("/api/sync/project-invites",e)}function Vu(){return Le("/api/sync/share-operations")}function mw(e){return Le(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function fw(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 hw(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 xo(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 gw(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 xo(r):new Error(ve(r)||n||"request failed");if(!Array.isArray(r?.mappings))throw new Error("response missing mappings");return r.mappings}async function vw(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 yw(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 bw(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 Uu(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 _w(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 Gu(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 ww(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 Sw(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 Cw(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 Tw(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 zu(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 Nw(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 kw(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 Hs(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}var ui,me,Ju,Yu,gn,Xu,Qu,Zu,Ks,Eo,pi,ep,qs,Ws,Vs,tp,Ao={},Io=[],xw=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,mi=Array.isArray;function jt(e,t){for(var n in t)e[n]=t[n];return e}function zs(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?ui.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 fi(e,s,r,i,null)}function fi(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??++Ju,__i:-1,__u:0};return i==null&&me.vnode!=null&&me.vnode(o),o}function np(){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 Pw(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],i=[],o=jt({},t);o.__v=t.__v+1,me.vnode&&me.vnode(o),Ys(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,cp(r,o,i),t.__e=t.__=null,o.__e!=n&&rp(o)}}function rp(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}),rp(e)}function Js(e){(!e.__d&&(e.__d=!0)&&gn.push(e)&&!Ro.__r++||Xu!=me.debounceRendering)&&((Xu=me.debounceRendering)||Qu)(Ro)}function Ro(){try{for(var e,t=1;gn.length;)gn.length>t&&gn.sort(Zu),e=gn.shift(),t=gn.length,Pw(e)}finally{gn.length=Ro.__r=0}}function ip(e,t,n,r,i,o,s,c,l,d,u){var p,m,f,g,h,v,b,w=r&&r.__k||Io,S=t.length;for(l=Ew(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,v=Ys(e,f,m,i,o,s,c,l,d,u),g=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&Qs(m.ref,null,f),u.push(f.ref,f.__c||g,f)),h==null&&g!=null&&(h=g),(b=!!(4&f.__u))||m.__k===f.__k?(l=op(f,l,e,b),b&&m.__e&&(m.__e=null)):typeof f.type=="function"&&v!==void 0?l=v:g&&(l=g.nextSibling),f.__u&=-7);return n.__e=h,l}function Ew(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]=fi(null,s,null,null,null):mi(s)?s=e.__k[o]=fi(te,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[o]=fi(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=Aw(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)),dp(c,c));return r}function op(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=op(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 Qt(e,t){return t=t||[],e==null||typeof e=="boolean"||(mi(e)?e.some(function(n){Qt(n,t)}):t.push(e)),t}function Aw(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 ap(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||xw.test(t)?n:n+"px"}function Do(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||ap(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||ap(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(ep,"$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[pi]=r[pi]:(n[pi]=qs,e.addEventListener(t,o?Vs:Ws,o)):e.removeEventListener(t,o?Vs:Ws,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 sp(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Eo]==null)t[Eo]=qs++;else if(t[Eo]<n[pi])return;return n(me.event?me.event(t):t)}}}function Ys(e,t,n,r,i,o,s,c,l,d){var u,p,m,f,g,h,v,b,w,S,T,N,P,A,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=me.__b)&&u(t);e:if(typeof U=="function")try{if(b=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?v=(p=t.__c=n.__c).__=p.__E:(w?t.__c=p=new U(b,T):(t.__c=p=new _t(b,T),p.constructor=U,p.render=Rw),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(b,p.__s))),f=p.props,g=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&&b!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(b,T),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(b,p.__s,T)===!1){t.__v!=n.__v&&(p.props=b,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(x){x&&(x.__=t)}),Io.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(b,p.__s,T),w&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,g,h)})}if(p.context=T,p.props=b,p.__P=e,p.__e=!1,N=me.__r,P=0,w)p.state=p.__s,p.__d=!1,N&&N(t),u=p.render(p.props,p.state,p.context),Io.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,N&&N(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,g)),A=u!=null&&u.type===te&&u.key==null?lp(u.props.children):u,c=ip(e,mi(A)?A:[A],t,n,r,i,o,s,c,l,d),p.base=t.__e,t.__u&=-161,p.__h.length&&s.push(p),v&&(p.__E=p.__=null)}catch(x){if(t.__v=null,l||o!=null)if(x.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--;)zs(o[M]);Xs(t)}else t.__e=n.__e,t.__k=n.__k,x.then||Xs(t);me.__e(x,t,n)}else o==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=Iw(n.__e,t,n,r,i,o,s,l,d);return(u=me.diffed)&&u(t),128&t.__u?void 0:c}function Xs(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Xs))}function cp(e,t,n){for(var r=0;r<n.length;r++)Qs(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 lp(e){return typeof e!="object"||e==null||e.__b>0?e:mi(e)?e.map(lp):e.constructor!==void 0?null:jt({},e)}function Iw(e,t,n,r,i,o,s,c,l){var d,u,p,m,f,g,h,v=n.props||Ao,b=t.props,w=t.type;if(w=="svg"?i="http://www.w3.org/2000/svg":w=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),o!=null){for(d=0;d<o.length;d++)if((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(b);e=document.createElementNS(i,w,b.is&&b),c&&(me.__m&&me.__m(t,o),c=!1),o=null}if(w==null)v===b||c&&e.data==b||(e.data=b);else{if(o=w=="textarea"&&b.defaultValue!=null?null:o&&ui.call(e.childNodes),!c&&o!=null)for(v={},d=0;d<e.attributes.length;d++)v[(f=e.attributes[d]).name]=f.value;for(d in v)f=v[d],d=="dangerouslySetInnerHTML"?p=f:d=="children"||d in b||d=="value"&&"defaultValue"in b||d=="checked"&&"defaultChecked"in b||Do(e,d,null,f,i);for(d in b)f=b[d],d=="children"?m=f:d=="dangerouslySetInnerHTML"?u=f:d=="value"?g=f:d=="checked"?h=f:c&&typeof f!="function"||v[d]===f||Do(e,d,f,v[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=""),ip(t.type=="template"?e.content:e,mi(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--;)zs(o[d]);c&&w!="textarea"||(d="value",w=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[d]||w=="progress"&&!g||w=="option"&&g!=v[d])&&Do(e,d,g,v[d],i),d="checked",h!=null&&h!=e[d]&&Do(e,d,h,v[d],i))}return e}function Qs(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 dp(e,t,n){var r,i;if(me.unmount&&me.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Qs(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]&&dp(r[i],t,n||typeof e.type!="function");n||zs(e.__e),e.__c=e.__=e.__e=void 0}function Rw(e,t,n){return this.constructor(e,n)}function Ue(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=[],Ys(t,e=(!r&&n||t).__k=y(te,null,[e]),i||Ao,Ao,t.namespaceURI,!r&&n?[n]:i?null:t.firstChild?ui.call(t.childNodes):null,o,!r&&n?n:i?i.__e:t.firstChild,r,s),cp(o,e,s)}function up(e,t){Ue(e,t,up)}function Dw(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?ui.call(arguments,2):n),fi(e.type,c,r||e.key,i||e.ref,null)}function Un(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,Js(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"+tp++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}ui=Io.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}},Ju=0,Yu=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),Js(this))},_t.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Js(this))},_t.prototype.render=te,gn=[],Qu=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Zu=function(e,t){return e.__v.__b-t.__v.__b},Ro.__r=0,Ks=Math.random().toString(8),Eo="__d"+Ks,pi="__a"+Ks,ep=/(PointerCapture)$|Capture$/i,qs=0,Ws=sp(!1),Vs=sp(!0),tp=0;var Zt,Re,Zs,pp,Sr=0,mp=[],je=me,fp=je.__b,hp=je.__r,gp=je.diffed,vp=je.__c,yp=je.unmount,bp=je.__;function Gn(e,t){je.__h&&je.__h(Re,e,Sr||t),Sr=0;var n=Re.__H||(Re.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function I(e){return Sr=1,hi(wp,e)}function hi(e,t,n){var r=Gn(Zt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):wp(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=Re,!Re.__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};Re.__f=!0;var o=Re.shouldComponentUpdate,s=Re.componentWillUpdate;Re.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)},Re.shouldComponentUpdate=i}return r.__N||r.__}function K(e,t){var n=Gn(Zt++,3);!je.__s&&nc(n.__H,t)&&(n.__=e,n.u=t,Re.__H.__h.push(n))}function gt(e,t){var n=Gn(Zt++,4);!je.__s&&nc(n.__H,t)&&(n.__=e,n.u=t,Re.__h.push(n))}function B(e){return Sr=5,ke(function(){return{current:e}},[])}function Lo(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 ke(e,t){var n=Gn(Zt++,7);return nc(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function re(e,t){return Sr=8,ke(function(){return e},t)}function vn(e){var t=Re.context[e.__c],n=Gn(Zt++,9);return n.c=e,t?(n.__??(n.__=!0,t.sub(Re)),t.props.value):e.__}function ec(e,t){je.useDebugValue&&je.useDebugValue(t?t(e):e)}function Lw(e){var t=Gn(Zt++,10),n=I();return t.__=e,Re.componentDidCatch||(Re.componentDidCatch=function(r,i){t.__&&t.__(r,i),n[1](r)}),[n[0],function(){n[1](void 0)}]}function gi(){var e=Gn(Zt++,11);if(!e.__){for(var t=Re.__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 $w(){for(var e;e=mp.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some($o),t.__h.some(tc),t.__h=[]}catch(n){t.__h=[],je.__e(n,e.__v)}}}je.__b=function(e){Re=null,fp&&fp(e)},je.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),bp&&bp(e,t)},je.__r=function(e){hp&&hp(e),Zt=0;var t=(Re=e.__c).__H;t&&(Zs===Re?(t.__h=[],Re.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some($o),t.__h.some(tc),t.__h=[],Zt=0)),Zs=Re},je.diffed=function(e){gp&&gp(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(mp.push(t)!==1&&pp===je.requestAnimationFrame||((pp=je.requestAnimationFrame)||Mw)($w)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Zs=Re=null},je.__c=function(e,t){t.some(function(n){try{n.__h.some($o),n.__h=n.__h.filter(function(r){return!r.__||tc(r)})}catch(r){t.some(function(i){i.__h&&(i.__h=[])}),t=[],je.__e(r,n.__v)}}),vp&&vp(e,t)},je.unmount=function(e){yp&&yp(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{$o(r)}catch(i){t=i}}),n.__H=void 0,t&&je.__e(t,n.__v))};var _p=typeof requestAnimationFrame=="function";function Mw(e){var t,n=function(){clearTimeout(r),_p&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);_p&&(t=requestAnimationFrame(n))}function $o(e){var t=Re,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Re=t}function tc(e){var t=Re;e.__c=e.__(),Re=t}function nc(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function wp(e,t){return typeof t=="function"?t(e):t}var RO=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ow=0,DO=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:--Ow,__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 Mo({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 Sp=T_({Children:()=>Ft,Component:()=>_t,Fragment:()=>te,PureComponent:()=>Oo,StrictMode:()=>te,Suspense:()=>vi,SuspenseList:()=>Cr,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>Bp,cloneElement:()=>Tr,createContext:()=>Un,createElement:()=>y,createFactory:()=>Up,createPortal:()=>en,createRef:()=>np,default:()=>nn,findDOMNode:()=>qp,flushSync:()=>jo,forwardRef:()=>F,hydrate:()=>$p,isElement:()=>Vp,isFragment:()=>Gp,isMemo:()=>Hp,isValidElement:()=>tn,lazy:()=>Ip,memo:()=>Tp,render:()=>Lp,startTransition:()=>ac,unmountComponentAtNode:()=>Kp,unstable_batchedUpdates:()=>Wp,useCallback:()=>re,useContext:()=>vn,useDebugValue:()=>ec,useDeferredValue:()=>sc,useEffect:()=>K,useErrorBoundary:()=>Lw,useId:()=>gi,useImperativeHandle:()=>Lo,useInsertionEffect:()=>lc,useLayoutEffect:()=>gt,useMemo:()=>ke,useReducer:()=>hi,useRef:()=>B,useState:()=>I,useSyncExternalStore:()=>ic,useTransition:()=>cc,version:()=>zw});function Cp(e,t){for(var n in t)e[n]=t[n];return e}function rc(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 ic(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,oc(i)&&o({t:i})},[e,n,t]),K(function(){return oc(i)&&o({t:i}),e(function(){oc(i)&&o({t:i})})},[e]),n}function oc(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 ac(e){e()}function sc(e){return e}function cc(){return[!1,ac]}var lc=gt;function Oo(e,t){this.props=e,this.context=t}function Tp(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:rc(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}(Oo.prototype=new _t).isPureReactComponent=!0,Oo.prototype.shouldComponentUpdate=function(e,t){return rc(this.props,e)||rc(this.state,t)};var Np=me.__b;me.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Np&&Np(e)};var jw=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function F(e){function t(n){var r=Cp({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=jw,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var kp=function(e,t){return e==null?null:Qt(Qt(e).map(t))},Ft={map:kp,forEach:kp,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},Fw=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)}Fw(e,t,n,r)};var xp=me.unmount;function Pp(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=Cp({},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 Pp(r,t,n)})),e}function Ep(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Ep(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 vi(){this.__u=0,this.o=null,this.__b=null}function Ap(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Ip(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 Cr(){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),xp&&xp(e)},(vi.prototype=new _t).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=Ap(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]=Ep(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)},vi.prototype.componentWillUnmount=function(){this.o=[]},vi.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]=Pp(this.__b,n,r.__O=r.__P)}this.__b=null}var i=t.__a&&y(te,null,e.fallback);return i&&(i.__u&=-33),[y(te,null,t.__a?null:e.children),i]};var Rp=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 Bw(e){return this.getChildContext=function(){return e.context},e.children}function Uw(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Ue(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(i,o){this.childNodes.push(i),t.h.insertBefore(i,o)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),t.h.removeChild(i)}}}Ue(y(Bw,{context:t.context},e.__v),t.v)}function en(e,t){var n=y(Uw,{__v:e,h:t});return n.containerInfo=t,n}(Cr.prototype=new _t).__a=function(e){var t=this,n=Ap(t.__v),r=t.l.get(e);return r[0]++,function(i){var o=function(){t.props.revealOrder?(r.push(i),Rp(t,e,r)):i()};n?n(o):o()}},Cr.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},Cr.prototype.componentDidUpdate=Cr.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Rp(e,n,t)})};var Dp=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Gw=/^(?: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]/,Hw=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Kw=/[A-Z0-9]/g,qw=typeof document<"u",Ww=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function Lp(e,t,n){return t.__k??(t.textContent=""),Ue(e,t),typeof n=="function"&&n(),e?e.__c:null}function $p(e,t,n){return up(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 Mp=me.event;me.event=function(e){return Mp&&(e=Mp(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var dc,Vw={configurable:!0,get:function(){return this.class}},Op=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||qw&&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"||Ww(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":Hw.test(s)&&(s=l):l=s="oninput":o&&Gw.test(s)?s=s.replace(Kw,"-$&").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",Vw)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=Dp,Op&&Op(e)};var jp=me.__r;me.__r=function(e){jp&&jp(e),dc=e.__c};var Fp=me.diffed;me.diffed=function(e){Fp&&Fp(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),dc=null};var Bp={ReactCurrentDispatcher:{current:{readContext:function(e){return dc.__n[e.__c].props.value},useCallback:re,useContext:vn,useDebugValue:ec,useDeferredValue:sc,useEffect:K,useId:gi,useImperativeHandle:Lo,useInsertionEffect:lc,useLayoutEffect:gt,useMemo:ke,useReducer:hi,useRef:B,useState:I,useSyncExternalStore:ic,useTransition:cc}}},zw="18.3.1";function Up(e){return y.bind(null,e)}function tn(e){return!!e&&e.$$typeof===Dp}function Gp(e){return tn(e)&&e.type===te}function Hp(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Tr(e){return tn(e)?Dw.apply(null,arguments):e}function Kp(e){return!!e.__k&&(Ue(null,e),!0)}function qp(e){return e&&(e.base||e.nodeType===1&&e)||null}var Wp=function(e,t){return e(t)},jo=function(e,t){var n=me.debounceRendering;me.debounceRendering=function(i){return i()};var r=e(t);return me.debounceRendering=n,r},Vp=tn,nn={useState:I,useId:gi,useReducer:hi,useEffect:K,useLayoutEffect:gt,useInsertionEffect:lc,useTransition:cc,useDeferredValue:sc,useSyncExternalStore:ic,startTransition:ac,useRef:B,useImperativeHandle:Lo,useMemo:ke,useCallback:re,useContext:vn,useDebugValue:ec,version:"18.3.1",Children:Ft,render:Lp,hydrate:$p,unmountComponentAtNode:Kp,createPortal:en,createElement:y,createContext:Un,createFactory:Up,cloneElement:Tr,createRef:np,Fragment:te,isValidElement:tn,isElement:Vp,isFragment:Gp,isMemo:Hp,findDOMNode:qp,Component:_t,PureComponent:Oo,memo:Tp,forwardRef:F,flushSync:jo,unstable_batchedUpdates:Wp,StrictMode:te,Suspense:vi,SuspenseList:Cr,lazy:Ip,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Bp},LO=!!(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 zp(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Fo(...e){return t=>{let n=!1;const r=e.map(i=>{const o=zp(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():zp(e[i],null)}}}}function we(...e){return re(Fo(...e),e)}function Jw(e,t){const n=Un(t),r=o=>{const{children:s,...c}=o,l=ke(()=>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 st(e,t=[]){let n=[];function r(o,s){const c=Un(s),l=n.length;n=[...n,s];const d=p=>{const{scope:m,children:f,...g}=p,h=m?.[e]?.[l]||c,v=ke(()=>g,Object.values(g));return a(h.Provider,{value:v,children:f})};d.displayName=o+"Provider";function u(p,m){const f=m?.[e]?.[l]||c,g=vn(f);if(g)return g;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=>Un(s));return function(c){const l=c?.[e]||o;return ke(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return i.scopeName=e,[r,Yw(i,...t)]}function Yw(...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 ke(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}var We=globalThis?.document?gt:()=>{},Xw=Sp[" useId ".trim().toString()]||(()=>{}),Qw=0;function ct(e){const[t,n]=I(Xw());return We(()=>{e||n(r=>r??String(Qw++))},[e]),e||(t?`radix-${t}`:"")}var Zw=Sp[" useInsertionEffect ".trim().toString()]||We;function wt({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,o,s]=eS({defaultProp:t,onChange:n}),c=e!==void 0,l=c?e:i;{const d=B(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=tS(d)?d(e):d;u!==e&&s.current?.(u)}else o(d)},[c,e,o,s])]}function eS({defaultProp:e,onChange:t}){const[n,r]=I(e),i=B(n),o=B(t);return Zw(()=>{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 Hn(e){const t=nS(e),n=F((r,i)=>{const{children:o,...s}=r,c=Ft.toArray(o),l=c.find(iS);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 nS(e){const t=F((n,r)=>{const{children:i,...o}=n;if(tn(i)){const s=aS(i),c=oS(o,i.props);return i.type!==te&&(c.ref=r?Fo(r,s):s),Tr(i,c)}return Ft.count(i)>1?Ft.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Jp=Symbol("radix.slottable");function rS(e){const t=({children:n})=>a(te,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=Jp,t}function iS(e){return tn(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Jp}function oS(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=Hn(`Primitive.${t}`),r=F((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 uc(e,t){e&&jo(()=>e.dispatchEvent(t))}function lt(e){const t=B(e);return K(()=>{t.current=e}),ke(()=>(...n)=>t.current?.(...n),[])}function sS(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 cS="DismissableLayer",pc="dismissableLayer.update",lS="dismissableLayer.pointerDownOutside",dS="dismissableLayer.focusOutside",Yp,Xp=Un({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Kn=F((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:s,onDismiss:c,...l}=e,d=vn(Xp),[u,p]=I(null),m=u?.ownerDocument??globalThis?.document,[,f]=I({}),g=we(t,A=>p(A)),h=Array.from(d.layers),[v]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),b=h.indexOf(v),w=u?h.indexOf(u):-1,S=d.layersWithOutsidePointerEventsDisabled.size>0,T=w>=b,N=pS(A=>{const M=A.target,U=[...d.branches].some(x=>x.contains(M));!T||U||(i?.(A),s?.(A),A.defaultPrevented||c?.())},m),P=mS(A=>{const M=A.target;[...d.branches].some(U=>U.contains(M))||(o?.(A),s?.(A),A.defaultPrevented||c?.())},m);return sS(A=>{w===d.layers.size-1&&(r?.(A),!A.defaultPrevented&&c&&(A.preventDefault(),c()))},m),K(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Yp=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=Yp)}},[u,m,n,d]),K(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),Zp())},[u,d]),K(()=>{const A=()=>f({});return document.addEventListener(pc,A),()=>document.removeEventListener(pc,A)},[]),a(se.div,{...l,ref:g,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,N.onPointerDownCapture)})});Kn.displayName=cS;var uS="DismissableLayerBranch",Qp=F((e,t)=>{const n=vn(Xp),r=B(null),i=we(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=uS;function pS(e,t=globalThis?.document){const n=lt(e),r=B(!1),i=B(()=>{});return K(()=>{const o=c=>{if(c.target&&!r.current){let l=function(){em(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 mS(e,t=globalThis?.document){const n=lt(e),r=B(!1);return K(()=>{const i=o=>{o.target&&!r.current&&em(dS,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(pc);document.dispatchEvent(e)}function em(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?uc(i,o):i.dispatchEvent(o)}var fS=Kn,hS=Qp,mc="focusScope.autoFocusOnMount",fc="focusScope.autoFocusOnUnmount",tm={bubbles:!1,cancelable:!0},gS="FocusScope",yi=F((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=B(null),m=we(t,h=>l(h)),f=B({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:yn(p.current,{select:!0})},v=function(S){if(f.paused||!c)return;const T=S.relatedTarget;T!==null&&(c.contains(T)||yn(p.current,{select:!0}))},b=function(S){if(document.activeElement===document.body)for(const T of S)T.removedNodes.length>0&&yn(c)};document.addEventListener("focusin",h),document.addEventListener("focusout",v);const w=new MutationObserver(b);return c&&w.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",v),w.disconnect()}}},[r,c,f.paused]),K(()=>{if(c){im.add(f);const h=document.activeElement;if(!c.contains(h)){const v=new CustomEvent(mc,tm);c.addEventListener(mc,d),c.dispatchEvent(v),v.defaultPrevented||(vS(SS(nm(c)),{select:!0}),document.activeElement===h&&yn(c))}return()=>{c.removeEventListener(mc,d),setTimeout(()=>{const v=new CustomEvent(fc,tm);c.addEventListener(fc,u),c.dispatchEvent(v),v.defaultPrevented||yn(h??document.body,{select:!0}),c.removeEventListener(fc,u),im.remove(f)},0)}}},[c,d,u,f]);const g=re(h=>{if(!n&&!r||f.paused)return;const v=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,b=document.activeElement;if(v&&b){const w=h.currentTarget,[S,T]=yS(w);S&&T?!h.shiftKey&&b===T?(h.preventDefault(),n&&yn(S,{select:!0})):h.shiftKey&&b===S&&(h.preventDefault(),n&&yn(T,{select:!0})):b===w&&h.preventDefault()}},[n,r,f.paused]);return a(se.div,{tabIndex:-1,...s,ref:m,onKeyDown:g})});yi.displayName=gS;function vS(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(yn(r,{select:t}),document.activeElement!==n)return}function yS(e){const t=nm(e);return[rm(t,e),rm(t.reverse(),e)]}function nm(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 rm(e,t){for(const n of e)if(!bS(n,{upTo:t}))return n}function bS(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 _S(e){return e instanceof HTMLInputElement&&"select"in e}function yn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&_S(e)&&t&&e.select()}}var im=wS();function wS(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=om(e,t),e.unshift(t)},remove(t){e=om(e,t),e[0]?.resume()}}}function om(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function SS(e){return e.filter(t=>t.tagName!=="A")}var CS="Portal",qn=F((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});qn.displayName=CS;function TS(e,t){return hi((n,r)=>t[n][r]??n,e)}var nt=e=>{const{present:t,children:n}=e,r=NS(t),i=typeof n=="function"?n({present:r.isPresent}):Ft.only(n),o=we(r.ref,kS(i));return typeof n=="function"||r.isPresent?Tr(i,{ref:o}):null};nt.displayName="Presence";function NS(e){const[t,n]=I(),r=B(null),i=B(e),o=B("none"),[s,c]=TS(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return K(()=>{const l=Bo(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=Bo(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=Bo(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&f&&(c("ANIMATION_END"),!i.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",l=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},p=m=>{m.target===t&&(o.current=Bo(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 Bo(e){return e?.animationName||"none"}function kS(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 hc=0;function Uo(){K(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??am()),document.body.insertAdjacentElement("beforeend",e[1]??am()),hc++,()=>{hc===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),hc--}},[])}function am(){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 sm(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 xS(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 Go="right-scroll-bar-position",Ho="width-before-scroll-bar",PS="with-scroll-bars-hidden",ES="--removed-body-scroll-bar-size";function gc(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function AS(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 IS=typeof window<"u"?gt:K,cm=new WeakMap;function RS(e,t){var n=AS(t||null,function(r){return e.forEach(function(i){return gc(i,r)})});return IS(function(){var r=cm.get(n);if(r){var i=new Set(r),o=new Set(e),s=n.current;i.forEach(function(c){o.has(c)||gc(c,null)}),o.forEach(function(c){i.has(c)||gc(c,s)})}cm.set(n,e)},[e]),n}function DS(e){return e}function LS(e,t){t===void 0&&(t=DS);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 $S(e){e===void 0&&(e={});var t=LS(null);return t.options=Bt({async:!0,ssr:!1},e),t}var lm=function(e){var t=e.sideCar,n=sm(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,Bt({},n))};lm.isSideCarExport=!0;function MS(e,t){return e.useMedium(t),lm}var dm=$S(),vc=function(){},Ko=F(function(e,t){var n=B(null),r=I({onScrollCapture:vc,onWheelCapture:vc,onTouchMoveCapture:vc}),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,g=e.noIsolation,h=e.inert,v=e.allowPinchZoom,b=e.as,w=b===void 0?"div":b,S=e.gapMode,T=sm(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),N=m,P=RS([n,t]),A=Bt(Bt({},T),i);return y(te,null,u&&y(N,{sideCar:dm,removeScrollBar:d,shards:p,noRelative:f,noIsolation:g,inert:h,setCallbacks:o,allowPinchZoom:!!v,lockRef:n,gapMode:S}),s?Tr(Ft.only(c),Bt(Bt({},A),{ref:P})):y(w,Bt({},A,{className:l,ref:P}),c))});Ko.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Ko.classNames={fullWidth:Ho,zeroRight:Go};var um,OS=function(){if(um)return um;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function jS(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=OS();return t&&e.setAttribute("nonce",t),e}function FS(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function BS(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var US=function(){var e=0,t=null;return{add:function(n){e==0&&(t=jS())&&(FS(t,n),BS(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},GS=function(){var e=US();return function(t,n){K(function(){return e.add(t),function(){e.remove()}},[t&&n])}},pm=function(){var e=GS(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},HS={left:0,top:0,right:0,gap:0},yc=function(e){return parseInt(e||"",10)||0},KS=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[yc(n),yc(r),yc(i)]},qS=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return HS;var t=KS(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])}},WS=pm(),bi="data-scroll-locked",VS=function(e,t,n,r){var i=e.left,o=e.top,s=e.right,c=e.gap;return n===void 0&&(n="margin"),`
|
|
1
|
+
(function(){var Iu=Object.defineProperty,T_=(e,t)=>{let n={};for(var r in e)Iu(n,r,{get:e[r],enumerable:!0});return t||Iu(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 Le(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 Ru(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 N_(){return Le("/api/observer-status")}async function k_(){return Le("/api/config")}async function x_(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 No(){return Le("/api/coordinator/admin/status")}async function Du(e){return Le(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`)}async function P_(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 E_(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 A_(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 I_(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 R_(e,t=!1){const n=new URLSearchParams;t&&n.set("include_inactive","1");const r=n.size?`?${n.toString()}`:"";return Le(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes${r}`)}async function D_(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 L_(e,t,n=!1){const r=new URLSearchParams;n&&r.set("include_revoked","1");const i=r.size?`?${r.toString()}`:"";return Le(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members${i}`)}async function $_(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 M_(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 O_(e){const t=new URLSearchParams;return e&&t.set("group_id",e),Le(`/api/coordinator/admin/join-requests${t.size?`?${t.toString()}`:""}`)}async function Lu(e,t=!0){const n=new URLSearchParams;return e&&n.set("group_id",e),t&&n.set("include_disabled","1"),Le(`/api/coordinator/admin/devices${n.size?`?${n.toString()}`:""}`)}async function j_(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 F_(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 B_(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 U_(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 G_(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 $u(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 Mu(e,t){return Le(`/api/observations?${Ru(e,t?.limit,t?.offset,t?.scope)}`)}async function H_(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 K_(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 q_(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 Ou(e,t){return Le(`/api/summaries?${Ru(e,t?.limit,t?.offset,t?.scope)}`)}async function V_(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 W_(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 z_(){return Le("/api/runtime")}async function ko(){return(await Le("/api/projects")).projects||[]}async function J_(){return Le("/api/stats")}async function Y_(e){return Le(`/api/usage?project=${encodeURIComponent(e)}`)}async function X_(e){return Le(`/api/session?project=${encodeURIComponent(e)}`)}async function Q_(e){return Le(`/api/raw-events?project=${encodeURIComponent(e)}`)}async function Fs(e,t="",n){const r=new URLSearchParams;return e&&r.set("includeDiagnostics","1"),t&&r.set("project",t),n?.includeJoinRequests&&r.set("includeJoinRequests","1"),Le(`/api/sync/status${r.size?`?${r.toString()}`:""}`)}async function Bs(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 ju(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 Le("/api/sync/actors")}async function ew(e=!1){return Le(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`)}async function tw(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 Fu(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 Bu(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 nw(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 Uu=class extends Error{preview;constructor(e){super("Project forget confirmation required"),this.name="ProjectForgetConfirmationError",this.preview=e}},xo=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??[]}},Gu=class extends Error{preview;constructor(e){super("Legacy shared review confirmation required"),this.name="LegacySharedReviewConfirmationError",this.preview=e}},Hu=class extends Error{result;constructor(e){super("Recipient policy review source state changed"),this.name="RecipientPolicyReviewStaleError",this.result=e}},Us=class extends Error{result;constructor(e){super("Recipient policy changed after review"),this.name="RecipientPolicyEdgesStaleError",this.result=e}};function Gs(){return Le("/api/sync/recipient-policy/v1/intent")}function rw(){return Le("/api/sync/recipient-policy/v1/reconciliation-status")}async function Ku(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 Us(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 iw(e){return Ku("/api/sync/recipient-policy/v1/edges/preview",e)}function ow(e){return Ku("/api/sync/recipient-policy/v1/edges/commit",e)}async function qu(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 aw(e){return qu("/api/sync/recipient-policy/v1/invites/preview",e)}function sw(e){return qu("/api/sync/recipient-policy/v1/invites",e)}function cw(){return Le("/api/sync/recipient-policy/v1/review")}async function lw(e){const t=await fetch("/api/sync/recipient-policy/v1/review/resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await ye(t);if(!t.ok)throw t.status===409&&r?.status==="stale"?new Hu(r):new Error(ve(r)||n||"request failed");return r}async function dw(){return Le("/api/sync/sharing-domains/settings")}async function Po(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 Le(`/api/sync/projects${n?`?${n}`:""}`)}async function Vu(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 uw(e){return Vu("/api/sync/project-invites/preview",e)}function pw(e){return Vu("/api/sync/project-invites",e)}function Wu(){return Le("/api/sync/share-operations")}function mw(e){return Le(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function fw(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 hw(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 xo(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 gw(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 xo(r):new Error(ve(r)||n||"request failed");if(!Array.isArray(r?.mappings))throw new Error("response missing mappings");return r.mappings}async function vw(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 yw(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 bw(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 Uu(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 _w(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 Gu(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 ww(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 Sw(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 Cw(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 Tw(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 zu(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 Nw(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 kw(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 Hs(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}var ui,me,Ju,Yu,gn,Xu,Qu,Zu,Ks,Eo,pi,ep,qs,Vs,Ws,tp,Ao={},Io=[],xw=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,mi=Array.isArray;function jt(e,t){for(var n in t)e[n]=t[n];return e}function zs(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?ui.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 fi(e,s,r,i,null)}function fi(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??++Ju,__i:-1,__u:0};return i==null&&me.vnode!=null&&me.vnode(o),o}function np(){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 Pw(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],i=[],o=jt({},t);o.__v=t.__v+1,me.vnode&&me.vnode(o),Ys(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,cp(r,o,i),t.__e=t.__=null,o.__e!=n&&rp(o)}}function rp(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}),rp(e)}function Js(e){(!e.__d&&(e.__d=!0)&&gn.push(e)&&!Ro.__r++||Xu!=me.debounceRendering)&&((Xu=me.debounceRendering)||Qu)(Ro)}function Ro(){try{for(var e,t=1;gn.length;)gn.length>t&&gn.sort(Zu),e=gn.shift(),t=gn.length,Pw(e)}finally{gn.length=Ro.__r=0}}function ip(e,t,n,r,i,o,s,c,l,d,u){var p,m,f,g,h,v,b,w=r&&r.__k||Io,S=t.length;for(l=Ew(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,v=Ys(e,f,m,i,o,s,c,l,d,u),g=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&Qs(m.ref,null,f),u.push(f.ref,f.__c||g,f)),h==null&&g!=null&&(h=g),(b=!!(4&f.__u))||m.__k===f.__k?(l=op(f,l,e,b),b&&m.__e&&(m.__e=null)):typeof f.type=="function"&&v!==void 0?l=v:g&&(l=g.nextSibling),f.__u&=-7);return n.__e=h,l}function Ew(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]=fi(null,s,null,null,null):mi(s)?s=e.__k[o]=fi(te,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[o]=fi(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=Aw(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)),dp(c,c));return r}function op(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=op(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 Qt(e,t){return t=t||[],e==null||typeof e=="boolean"||(mi(e)?e.some(function(n){Qt(n,t)}):t.push(e)),t}function Aw(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 ap(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||xw.test(t)?n:n+"px"}function Do(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||ap(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||ap(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(ep,"$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[pi]=r[pi]:(n[pi]=qs,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 sp(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Eo]==null)t[Eo]=qs++;else if(t[Eo]<n[pi])return;return n(me.event?me.event(t):t)}}}function Ys(e,t,n,r,i,o,s,c,l,d){var u,p,m,f,g,h,v,b,w,S,T,N,P,A,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=me.__b)&&u(t);e:if(typeof U=="function")try{if(b=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?v=(p=t.__c=n.__c).__=p.__E:(w?t.__c=p=new U(b,T):(t.__c=p=new _t(b,T),p.constructor=U,p.render=Rw),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(b,p.__s))),f=p.props,g=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&&b!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(b,T),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(b,p.__s,T)===!1){t.__v!=n.__v&&(p.props=b,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(x){x&&(x.__=t)}),Io.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(b,p.__s,T),w&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,g,h)})}if(p.context=T,p.props=b,p.__P=e,p.__e=!1,N=me.__r,P=0,w)p.state=p.__s,p.__d=!1,N&&N(t),u=p.render(p.props,p.state,p.context),Io.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,N&&N(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,g)),A=u!=null&&u.type===te&&u.key==null?lp(u.props.children):u,c=ip(e,mi(A)?A:[A],t,n,r,i,o,s,c,l,d),p.base=t.__e,t.__u&=-161,p.__h.length&&s.push(p),v&&(p.__E=p.__=null)}catch(x){if(t.__v=null,l||o!=null)if(x.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--;)zs(o[M]);Xs(t)}else t.__e=n.__e,t.__k=n.__k,x.then||Xs(t);me.__e(x,t,n)}else o==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=Iw(n.__e,t,n,r,i,o,s,l,d);return(u=me.diffed)&&u(t),128&t.__u?void 0:c}function Xs(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Xs))}function cp(e,t,n){for(var r=0;r<n.length;r++)Qs(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 lp(e){return typeof e!="object"||e==null||e.__b>0?e:mi(e)?e.map(lp):e.constructor!==void 0?null:jt({},e)}function Iw(e,t,n,r,i,o,s,c,l){var d,u,p,m,f,g,h,v=n.props||Ao,b=t.props,w=t.type;if(w=="svg"?i="http://www.w3.org/2000/svg":w=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),o!=null){for(d=0;d<o.length;d++)if((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(b);e=document.createElementNS(i,w,b.is&&b),c&&(me.__m&&me.__m(t,o),c=!1),o=null}if(w==null)v===b||c&&e.data==b||(e.data=b);else{if(o=w=="textarea"&&b.defaultValue!=null?null:o&&ui.call(e.childNodes),!c&&o!=null)for(v={},d=0;d<e.attributes.length;d++)v[(f=e.attributes[d]).name]=f.value;for(d in v)f=v[d],d=="dangerouslySetInnerHTML"?p=f:d=="children"||d in b||d=="value"&&"defaultValue"in b||d=="checked"&&"defaultChecked"in b||Do(e,d,null,f,i);for(d in b)f=b[d],d=="children"?m=f:d=="dangerouslySetInnerHTML"?u=f:d=="value"?g=f:d=="checked"?h=f:c&&typeof f!="function"||v[d]===f||Do(e,d,f,v[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=""),ip(t.type=="template"?e.content:e,mi(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--;)zs(o[d]);c&&w!="textarea"||(d="value",w=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[d]||w=="progress"&&!g||w=="option"&&g!=v[d])&&Do(e,d,g,v[d],i),d="checked",h!=null&&h!=e[d]&&Do(e,d,h,v[d],i))}return e}function Qs(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 dp(e,t,n){var r,i;if(me.unmount&&me.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Qs(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]&&dp(r[i],t,n||typeof e.type!="function");n||zs(e.__e),e.__c=e.__=e.__e=void 0}function Rw(e,t,n){return this.constructor(e,n)}function Ue(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=[],Ys(t,e=(!r&&n||t).__k=y(te,null,[e]),i||Ao,Ao,t.namespaceURI,!r&&n?[n]:i?null:t.firstChild?ui.call(t.childNodes):null,o,!r&&n?n:i?i.__e:t.firstChild,r,s),cp(o,e,s)}function up(e,t){Ue(e,t,up)}function Dw(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?ui.call(arguments,2):n),fi(e.type,c,r||e.key,i||e.ref,null)}function Un(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,Js(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"+tp++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}ui=Io.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}},Ju=0,Yu=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),Js(this))},_t.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Js(this))},_t.prototype.render=te,gn=[],Qu=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Zu=function(e,t){return e.__v.__b-t.__v.__b},Ro.__r=0,Ks=Math.random().toString(8),Eo="__d"+Ks,pi="__a"+Ks,ep=/(PointerCapture)$|Capture$/i,qs=0,Vs=sp(!1),Ws=sp(!0),tp=0;var Zt,Re,Zs,pp,Sr=0,mp=[],Fe=me,fp=Fe.__b,hp=Fe.__r,gp=Fe.diffed,vp=Fe.__c,yp=Fe.unmount,bp=Fe.__;function Gn(e,t){Fe.__h&&Fe.__h(Re,e,Sr||t),Sr=0;var n=Re.__H||(Re.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function I(e){return Sr=1,hi(wp,e)}function hi(e,t,n){var r=Gn(Zt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):wp(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=Re,!Re.__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};Re.__f=!0;var o=Re.shouldComponentUpdate,s=Re.componentWillUpdate;Re.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)},Re.shouldComponentUpdate=i}return r.__N||r.__}function K(e,t){var n=Gn(Zt++,3);!Fe.__s&&nc(n.__H,t)&&(n.__=e,n.u=t,Re.__H.__h.push(n))}function gt(e,t){var n=Gn(Zt++,4);!Fe.__s&&nc(n.__H,t)&&(n.__=e,n.u=t,Re.__h.push(n))}function B(e){return Sr=5,xe(function(){return{current:e}},[])}function Lo(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 xe(e,t){var n=Gn(Zt++,7);return nc(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function re(e,t){return Sr=8,xe(function(){return e},t)}function vn(e){var t=Re.context[e.__c],n=Gn(Zt++,9);return n.c=e,t?(n.__??(n.__=!0,t.sub(Re)),t.props.value):e.__}function ec(e,t){Fe.useDebugValue&&Fe.useDebugValue(t?t(e):e)}function Lw(e){var t=Gn(Zt++,10),n=I();return t.__=e,Re.componentDidCatch||(Re.componentDidCatch=function(r,i){t.__&&t.__(r,i),n[1](r)}),[n[0],function(){n[1](void 0)}]}function gi(){var e=Gn(Zt++,11);if(!e.__){for(var t=Re.__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 $w(){for(var e;e=mp.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some($o),t.__h.some(tc),t.__h=[]}catch(n){t.__h=[],Fe.__e(n,e.__v)}}}Fe.__b=function(e){Re=null,fp&&fp(e)},Fe.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),bp&&bp(e,t)},Fe.__r=function(e){hp&&hp(e),Zt=0;var t=(Re=e.__c).__H;t&&(Zs===Re?(t.__h=[],Re.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some($o),t.__h.some(tc),t.__h=[],Zt=0)),Zs=Re},Fe.diffed=function(e){gp&&gp(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(mp.push(t)!==1&&pp===Fe.requestAnimationFrame||((pp=Fe.requestAnimationFrame)||Mw)($w)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Zs=Re=null},Fe.__c=function(e,t){t.some(function(n){try{n.__h.some($o),n.__h=n.__h.filter(function(r){return!r.__||tc(r)})}catch(r){t.some(function(i){i.__h&&(i.__h=[])}),t=[],Fe.__e(r,n.__v)}}),vp&&vp(e,t)},Fe.unmount=function(e){yp&&yp(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{$o(r)}catch(i){t=i}}),n.__H=void 0,t&&Fe.__e(t,n.__v))};var _p=typeof requestAnimationFrame=="function";function Mw(e){var t,n=function(){clearTimeout(r),_p&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);_p&&(t=requestAnimationFrame(n))}function $o(e){var t=Re,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Re=t}function tc(e){var t=Re;e.__c=e.__(),Re=t}function nc(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function wp(e,t){return typeof t=="function"?t(e):t}var RO=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ow=0,DO=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:--Ow,__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 Mo({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 Sp=T_({Children:()=>Ft,Component:()=>_t,Fragment:()=>te,PureComponent:()=>Oo,StrictMode:()=>te,Suspense:()=>vi,SuspenseList:()=>Cr,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>Bp,cloneElement:()=>Tr,createContext:()=>Un,createElement:()=>y,createFactory:()=>Up,createPortal:()=>en,createRef:()=>np,default:()=>nn,findDOMNode:()=>qp,flushSync:()=>jo,forwardRef:()=>F,hydrate:()=>$p,isElement:()=>Wp,isFragment:()=>Gp,isMemo:()=>Hp,isValidElement:()=>tn,lazy:()=>Ip,memo:()=>Tp,render:()=>Lp,startTransition:()=>ac,unmountComponentAtNode:()=>Kp,unstable_batchedUpdates:()=>Vp,useCallback:()=>re,useContext:()=>vn,useDebugValue:()=>ec,useDeferredValue:()=>sc,useEffect:()=>K,useErrorBoundary:()=>Lw,useId:()=>gi,useImperativeHandle:()=>Lo,useInsertionEffect:()=>lc,useLayoutEffect:()=>gt,useMemo:()=>xe,useReducer:()=>hi,useRef:()=>B,useState:()=>I,useSyncExternalStore:()=>ic,useTransition:()=>cc,version:()=>zw});function Cp(e,t){for(var n in t)e[n]=t[n];return e}function rc(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 ic(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,oc(i)&&o({t:i})},[e,n,t]),K(function(){return oc(i)&&o({t:i}),e(function(){oc(i)&&o({t:i})})},[e]),n}function oc(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 ac(e){e()}function sc(e){return e}function cc(){return[!1,ac]}var lc=gt;function Oo(e,t){this.props=e,this.context=t}function Tp(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:rc(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}(Oo.prototype=new _t).isPureReactComponent=!0,Oo.prototype.shouldComponentUpdate=function(e,t){return rc(this.props,e)||rc(this.state,t)};var Np=me.__b;me.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Np&&Np(e)};var jw=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function F(e){function t(n){var r=Cp({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=jw,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var kp=function(e,t){return e==null?null:Qt(Qt(e).map(t))},Ft={map:kp,forEach:kp,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},Fw=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)}Fw(e,t,n,r)};var xp=me.unmount;function Pp(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=Cp({},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 Pp(r,t,n)})),e}function Ep(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Ep(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 vi(){this.__u=0,this.o=null,this.__b=null}function Ap(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Ip(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 Cr(){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),xp&&xp(e)},(vi.prototype=new _t).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=Ap(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]=Ep(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)},vi.prototype.componentWillUnmount=function(){this.o=[]},vi.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]=Pp(this.__b,n,r.__O=r.__P)}this.__b=null}var i=t.__a&&y(te,null,e.fallback);return i&&(i.__u&=-33),[y(te,null,t.__a?null:e.children),i]};var Rp=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 Bw(e){return this.getChildContext=function(){return e.context},e.children}function Uw(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Ue(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(i,o){this.childNodes.push(i),t.h.insertBefore(i,o)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),t.h.removeChild(i)}}}Ue(y(Bw,{context:t.context},e.__v),t.v)}function en(e,t){var n=y(Uw,{__v:e,h:t});return n.containerInfo=t,n}(Cr.prototype=new _t).__a=function(e){var t=this,n=Ap(t.__v),r=t.l.get(e);return r[0]++,function(i){var o=function(){t.props.revealOrder?(r.push(i),Rp(t,e,r)):i()};n?n(o):o()}},Cr.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},Cr.prototype.componentDidUpdate=Cr.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Rp(e,n,t)})};var Dp=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Gw=/^(?: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]/,Hw=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Kw=/[A-Z0-9]/g,qw=typeof document<"u",Vw=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function Lp(e,t,n){return t.__k??(t.textContent=""),Ue(e,t),typeof n=="function"&&n(),e?e.__c:null}function $p(e,t,n){return up(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 Mp=me.event;me.event=function(e){return Mp&&(e=Mp(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var dc,Ww={configurable:!0,get:function(){return this.class}},Op=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||qw&&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"||Vw(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":Hw.test(s)&&(s=l):l=s="oninput":o&&Gw.test(s)?s=s.replace(Kw,"-$&").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",Ww)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=Dp,Op&&Op(e)};var jp=me.__r;me.__r=function(e){jp&&jp(e),dc=e.__c};var Fp=me.diffed;me.diffed=function(e){Fp&&Fp(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),dc=null};var Bp={ReactCurrentDispatcher:{current:{readContext:function(e){return dc.__n[e.__c].props.value},useCallback:re,useContext:vn,useDebugValue:ec,useDeferredValue:sc,useEffect:K,useId:gi,useImperativeHandle:Lo,useInsertionEffect:lc,useLayoutEffect:gt,useMemo:xe,useReducer:hi,useRef:B,useState:I,useSyncExternalStore:ic,useTransition:cc}}},zw="18.3.1";function Up(e){return y.bind(null,e)}function tn(e){return!!e&&e.$$typeof===Dp}function Gp(e){return tn(e)&&e.type===te}function Hp(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Tr(e){return tn(e)?Dw.apply(null,arguments):e}function Kp(e){return!!e.__k&&(Ue(null,e),!0)}function qp(e){return e&&(e.base||e.nodeType===1&&e)||null}var Vp=function(e,t){return e(t)},jo=function(e,t){var n=me.debounceRendering;me.debounceRendering=function(i){return i()};var r=e(t);return me.debounceRendering=n,r},Wp=tn,nn={useState:I,useId:gi,useReducer:hi,useEffect:K,useLayoutEffect:gt,useInsertionEffect:lc,useTransition:cc,useDeferredValue:sc,useSyncExternalStore:ic,startTransition:ac,useRef:B,useImperativeHandle:Lo,useMemo:xe,useCallback:re,useContext:vn,useDebugValue:ec,version:"18.3.1",Children:Ft,render:Lp,hydrate:$p,unmountComponentAtNode:Kp,createPortal:en,createElement:y,createContext:Un,createFactory:Up,cloneElement:Tr,createRef:np,Fragment:te,isValidElement:tn,isElement:Wp,isFragment:Gp,isMemo:Hp,findDOMNode:qp,Component:_t,PureComponent:Oo,memo:Tp,forwardRef:F,flushSync:jo,unstable_batchedUpdates:Vp,StrictMode:te,Suspense:vi,SuspenseList:Cr,lazy:Ip,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Bp},LO=!!(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 zp(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Fo(...e){return t=>{let n=!1;const r=e.map(i=>{const o=zp(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():zp(e[i],null)}}}}function we(...e){return re(Fo(...e),e)}function Jw(e,t){const n=Un(t),r=o=>{const{children:s,...c}=o,l=xe(()=>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 st(e,t=[]){let n=[];function r(o,s){const c=Un(s),l=n.length;n=[...n,s];const d=p=>{const{scope:m,children:f,...g}=p,h=m?.[e]?.[l]||c,v=xe(()=>g,Object.values(g));return a(h.Provider,{value:v,children:f})};d.displayName=o+"Provider";function u(p,m){const f=m?.[e]?.[l]||c,g=vn(f);if(g)return g;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=>Un(s));return function(c){const l=c?.[e]||o;return xe(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return i.scopeName=e,[r,Yw(i,...t)]}function Yw(...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 xe(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}var Ve=globalThis?.document?gt:()=>{},Xw=Sp[" useId ".trim().toString()]||(()=>{}),Qw=0;function ct(e){const[t,n]=I(Xw());return Ve(()=>{e||n(r=>r??String(Qw++))},[e]),e||(t?`radix-${t}`:"")}var Zw=Sp[" useInsertionEffect ".trim().toString()]||Ve;function wt({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,o,s]=eS({defaultProp:t,onChange:n}),c=e!==void 0,l=c?e:i;{const d=B(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=tS(d)?d(e):d;u!==e&&s.current?.(u)}else o(d)},[c,e,o,s])]}function eS({defaultProp:e,onChange:t}){const[n,r]=I(e),i=B(n),o=B(t);return Zw(()=>{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 Hn(e){const t=nS(e),n=F((r,i)=>{const{children:o,...s}=r,c=Ft.toArray(o),l=c.find(iS);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 nS(e){const t=F((n,r)=>{const{children:i,...o}=n;if(tn(i)){const s=aS(i),c=oS(o,i.props);return i.type!==te&&(c.ref=r?Fo(r,s):s),Tr(i,c)}return Ft.count(i)>1?Ft.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Jp=Symbol("radix.slottable");function rS(e){const t=({children:n})=>a(te,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=Jp,t}function iS(e){return tn(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Jp}function oS(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=Hn(`Primitive.${t}`),r=F((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 uc(e,t){e&&jo(()=>e.dispatchEvent(t))}function lt(e){const t=B(e);return K(()=>{t.current=e}),xe(()=>(...n)=>t.current?.(...n),[])}function sS(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 cS="DismissableLayer",pc="dismissableLayer.update",lS="dismissableLayer.pointerDownOutside",dS="dismissableLayer.focusOutside",Yp,Xp=Un({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Kn=F((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:s,onDismiss:c,...l}=e,d=vn(Xp),[u,p]=I(null),m=u?.ownerDocument??globalThis?.document,[,f]=I({}),g=we(t,A=>p(A)),h=Array.from(d.layers),[v]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),b=h.indexOf(v),w=u?h.indexOf(u):-1,S=d.layersWithOutsidePointerEventsDisabled.size>0,T=w>=b,N=pS(A=>{const M=A.target,U=[...d.branches].some(x=>x.contains(M));!T||U||(i?.(A),s?.(A),A.defaultPrevented||c?.())},m),P=mS(A=>{const M=A.target;[...d.branches].some(U=>U.contains(M))||(o?.(A),s?.(A),A.defaultPrevented||c?.())},m);return sS(A=>{w===d.layers.size-1&&(r?.(A),!A.defaultPrevented&&c&&(A.preventDefault(),c()))},m),K(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Yp=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=Yp)}},[u,m,n,d]),K(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),Zp())},[u,d]),K(()=>{const A=()=>f({});return document.addEventListener(pc,A),()=>document.removeEventListener(pc,A)},[]),a(se.div,{...l,ref:g,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,N.onPointerDownCapture)})});Kn.displayName=cS;var uS="DismissableLayerBranch",Qp=F((e,t)=>{const n=vn(Xp),r=B(null),i=we(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=uS;function pS(e,t=globalThis?.document){const n=lt(e),r=B(!1),i=B(()=>{});return K(()=>{const o=c=>{if(c.target&&!r.current){let l=function(){em(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 mS(e,t=globalThis?.document){const n=lt(e),r=B(!1);return K(()=>{const i=o=>{o.target&&!r.current&&em(dS,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(pc);document.dispatchEvent(e)}function em(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?uc(i,o):i.dispatchEvent(o)}var fS=Kn,hS=Qp,mc="focusScope.autoFocusOnMount",fc="focusScope.autoFocusOnUnmount",tm={bubbles:!1,cancelable:!0},gS="FocusScope",yi=F((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=B(null),m=we(t,h=>l(h)),f=B({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:yn(p.current,{select:!0})},v=function(S){if(f.paused||!c)return;const T=S.relatedTarget;T!==null&&(c.contains(T)||yn(p.current,{select:!0}))},b=function(S){if(document.activeElement===document.body)for(const T of S)T.removedNodes.length>0&&yn(c)};document.addEventListener("focusin",h),document.addEventListener("focusout",v);const w=new MutationObserver(b);return c&&w.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",v),w.disconnect()}}},[r,c,f.paused]),K(()=>{if(c){im.add(f);const h=document.activeElement;if(!c.contains(h)){const v=new CustomEvent(mc,tm);c.addEventListener(mc,d),c.dispatchEvent(v),v.defaultPrevented||(vS(SS(nm(c)),{select:!0}),document.activeElement===h&&yn(c))}return()=>{c.removeEventListener(mc,d),setTimeout(()=>{const v=new CustomEvent(fc,tm);c.addEventListener(fc,u),c.dispatchEvent(v),v.defaultPrevented||yn(h??document.body,{select:!0}),c.removeEventListener(fc,u),im.remove(f)},0)}}},[c,d,u,f]);const g=re(h=>{if(!n&&!r||f.paused)return;const v=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,b=document.activeElement;if(v&&b){const w=h.currentTarget,[S,T]=yS(w);S&&T?!h.shiftKey&&b===T?(h.preventDefault(),n&&yn(S,{select:!0})):h.shiftKey&&b===S&&(h.preventDefault(),n&&yn(T,{select:!0})):b===w&&h.preventDefault()}},[n,r,f.paused]);return a(se.div,{tabIndex:-1,...s,ref:m,onKeyDown:g})});yi.displayName=gS;function vS(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(yn(r,{select:t}),document.activeElement!==n)return}function yS(e){const t=nm(e);return[rm(t,e),rm(t.reverse(),e)]}function nm(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 rm(e,t){for(const n of e)if(!bS(n,{upTo:t}))return n}function bS(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 _S(e){return e instanceof HTMLInputElement&&"select"in e}function yn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&_S(e)&&t&&e.select()}}var im=wS();function wS(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=om(e,t),e.unshift(t)},remove(t){e=om(e,t),e[0]?.resume()}}}function om(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function SS(e){return e.filter(t=>t.tagName!=="A")}var CS="Portal",qn=F((e,t)=>{const{container:n,...r}=e,[i,o]=I(!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=CS;function TS(e,t){return hi((n,r)=>t[n][r]??n,e)}var rt=e=>{const{present:t,children:n}=e,r=NS(t),i=typeof n=="function"?n({present:r.isPresent}):Ft.only(n),o=we(r.ref,kS(i));return typeof n=="function"||r.isPresent?Tr(i,{ref:o}):null};rt.displayName="Presence";function NS(e){const[t,n]=I(),r=B(null),i=B(e),o=B("none"),[s,c]=TS(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return K(()=>{const l=Bo(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=Bo(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=m=>{const f=Bo(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&f&&(c("ANIMATION_END"),!i.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",l=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},p=m=>{m.target===t&&(o.current=Bo(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 Bo(e){return e?.animationName||"none"}function kS(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 hc=0;function Uo(){K(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??am()),document.body.insertAdjacentElement("beforeend",e[1]??am()),hc++,()=>{hc===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),hc--}},[])}function am(){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 sm(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 xS(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 Go="right-scroll-bar-position",Ho="width-before-scroll-bar",PS="with-scroll-bars-hidden",ES="--removed-body-scroll-bar-size";function gc(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function AS(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 IS=typeof window<"u"?gt:K,cm=new WeakMap;function RS(e,t){var n=AS(t||null,function(r){return e.forEach(function(i){return gc(i,r)})});return IS(function(){var r=cm.get(n);if(r){var i=new Set(r),o=new Set(e),s=n.current;i.forEach(function(c){o.has(c)||gc(c,null)}),o.forEach(function(c){i.has(c)||gc(c,s)})}cm.set(n,e)},[e]),n}function DS(e){return e}function LS(e,t){t===void 0&&(t=DS);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 $S(e){e===void 0&&(e={});var t=LS(null);return t.options=Bt({async:!0,ssr:!1},e),t}var lm=function(e){var t=e.sideCar,n=sm(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,Bt({},n))};lm.isSideCarExport=!0;function MS(e,t){return e.useMedium(t),lm}var dm=$S(),vc=function(){},Ko=F(function(e,t){var n=B(null),r=I({onScrollCapture:vc,onWheelCapture:vc,onTouchMoveCapture:vc}),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,g=e.noIsolation,h=e.inert,v=e.allowPinchZoom,b=e.as,w=b===void 0?"div":b,S=e.gapMode,T=sm(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),N=m,P=RS([n,t]),A=Bt(Bt({},T),i);return y(te,null,u&&y(N,{sideCar:dm,removeScrollBar:d,shards:p,noRelative:f,noIsolation:g,inert:h,setCallbacks:o,allowPinchZoom:!!v,lockRef:n,gapMode:S}),s?Tr(Ft.only(c),Bt(Bt({},A),{ref:P})):y(w,Bt({},A,{className:l,ref:P}),c))});Ko.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Ko.classNames={fullWidth:Ho,zeroRight:Go};var um,OS=function(){if(um)return um;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function jS(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=OS();return t&&e.setAttribute("nonce",t),e}function FS(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function BS(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var US=function(){var e=0,t=null;return{add:function(n){e==0&&(t=jS())&&(FS(t,n),BS(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},GS=function(){var e=US();return function(t,n){K(function(){return e.add(t),function(){e.remove()}},[t&&n])}},pm=function(){var e=GS(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},HS={left:0,top:0,right:0,gap:0},yc=function(e){return parseInt(e||"",10)||0},KS=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[yc(n),yc(r),yc(i)]},qS=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return HS;var t=KS(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])}},VS=pm(),bi="data-scroll-locked",WS=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
2
|
.`.concat(PS,` {
|
|
3
3
|
overflow: hidden `).concat(r,`;
|
|
4
4
|
padding-right: `).concat(c,"px ").concat(r,`;
|
|
@@ -35,19 +35,19 @@
|
|
|
35
35
|
body[`).concat(bi,`] {
|
|
36
36
|
`).concat(ES,": ").concat(c,`px;
|
|
37
37
|
}
|
|
38
|
-
`)},mm=function(){var e=parseInt(document.body.getAttribute("data-scroll-locked")||"0",10);return isFinite(e)?e:0},zS=function(){K(function(){return document.body.setAttribute(bi,(mm()+1).toString()),function(){var e=mm()-1;e<=0?document.body.removeAttribute(bi):document.body.setAttribute(bi,e.toString())}},[])},JS=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;zS();var o=
|
|
38
|
+
`)},mm=function(){var e=parseInt(document.body.getAttribute("data-scroll-locked")||"0",10);return isFinite(e)?e:0},zS=function(){K(function(){return document.body.setAttribute(bi,(mm()+1).toString()),function(){var e=mm()-1;e<=0?document.body.removeAttribute(bi):document.body.setAttribute(bi,e.toString())}},[])},JS=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;zS();var o=xe(function(){return qS(i)},[i]);return y(VS,{styles:WS(o,!t,i,n?"":"!important")})},bc=!1;if(typeof window<"u")try{var qo=Object.defineProperty({},"passive",{get:function(){return bc=!0,!0}});window.addEventListener("test",qo,qo),window.removeEventListener("test",qo,qo)}catch{bc=!1}var Nr=bc?{passive:!1}:!1,YS=function(e){return e.tagName==="TEXTAREA"},fm=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!YS(e)&&n[t]==="visible")},XS=function(e){return fm(e,"overflowY")},QS=function(e){return fm(e,"overflowX")},hm=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host),gm(e,r)){var i=vm(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},ZS=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},eC=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},gm=function(e,t){return e==="v"?XS(t):QS(t)},vm=function(e,t){return e==="v"?ZS(t):eC(t)},tC=function(e,t){return e==="h"&&t==="rtl"?-1:1},nC=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,m=0;do{if(!c)break;var f=vm(e,c),g=f[0],h=f[1]-f[2]-o*g;(g||h)&&gm(e,c)&&(p+=h,m+=g);var v=c.parentNode;c=v&&v.nodeType===Node.DOCUMENT_FRAGMENT_NODE?v.host:v}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]},ym=function(e){return[e.deltaX,e.deltaY]},bm=function(e){return e&&"current"in e?e.current:e},rC=function(e,t){return e[0]===t[0]&&e[1]===t[1]},iC=function(e){return`
|
|
39
39
|
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
40
40
|
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
41
|
-
`)},oC=0,kr=[];function aC(e){var t=B([]),n=B([0,0]),r=B(),i=I(oC++)[0],o=I(pm)[0],s=B(e);K(function(){s.current=e},[e]),K(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var h=xS([e.lockRef.current],(e.shards||[]).map(bm),!0).filter(Boolean);return h.forEach(function(v){return v.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),h.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var c=re(function(h,v){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!s.current.allowPinchZoom;var b=
|
|
41
|
+
`)},oC=0,kr=[];function aC(e){var t=B([]),n=B([0,0]),r=B(),i=I(oC++)[0],o=I(pm)[0],s=B(e);K(function(){s.current=e},[e]),K(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var h=xS([e.lockRef.current],(e.shards||[]).map(bm),!0).filter(Boolean);return h.forEach(function(v){return v.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),h.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var c=re(function(h,v){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!s.current.allowPinchZoom;var b=Vo(h),w=n.current,S="deltaX"in h?h.deltaX:w[0]-b[0],T="deltaY"in h?h.deltaY:w[1]-b[1],N,P=h.target,A=Math.abs(S)>Math.abs(T)?"h":"v";if("touches"in h&&A==="h"&&P.type==="range")return!1;var M=window.getSelection(),U=M&&M.anchorNode;if(U&&(U===P||U.contains(P)))return!1;var x=hm(A,P);if(!x)return!0;if(x?N=A:(N=A==="v"?"h":"v",x=hm(A,P)),!x)return!1;if(!r.current&&"changedTouches"in h&&(S||T)&&(r.current=N),!N)return!0;var G=r.current||N;return nC(G,v,h,G==="h"?S:T,!0)},[]),l=re(function(h){var v=h;if(!(!kr.length||kr[kr.length-1]!==o)){var b="deltaY"in v?ym(v):Vo(v),w=t.current.filter(function(T){return T.name===v.type&&(T.target===v.target||v.target===T.shadowParent)&&rC(T.delta,b)})[0];if(w&&w.should){v.cancelable&&v.preventDefault();return}if(!w){var S=(s.current.shards||[]).map(bm).filter(Boolean).filter(function(T){return T.contains(v.target)});(S.length>0?c(v,S[0]):!s.current.noIsolation)&&v.cancelable&&v.preventDefault()}}},[]),d=re(function(h,v,b,w){var S={name:h,delta:v,target:b,should:w,shadowParent:sC(b)};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,ym(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 kr.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:m}),document.addEventListener("wheel",l,Nr),document.addEventListener("touchmove",l,Nr),document.addEventListener("touchstart",u,Nr),function(){kr=kr.filter(function(h){return h!==o}),document.removeEventListener("wheel",l,Nr),document.removeEventListener("touchmove",l,Nr),document.removeEventListener("touchstart",u,Nr)}},[]);var f=e.removeScrollBar,g=e.inert;return y(te,null,g?y(o,{styles:iC(i)}):null,f?y(JS,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function sC(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var cC=MS(dm,aC),_i=F(function(e,t){return y(Ko,Bt({},e,{ref:t,sideCar:cC}))});_i.classNames=Ko.classNames;var lC=function(e){return typeof document>"u"?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},xr=new WeakMap,Wo=new WeakMap,zo={},_c=0,_m=function(e){return e&&(e.host||_m(e.parentNode))},dC=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=_m(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})},uC=function(e,t,n,r){var i=dC(t,Array.isArray(e)?e:[e]);zo[n]||(zo[n]=new WeakMap);var o=zo[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),g=f!==null&&f!=="false",h=(xr.get(m)||0)+1,v=(o.get(m)||0)+1;xr.set(m,h),o.set(m,v),s.push(m),h===1&&g&&Wo.set(m,!0),v===1&&m.setAttribute(n,"true"),g||m.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",m,b)}})};return u(t),c.clear(),_c++,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)}),_c--,_c||(xr=new WeakMap,xr=new WeakMap,Wo=new WeakMap,zo={})}},Jo=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"))),uC(r,i,n,"aria-hidden")):function(){return null}},Yo="Dialog",[wm,$O]=st(Yo),[pC,xt]=wm(Yo),Sm=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!0}=e,c=B(null),l=B(null),[d,u]=wt({prop:r,defaultProp:i??!1,onChange:o,caller:Yo});return a(pC,{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})};Sm.displayName=Yo;var Cm="DialogTrigger",mC=F((e,t)=>{const{__scopeDialog:n,...r}=e,i=xt(Cm,n),o=we(t,i.triggerRef);return a(se.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Cc(i.open),...r,ref:o,onClick:z(e.onClick,i.onOpenToggle)})});mC.displayName=Cm;var wc="DialogPortal",[fC,Tm]=wm(wc,{forceMount:void 0}),Nm=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,o=xt(wc,t);return a(fC,{scope:t,forceMount:n,children:Ft.map(r,s=>a(rt,{present:n||o.open,children:a(qn,{asChild:!0,container:i,children:s})}))})};Nm.displayName=wc;var Xo="DialogOverlay",km=F((e,t)=>{const n=Tm(Xo,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,o=xt(Xo,e.__scopeDialog);return o.modal?a(rt,{present:r||o.open,children:a(gC,{...i,ref:t})}):null});km.displayName=Xo;var hC=Hn("DialogOverlay.RemoveScroll"),gC=F((e,t)=>{const{__scopeDialog:n,...r}=e,i=xt(Xo,n);return a(_i,{as:hC,allowPinchZoom:!0,shards:[i.contentRef],children:a(se.div,{"data-state":Cc(i.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Vn="DialogContent",xm=F((e,t)=>{const n=Tm(Vn,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,o=xt(Vn,e.__scopeDialog);return a(rt,{present:r||o.open,children:o.modal?a(vC,{...i,ref:t}):a(yC,{...i,ref:t})})});xm.displayName=Vn;var vC=F((e,t)=>{const n=xt(Vn,e.__scopeDialog),r=B(null),i=we(t,n.contentRef,r);return K(()=>{const o=r.current;if(o)return Jo(o)},[]),a(Pm,{...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())})}),yC=F((e,t)=>{const n=xt(Vn,e.__scopeDialog),r=B(!1),i=B(!1);return a(Pm,{...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()}})}),Pm=F((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:o,...s}=e,c=xt(Vn,n),l=B(null),d=we(t,l);return Uo(),a(te,{children:[a(yi,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:o,children:a(Kn,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":Cc(c.open),...s,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),a(te,{children:[a(SC,{titleId:c.titleId}),a(TC,{contentRef:l,descriptionId:c.descriptionId})]})]})}),Sc="DialogTitle",bC=F((e,t)=>{const{__scopeDialog:n,...r}=e,i=xt(Sc,n);return a(se.h2,{id:i.titleId,...r,ref:t})});bC.displayName=Sc;var Em="DialogDescription",_C=F((e,t)=>{const{__scopeDialog:n,...r}=e,i=xt(Em,n);return a(se.p,{id:i.descriptionId,...r,ref:t})});_C.displayName=Em;var Am="DialogClose",wC=F((e,t)=>{const{__scopeDialog:n,...r}=e,i=xt(Am,n);return a(se.button,{type:"button",...r,ref:t,onClick:z(e.onClick,()=>i.onOpenChange(!1))})});wC.displayName=Am;function Cc(e){return e?"open":"closed"}var Im="DialogTitleWarning",[MO,Rm]=Jw(Im,{contentName:Vn,titleName:Sc,docsSlug:"dialog"}),SC=({titleId:e})=>{const t=Rm(Im),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},CC="DialogDescriptionWarning",TC=({contentRef:e,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Rm(CC).contentName}}.`;return K(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},NC=Sm,kC=Nm,xC=km,PC=xm;function wi({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:g}){return a(NC,{modal:o,open:p,onOpenChange:u,children:p?a(kC,{children:[a(xC,{asChild:!0,children:a("div",{className:m,id:f})}),a(PC,{"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??(g?a("div",{id:g}):null)})})]}):null})}var Dm=500,Qo=null,Si=null,Ci=null;function Ti(e){return Si?Si(e)?(Ci=document.activeElement instanceof HTMLElement?document.activeElement:null,!0):!1:(Ci=document.activeElement instanceof HTMLElement?document.activeElement:null,Qo=e,!0)}function rt(e){return e.recipientKind==="identity"?`identity:${e.identityId}`:`team:${e.teamId}`}function Lm(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 Tc(e){return e.recipientKind==="identity"?rt({recipientKind:"identity",identityId:e.identityId}):rt({recipientKind:"team",teamId:e.teamId})}function EC(e,t){return Tc(e)===rt(t)}function $m(e,t){return e instanceof Us?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function Mm({checked:e,description:t,disabled:n,label:r,onChange:i}){const o=`recipient-policy-choice-${gi()}`;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 AC(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:rt({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:rt({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=Tc(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 Om(e){return e.mode==="project-add"?[...new Set(e.projectIds)]:e.mode==="project-manage"?[e.projectId]:[]}function IC(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(Tc):n.filter(r=>EC(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function RC(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 DC(e,t,n){return e.mode==="project-add"?Om(e).flatMap(r=>t.flatMap(i=>{const o=Lm(i);return o?[{canonicalProjectIdentity:r,recipient:o,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=Lm(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 LC(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 jm(e,t){let n=!1,r=!1,i=!1,o=!1;const s=rt(t);for(const c of e){const{change:l,outcome:d}=c;rt(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 $C(e){const t=new Set(e.selectedRecipients.map(rt)),n=new Map;for(const r of e.normalizedChanges){const i=rt(r.recipient);t.has(i)||n.set(i,r.recipient)}return[...n.values()]}function MC(e){const t=new Set;return e.filter(n=>t.has(n.deviceId)?!1:(t.add(n.deviceId),!0))}function OC({preview:e,recipientLabels:t}){const n=MC(e.effectiveDevices),r=$C(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:["— ",jm(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."]})]},rt(i))),r.map(i=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:t.get(rt(i))??(i.recipientKind==="team"?i.teamId:i.identityId)})," ",a("span",{children:["— ",jm(e.outcomes,i)," ·"," ",i.recipientKind==="team"?"Team":"Identity"]})]},rt(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 jC({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=>rt(s)===rt(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}:${rt(r.change.recipient)}`)})}):null]})})}function FC({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,g]=I(null),[h,v]=I(""),[b,w]=I(!1),S=B(!1),T=ke(()=>AC(e,r),[e,r]),N=ke(()=>new Map([...e.teams.map(Y=>[`team:${Y.teamId}`,Y.displayName]),...e.identities.map(Y=>[`identity:${Y.identityId}`,Y.displayName])]),[e]),P=ke(()=>new Set(n.map(Y=>Y.canonicalProjectIdentity)),[n]);if(K(()=>{if(Si=Y=>{if(S.current)return!1;const fe=IC(Y,e);return i(Y),l(fe),s(Y.mode==="recipient-add"?[]:fe),u(null),m(null),g(null),v(""),w(!1),S.current=!1,!0},Qo){const Y=Qo;Qo=null,Si(Y)}return()=>{Si=null}},[e]),K(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const A=LC(r),M=Om(r),U=r.mode==="recipient-manage"?!1:M.some(Y=>!P.has(Y)),x=(r.mode==="recipient-add"||r.mode==="recipient-manage")&&!T.some(Y=>Y.key===rt(r.recipient)),G=t.loading||t.loadError||U||x,E=DC(r,o,c),$=E.length>Dm,L=(r.mode==="project-add"||r.mode==="recipient-add")&&o.length===0,J=r.mode!=="project-add"&&r.mode!=="recipient-add"&&E.length===0,H=RC(n,r,c),k=p?.status==="applied",R=p?k?"Recipient access updated":"Recipient access needs attention":d?"Review recipient access":A.title,j=p?k?"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.":A.description,W=()=>{S.current||(i(null),u(null),m(null),g(null),v(""))},ge=Y=>{s(fe=>fe.includes(Y)?fe.filter(X=>X!==Y):[...fe,Y]),g(null),v("")},le=async()=>{if(!(G||L||J||$||S.current)){S.current=!0,w(!0),g(null),v("Reviewing exact recipient access changes.");try{u(await iw({version:1,changes:E})),v("Review ready. Confirm the exact changes.")}catch(Y){g($m(Y,"Unable to review recipient access changes.")),v("")}finally{S.current=!1,w(!1)}}},ce=async()=>{if(!(!d||S.current)){S.current=!0,w(!0),g(null),v("Saving recipient access changes.");try{const Y=await ow({version:1,changes:d.normalizedChanges,reviewedPolicyDigest:d.reviewedPolicyDigest});m(Y),v("");try{await t.onCommitted?.(Y)}catch{g("Recipient access was saved, but this view could not refresh.")}}catch(Y){Y instanceof Us&&(u(null),v("")),g($m(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.":x&&(be="This recipient is no longer available. Refresh and try again."),a(wi,{ariaDescribedby:"recipient-policy-management-description",ariaLabelledby:"recipient-policy-management-title",contentClassName:"modal recipient-policy-management-dialog",contentId:"recipientPolicyManagementDialog",onCloseAutoFocus:Y=>{Y.preventDefault();const fe=r.mode.startsWith("project-")?"tabBtn-projects":"tabBtn-sharing",X=Ci?.isConnected?Ci:document.getElementById(fe);X instanceof HTMLElement&&X.focus(),Ci=null},onOpenAutoFocus:Y=>{const fe=document.getElementById("recipient-policy-management-title");fe&&(Y.preventDefault(),fe.focus())},onOpenChange:Y=>{Y||W()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyManagementDialogBackdrop",children:a("div",{"aria-busy":b||t.loading?"true":"false",className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"recipient-policy-management-title",tabIndex:-1,children:R}),a(Mo,{ariaLabel:`Close ${R}`,className:"modal-close-button recipient-policy-management-target",disabled:b,onClick:W})]}),a("div",{className:"modal-body recipient-policy-management-selection",children:[a("p",{className:"small",id:"recipient-policy-management-description",children:j}),be?a("p",{"aria-live":"polite",role:t.loadError?"alert":"status",children:be}):p&&d?a(jC,{preview:d,result:p}):d?a(OC,{preview:d,recipientLabels:N}):r.mode==="recipient-add"||r.mode==="recipient-manage"?a("fieldset",{className:"sync-dialog-radio-list",disabled:b,children:[a("legend",{children:A.legend}),H.length?H.map(Y=>a(Mm,{checked:o.includes(Y.canonicalProjectIdentity),description:Y.description,disabled:b,label:Y.displayName,onChange:()=>ge(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:b,children:[a("legend",{children:A.legend}),T.length?T.map(Y=>a(Mm,{checked:o.includes(Y.key),description:Y.description,disabled:b,label:Y.label,onChange:()=>ge(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 ",E.length.toLocaleString()," access changes. Review at most ",Dm.toLocaleString()," changes at a time; reduce the selection and try again."]}):null]}),a("div",{className:"modal-footer recipient-policy-management-actions",children:[a("button",{className:"settings-button recipient-policy-management-target",disabled:b,onClick:d&&!p?()=>{u(null),v("")}:W,type:"button",children:p?"Done":d?"Back":"Cancel"}),!p&&!be?a("button",{className:"settings-button sync-dialog-confirm recipient-policy-management-target",disabled:b||!d&&(L||J||$),onClick:()=>{d?ce():le()},type:"button",children:b?d?"Saving…":"Reviewing…":d?"Confirm changes":"Review changes"}):null]})]})})}function Fm(e,t,n,r={}){Ue(a(FC,{intent:n,options:r,projects:t}),e)}function Zo(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function BC(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 ea(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,Er=null;function ta(e=[],t=""){if(Er){const n=Er(e,t);return n||(Pr=null),n}return Pr={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function Bm(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 UC(e){const t=`share-project-${gi()}`,n=Bm(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 GC({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 HC({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),[g,h]=I(!1),[v,b]=I(null),[w,S]=I(!1),T=ke(()=>e.filter(Bm),[e]);K(()=>{if(Er=(x,G="")=>{if(t)return!1;const E=[...new Set(x)],$=E.some(L=>!T.some(J=>J.workspace_identity===L));return o(G.trim()),c($?[]:E),S($),d(null),p(null),f($?"The original project selection is no longer available. Refresh Projects and try again.":null),b(null),r(!0),!0},Pr){const x=Pr;Pr=null,Er(x.projectIds,x.teammateName)}return()=>{Er=null}},[T,t]),K(()=>{t&&(Pr=null,r(!1),o(""),c([]),d(null),p(null),f(null),b(null),S(!1))},[t]);const N=()=>{g||r(!1)},P=x=>{c(G=>G.includes(x)?G.filter(E=>E!==x):[...G,x])},A=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 uw({teammate_name:i.trim(),project_ids:s}))}catch(x){f(Um(x,"Unable to review this invitation."))}finally{h(!1)}},M=async()=>{if(l){f(null),h(!0);try{p(await pw({teammate_name:l.teammate.display_name,project_ids:l.projects.map(x=>x.project_id),reviewed_project_set_digest:l.reviewed_project_set_digest}))}catch(x){x instanceof Error&&x.message==="reviewed_project_set_changed"&&d(null),f(Um(x,"Unable to create this invitation."))}finally{h(!1)}}},U=async()=>{if(u){f(null),b(null);try{if(!navigator.clipboard)throw new Error("Clipboard access is unavailable.");await navigator.clipboard.writeText(u.invite.link),b("Invite copied.")}catch(x){f(x instanceof Error?x.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:()=>Er?.([]),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(wi,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:x=>{x||N()},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:g,onClick:N,type:"button",children:"×"})]}),a("div",{"aria-busy":g,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(x=>x.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"}),v?a("p",{role:"status",children:v}):null]}):l?a(GC,{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:x=>o(x.currentTarget.value),type:"text",value:i})]}),a("fieldset",{className:"sync-dialog-radio-list",children:[a("legend",{children:"Select exact projects"}),e.map(x=>a(UC,{onToggle:P,project:x,selected:s.includes(x.workspace_identity)},x.workspace_identity))]})]}),m?a("p",{role:"alert",children:m}):null]}),a("div",{className:"modal-footer",children:[a("button",{className:"settings-button",disabled:g,onClick:N,type:"button",children:u?"Done":"Cancel"}),u?null:a("button",{className:"settings-button sync-dialog-confirm",disabled:g||w,onClick:()=>{l?M():A()},type:"button",children:g?l?"Creating invite…":"Reviewing…":l?"Create invite":"Review sharing"})]})]})}):null]})}function Gm(e,t,n={}){Ue(a(HC,{inventoryError:n.inventoryError===!0,projects:t}),e)}var KC=/^(?:local:|identity:|pending_)/iu,qC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,WC=/^[0-9a-f]{12,}$/iu;function Hm(e){const t=String(e??"").trim();return!t||KC.test(t)||qC.test(t)||WC.test(t)?"":t}function na(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 VC(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 ra(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 Ni(e){return`${e.toLocaleString()} existing ${e===1?"memory":"memories"}`}function zC({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})," — ",Ni(t.existingMemoryCount)," and future activity"]},t.canonicalProjectIdentity))})}function JC({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(zC,{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 YC({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," — ",Ni(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," — ",Ni(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," — ",Ni(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 Km({preview:e}){return e.journey==="team"?a(JC,{preview:e}):a(YC,{preview:e})}function XC({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})," —"," ",Ni(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 QC({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 ZC({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 qm(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function eT({intent:e}){const t=e.teams.filter(q=>q.status==="active"),n=e.identities.filter(q=>q.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,g]=I(null),[h,v]=I(null),[b,w]=I(null),[S,T]=I(""),[N,P]=I(""),[A,M]=I(null),[U,x]=I(!1),[G,E]=I(""),[$,L]=I(""),J=B(null),H=B(0),k=B(""),R=B(!1);K(()=>{if(b){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,b]);const j=()=>{H.current+=1,k.current="",R.current=!1,u(""),m(null),g(null),v(null),w(null),T(""),P(""),M(null),E(""),L("")},W=(q,oe)=>{j(),J.current=oe,i(q)},ge=()=>{U||(i(null),j())},le=q=>{H.current+=1,k.current=q,u(q)},ce=q=>{s(q),l(q==="team_member"?t[0]?.teamId??"":n[0]?.identityId??""),j()},be=async()=>{if(c){x(!0),L(""),E("Reviewing invitation…");try{m((await aw(qm(o,c))).preview),E("Review ready. Confirm the invitation details.")}catch(q){L(ra(q,"Unable to review this invitation.")),E("")}finally{x(!1)}}},Y=async()=>{if(p){x(!0),L(""),E("Creating invitation…");try{M(await sw({...qm(o,c),reviewed_onboarding_digest:p.reviewedOnboardingDigest})),E("Invitation created.")}catch(q){q instanceof Error&&q.message==="reviewed_onboarding_stale"&&m(null),L(ra(q,"Unable to create this invitation.")),E("")}finally{x(!1)}}},fe=async()=>{const q=k.current.trim(),oe=H.current;if(!q){L("Paste an invitation first.");return}const qe=()=>H.current===oe&&k.current.trim()===q;x(!0),L(""),E("Reviewing invitation…");try{const Me=await ju(q);if(!qe())return;g(Me),Me.kind==="project_share_invite"&&(T(Hm(Me.recipient_name)),P(Hm(Me.device_name))),E(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(!qe())return;L(ra(Me,"Unable to review this invitation.")),E("")}finally{x(!1)}},X=async()=>{if(!(U||R.current||b)&&!(!f||f.kind==="legacy_team_invite")&&!(f.kind==="project_share_invite"&&!(f.projects?.length??0))&&!(f.kind==="project_share_invite"&&(na(S,"Identity display name")||na(N,"Device display name")))){R.current=!0,x(!0),L(""),E("Accepting invitation…");try{const q=f.kind==="project_share_invite"?await Bs(d.trim(),{recipient_name:S.trim(),device_name:N.trim()}):await Bs(d.trim(),{recipient_name:f.recipient_name,device_name:f.device_name,reviewed_onboarding_digest:f.onboarding.reviewedOnboardingDigest});if(f.kind==="project_share_invite")v(VC(q)),E("");else{const oe=f.kind;w({kind:oe,restartRequired:q.restart_required===!0||q.setup_state==="restart_required",detail:(typeof q.detail=="string"?q.detail.trim():"")||"Restart codemem before continuing.",deliveryPending:oe==="add_device"&&(f.onboarding?.projects?.length??0)>0}),E("")}}catch(q){R.current=!1;const oe=q instanceof Error?q.message.trim():"";L(ra(q,f.kind==="project_share_invite"&&oe?oe:"Unable to accept this invitation.")),E("")}finally{x(!1)}}},_e=async()=>{const q=A?.invite.link||A?.invite.encoded||"";if(!q){L("The invitation text is unavailable.");return}try{await navigator.clipboard.writeText(q),E("Invitation copied.")}catch{L("Unable to copy the invitation.")}},he=f?.kind==="team_member"||f?.kind==="add_device"?f.onboarding:null,Q=f?.kind==="project_share_invite"?f:null,$e=Q?na(S,"Identity display name"):"",ue=Q?na(N,"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=>{ce("team_member"),W("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=>{ce("add_device"),W("create",q.currentTarget)},type:"button",children:"Add a device"}),a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>ta(),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=>W("accept",q.currentTarget),type:"button",children:"Review invitation"}),a("p",{className:"small",children:"Legacy invitation import remains under Advanced Team administration."})]}),r?a(wi,{ariaDescribedby:"recipient-invitation-description",ariaLabelledby:"recipient-invitation-title",contentClassName:"modal recipient-policy-invitation-dialog",contentId:"recipientInvitationDialog",onCloseAutoFocus:q=>{q.preventDefault(),J.current?.focus(),J.current=null},onOpenAutoFocus:q=>{q.preventDefault(),document.getElementById("recipient-invitation-title")?.focus()},onOpenChange:q=>{q||ge()},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:b?"Invitation accepted":r==="create"?"Create invitation":"Review invitation"}),a(Mo,{ariaLabel:"Close invitation",className:"modal-close-button recipient-policy-sharing-target-24",disabled:U,onClick:ge})]}),a("div",{className:"modal-body",children:[a("p",{className:"small",id:"recipient-invitation-description",children:b?"The invitation has been accepted.":"Confirm exactly what this invitation includes before continuing."}),r==="create"&&!p&&!A?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"&&!f&&!b?a("label",{className:"field",htmlFor:"recipient-invitation-value",children:[a("span",{children:"Invitation"}),a("textarea",{id:"recipient-invitation-value",onInput:q=>{le(q.currentTarget.value),g(null),v(null),E(""),L("")},rows:5,value:d})]}):null,p?a(Km,{preview:p}):null,he&&!b?a(Km,{preview:he}):null,Q&&!h?a(XC,{deviceName:N,deviceNameError:ue,invite:Q,onDeviceNameChange:q=>{P(q),L("")},onRecipientNameChange:q=>{T(q),L("")},recipientName:S,recipientNameError:$e}):null,h?a(QC,{result:h}):null,b?a(ZC,{result:b}):null,A?a("div",{children:[a("p",{children:"Share the invitation with the recipient."}),a("button",{className:"settings-button",onClick:()=>{_e()},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:ge,type:"button",children:A||h||b?"Done":"Cancel"}),r==="create"&&!A?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&&!b?a("button",{className:"settings-button sync-dialog-confirm",disabled:U,onClick:()=>{fe()},type:"button",children:U?"Reviewing…":"Review invitation"}):he&&!b||Q&&!h?a("button",{className:"settings-button sync-dialog-confirm",disabled:U||!!(Q&&(!Q.projects?.length||$e||ue)),onClick:()=>{X()},type:"button",children:U?"Accepting…":Q?"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 bn(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function Ar(e,t){return e.length?e.join(", "):t}function Nc(e,t){return[...new Set(e)].flatMap(n=>{const r=t.get(n);return r?[r.displayName]:[]})}function Wm({descriptionId:e,displayName:t,recipient:n}){const r=()=>{Ti({mode:"recipient-manage",recipient:n})},i=()=>{Ti({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 tT({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=Nc(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:[bn(l.length,"active member")," —"," ",Ar(l,"No active members")]})]}),a("div",{children:[a("dt",{children:"Registered devices"}),a("dd",{children:bn(d,"active registered device")})]}),a("div",{children:[a("dt",{children:"Shared Projects"}),a("dd",{children:[bn(u.length,"active shared Project")," —"," ",Ar(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(Wm,{descriptionId:m,displayName:o.displayName,recipient:{recipientKind:"team",teamId:o.teamId}})]},o.teamId)})})}function nT({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(g=>g.status==="active"&&g.identityId===o.identityId),l=[...new Set(e.teamMemberships.filter(g=>g.status==="active"&&g.identityId===o.identityId&&r.has(g.teamId)).map(g=>g.teamId))],d=l.map(g=>r.get(g)?.displayName??""),u=Nc(e.projectRecipients.filter(g=>g.status==="active"&&g.recipientKind==="identity"&&g.identityId===o.identityId).map(g=>g.canonicalProjectIdentity),i),p=Nc(e.projectRecipients.filter(g=>g.status==="active"&&g.recipientKind==="team"&&l.includes(g.teamId)).map(g=>g.canonicalProjectIdentity),i),m=`recipient-policy-sharing-identity-title-${s}`,f=`recipient-policy-sharing-identity-add-description-${s}`;return a("article",{"aria-labelledby":m,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:m,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:[bn(c.length,"active registered device")," —"," ",Ar(c.map(g=>g.displayName),"No active devices")]})]}),a("div",{children:[a("dt",{children:"Team memberships"}),a("dd",{children:[bn(d.length,"active Team membership")," —"," ",Ar(d,"No active Team memberships")]})]}),a("div",{children:[a("dt",{children:"Directly shared Projects"}),a("dd",{children:[bn(u.length,"directly shared active Project")," —"," ",Ar(u,"No Projects shared directly")]})]}),a("div",{children:[a("dt",{children:"Projects through Teams"}),a("dd",{children:[bn(p.length,"Team-inherited Project")," —"," ",Ar(p,"No Projects inherited through Teams")]})]})]}),a("p",{className:"small",children:"Projects through Teams are shown separately and are not direct Identity shares."}),a(Wm,{descriptionId:f,displayName:o.displayName,recipient:{recipientKind:"identity",identityId:o.identityId}})]},o.identityId)})})}function rT({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:bn(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 iT({intent:e,options:t,projects:n}){const[r,i]=I("teams"),o=B([]),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(tT,{intent:e,projects:n}):l.id==="identities"?a(nT,{intent:e,projects:n}):l.id==="received"?a(rT,{received:t.received??[]}):a(eT,{intent:e})},l.id))]})}function oT(e,t,n,r={}){Ue(a(iT,{intent:n,options:r,projects:t}),e)}var kc={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function aT(){const e=[];let t=0;for(;;){const n=await Po({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return{manageable:ea(e),received:BC(e)}}var sT={loadIntent:Gs,loadProjects:aT,mountManagement:Fm,mountSharing:oT};function cT(e={}){const t={...sT,...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,[],kc,{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,[],kc,{loadError:!0}),o&&t.mountManagement(o,[],kc,{loadError:!0})}}}var lT=Symbol.for("preact-signals");function ia(){if(rn>1)rn--;else{var e,t=!1;for((function(){var i=aa;for(aa=void 0;i!==void 0;)i.S.v===i.v&&(i.S.i=i.i),i=i.o})();ki!==void 0;){var n=ki;for(ki=void 0,oa++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Jm(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if(oa=0,rn--,t)throw e}}function dT(e){if(rn>0)return e();Pc=++uT,rn++;try{return e()}finally{ia()}}var De=void 0;function xc(e){var t=De;De=void 0;try{return e()}finally{De=t}}var Vm,ki=void 0,rn=0,oa=0,uT=0,Pc=0,aa=void 0,sa=0;function zm(e){if(De!==void 0){var t=e.n;if(t===void 0||t.t!==De)return t={i:0,S:e,p:De.s,n:void 0,t:De,e:void 0,x:void 0,r:t},De.s!==void 0&&(De.s.n=t),De.s=t,e.n=t,32&De.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=De.s,t.n=void 0,De.s.n=t,De.s=t),t}}function ze(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}ze.prototype.brand=lT,ze.prototype.h=function(){return!0},ze.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:xc(function(){var r;(r=t.W)==null||r.call(t)}))},ze.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&&xc(function(){var i;(i=t.Z)==null||i.call(t)}))}},ze.prototype.subscribe=function(e){var t=this;return xi(function(){var n=t.value,r=De;De=void 0;try{e(n)}finally{De=r}},{name:"sub"})},ze.prototype.valueOf=function(){return this.value},ze.prototype.toString=function(){return this.value+""},ze.prototype.toJSON=function(){return this.value},ze.prototype.peek=function(){var e=this;return xc(function(){return e.value})},Object.defineProperty(ze.prototype,"value",{get:function(){var e=zm(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(oa>100)throw new Error("Cycle detected");(function(n){rn!==0&&oa===0&&n.l!==Pc&&(n.l=Pc,aa={S:n,v:n.v,i:n.i,o:aa})})(this),this.v=e,this.i++,sa++,rn++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{ia()}}}});function Ec(e,t){return new ze(e,t)}function Jm(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 Ym(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 Xm(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){ze.call(this,void 0),this.x=e,this.s=void 0,this.g=sa-1,this.f=4,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}zn.prototype=new ze,zn.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===sa))return!0;if(this.g=sa,this.f|=1,this.i>0&&!Jm(this))return this.f&=-2,!0;var e=De;try{Ym(this),De=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 De=e,Xm(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)}ze.prototype.S.call(this,e)},zn.prototype.U=function(e){if(this.t!==void 0&&(ze.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=zm(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function Qm(e,t){return new zn(e,t)}function Zm(e){var t=e.m;if(e.m=void 0,typeof t=="function"){rn++;var n=De;De=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,Ac(e),r}finally{De=n,ia()}}}function Ac(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,Zm(e)}function pT(e){if(De!==this)throw new Error("Out-of-order effect");Xm(this),De=e,this.f&=-2,8&this.f&&Ac(this),ia()}function Ir(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,Vm&&Vm.push(this)}Ir.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()}},Ir.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Zm(this),Ym(this),rn++;var e=De;return De=this,pT.bind(this,e)},Ir.prototype.N=function(){2&this.f||(this.f|=2,this.u=ki,ki=this)},Ir.prototype.d=function(){this.f|=8,1&this.f||Ac(this)},Ir.prototype.dispose=function(){this.d()};function xi(e,t){var n=new Ir(e,t);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var ef,Ic,ca,mT=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,OO=[],tf=[];xi(function(){ef=this.N})();function Rr(e,t){me[e]=t.bind(null,me[e]||function(){})}function la(e){if(ca){var t=ca;ca=void 0,t()}ca=e&&e.S()}function nf(e){var t=this,n=e.data,r=hT(n);r.value=n;var i=ke(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=Qm(function(){var f=r.value.value;return f===0?0:f===!0?"":f||""}),u=Qm(function(){return!Array.isArray(d.value)&&!Yu(d.value)}),p=xi(function(){if(this.N=rf,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}nf.displayName="ReactiveTextNode",Object.defineProperties(ze.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:nf},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),Rr("__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 ze&&(n||(t.__np=n={}),n[i]=o,r[i]=o.peek())}}e(t)}),Rr("__r",function(e,t){if(e(t),t.type!==te){la();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,o){var s;return xi(function(){s=this},{name:o}),s.c=i,s})(function(){var i;mT&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:""))),Ic=r,la(n)}}),Rr("__e",function(e,t,n,r){la(),Ic=void 0,e(t,n,r)}),Rr("diffed",function(e,t){la(),Ic=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=fT(n,l,u),o[l]=d):d.o(u,i)}}}e(t)});function fT(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,o=Ec(n),s=n.peek();return{o:function(c,l){o.value=c,s=c.peek()},d:xi(function(){this.N=rf;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})}}Rr("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)}),Rr("__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 hT(e,t){return ke(function(){return Ec(e,t)},[])}var jO=typeof requestAnimationFrame>"u"?setTimeout:function(e){var t=function(){clearTimeout(n),cancelAnimationFrame(r),e()},n=setTimeout(t,35),r=requestAnimationFrame(t)},gT=function(e){queueMicrotask(function(){queueMicrotask(e)})};function vT(){dT(function(){for(var e;e=tf.shift();)ef.call(e)})}function rf(){tf.push(this)===1&&(me.requestAnimationFrame||gT)(vT)}function da(e){const t=e+"CollectionProvider",[n,r]=st(t),[i,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=h=>{const{scope:v,children:b}=h,w=nn.useRef(null),S=nn.useRef(new Map).current;return a(i,{scope:v,itemMap:S,collectionRef:w,children:b})};s.displayName=t;const c=e+"CollectionSlot",l=Hn(c),d=nn.forwardRef((h,v)=>{const{scope:b,children:w}=h;return a(l,{ref:we(v,o(c,b).collectionRef),children:w})});d.displayName=c;const u=e+"CollectionItemSlot",p="data-radix-collection-item",m=Hn(u),f=nn.forwardRef((h,v)=>{const{scope:b,children:w,...S}=h,T=nn.useRef(null),N=we(v,T),P=o(u,b);return nn.useEffect(()=>(P.itemMap.set(T,{ref:T,...S}),()=>{P.itemMap.delete(T)})),a(m,{[p]:"",ref:N,children:w})});f.displayName=u;function g(h){const v=o(e+"CollectionConsumer",h);return nn.useCallback(()=>{const b=v.collectionRef.current;if(!b)return[];const w=Array.from(b.querySelectorAll(`[${p}]`));return Array.from(v.itemMap.values()).sort((S,T)=>w.indexOf(S.ref.current)-w.indexOf(T.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:s,Slot:d,ItemSlot:f},g,r]}var of=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"}),yT="VisuallyHidden",ua=F((e,t)=>a(se.span,{...e,ref:t,style:{...of,...e.style}}));ua.displayName=yT;var bT=ua,Rc="ToastProvider",[Dc,_T,wT]=da("Toast"),[af,FO]=st("Toast",[wT]),[ST,pa]=af(Rc),sf=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=B(!1),m=B(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${Rc}\`. Expected non-empty \`string\`.`),a(Dc.Provider,{scope:t,children:a(ST,{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})})};sf.displayName=Rc;var cf="ToastViewport",CT=["F8"],Lc="toast.viewportPause",$c="toast.viewportResume",lf=F((e,t)=>{const{__scopeToast:n,hotkey:r=CT,label:i="Notifications ({hotkey})",...o}=e,s=pa(cf,n),c=_T(n),l=B(null),d=B(null),u=B(null),p=B(null),m=we(t,p,s.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=s.toastCount>0;K(()=>{const v=b=>{r.length!==0&&r.every(w=>b[w]||b.code===w)&&p.current?.focus()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r]),K(()=>{const v=l.current,b=p.current;if(g&&v&&b){const w=()=>{if(!s.isClosePausedRef.current){const P=new CustomEvent(Lc);b.dispatchEvent(P),s.isClosePausedRef.current=!0}},S=()=>{if(s.isClosePausedRef.current){const P=new CustomEvent($c);b.dispatchEvent(P),s.isClosePausedRef.current=!1}},T=P=>{v.contains(P.relatedTarget)||S()},N=()=>{v.contains(document.activeElement)||S()};return v.addEventListener("focusin",w),v.addEventListener("focusout",T),v.addEventListener("pointermove",w),v.addEventListener("pointerleave",N),window.addEventListener("blur",w),window.addEventListener("focus",S),()=>{v.removeEventListener("focusin",w),v.removeEventListener("focusout",T),v.removeEventListener("pointermove",w),v.removeEventListener("pointerleave",N),window.removeEventListener("blur",w),window.removeEventListener("focus",S)}}},[g,s.isClosePausedRef]);const h=re(({tabbingDirection:v})=>{const b=c().map(w=>{const S=w.ref.current,T=[S,...jT(S)];return v==="forwards"?T:T.reverse()});return(v==="forwards"?b.reverse():b).flat()},[c]);return K(()=>{const v=p.current;if(v){const b=w=>{const S=w.altKey||w.ctrlKey||w.metaKey;if(w.key==="Tab"&&!S){const T=document.activeElement,N=w.shiftKey;if(w.target===v&&N){d.current?.focus();return}const P=h({tabbingDirection:N?"backwards":"forwards"}),A=P.findIndex(M=>M===T);jc(P.slice(A+1))?w.preventDefault():N?d.current?.focus():u.current?.focus()}};return v.addEventListener("keydown",b),()=>v.removeEventListener("keydown",b)}},[c,h]),a(hS,{ref:l,role:"region","aria-label":i.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&a(Mc,{ref:d,onFocusFromOutsideViewport:()=>{jc(h({tabbingDirection:"forwards"}))}}),a(Dc.Slot,{scope:n,children:a(se.ol,{tabIndex:-1,...o,ref:m})}),g&&a(Mc,{ref:u,onFocusFromOutsideViewport:()=>{jc(h({tabbingDirection:"backwards"}))}})]})});lf.displayName=cf;var df="ToastFocusProxy",Mc=F((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...i}=e,o=pa(df,n);return a(ua,{tabIndex:0,...i,ref:t,style:{position:"fixed"},onFocus:s=>{const c=s.relatedTarget;o.viewport?.contains(c)||r()}})});Mc.displayName=df;var Pi="Toast",TT="toast.swipeStart",NT="toast.swipeMove",kT="toast.swipeCancel",xT="toast.swipeEnd",uf=F((e,t)=>{const{forceMount:n,open:r,defaultOpen:i,onOpenChange:o,...s}=e,[c,l]=wt({prop:r,defaultProp:i??!0,onChange:o,caller:Pi});return a(nt,{present:n||c,children:a(AT,{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)})})})});uf.displayName=Pi;var[PT,ET]=af(Pi,{onClose(){}}),AT=F((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,...g}=e,h=pa(Pi,n),[v,b]=I(null),w=we(t,L=>b(L)),S=B(null),T=B(null),N=i||h.duration,P=B(0),A=B(N),M=B(0),{onToastAdd:U,onToastRemove:x}=h,G=lt(()=>{v?.contains(document.activeElement)&&h.viewport?.focus(),s()}),E=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=()=>{E(A.current),d?.()},H=()=>{const k=new Date().getTime()-P.current;A.current=A.current-k,window.clearTimeout(M.current),l?.()};return L.addEventListener(Lc,H),L.addEventListener($c,J),()=>{L.removeEventListener(Lc,H),L.removeEventListener($c,J)}}},[h.viewport,N,l,d,E]),K(()=>{o&&!h.isClosePausedRef.current&&E(N)},[o,N,h.isClosePausedRef,E]),K(()=>(U(),()=>x()),[U,x]);const $=ke(()=>v?gf(v):null,[v]);return h.viewport?a(te,{children:[$&&a(IT,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite",children:$}),a(PT,{scope:n,onClose:G,children:en(a(Dc.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,...g,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,k=!!T.current,R=["left","right"].includes(h.swipeDirection),j=["left","up"].includes(h.swipeDirection)?Math.min:Math.max,W=R?j(0,J):0,ge=R?0:j(0,H),le=L.pointerType==="touch"?10:2,ce={x:W,y:ge},be={originalEvent:L,delta:ce};k?(T.current=ce,ma(NT,p,be,{discrete:!1})):vf(ce,h.swipeDirection,le)?(T.current=ce,ma(TT,u,be,{discrete:!1}),L.target.setPointerCapture(L.pointerId)):(Math.abs(J)>le||Math.abs(H)>le)&&(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 k=L.currentTarget,R={originalEvent:L,delta:J};vf(J,h.swipeDirection,h.swipeThreshold)?ma(xT,f,R,{discrete:!0}):ma(kT,m,R,{discrete:!0}),k.addEventListener("click",j=>j.preventDefault(),{once:!0})}})})})}),h.viewport)})]}):null}),IT=e=>{const{__scopeToast:t,children:n,...r}=e,i=pa(Pi,t),[o,s]=I(!1),[c,l]=I(!1);return MT(()=>s(!0)),K(()=>{const d=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(d)},[]),c?null:a(qn,{asChild:!0,children:a(ua,{...r,children:o&&a(te,{children:[i.label," ",n]})})})},RT="ToastTitle",DT=F((e,t)=>{const{__scopeToast:n,...r}=e;return a(se.div,{...r,ref:t})});DT.displayName=RT;var LT="ToastDescription",pf=F((e,t)=>{const{__scopeToast:n,...r}=e;return a(se.div,{...r,ref:t})});pf.displayName=LT;var mf="ToastAction",$T=F((e,t)=>{const{altText:n,...r}=e;return n.trim()?a(hf,{altText:n,asChild:!0,children:a(Oc,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${mf}\`. Expected non-empty \`string\`.`),null)});$T.displayName=mf;var ff="ToastClose",Oc=F((e,t)=>{const{__scopeToast:n,...r}=e,i=ET(ff,n);return a(hf,{asChild:!0,children:a(se.button,{type:"button",...r,ref:t,onClick:z(e.onClick,i.onClose)})})});Oc.displayName=ff;var hf=F((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 gf(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),OT(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(...gf(n))}}),t}function ma(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?uc(i,o):i.dispatchEvent(o)}var vf=(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 MT(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 OT(e){return e.nodeType===e.ELEMENT_NODE}function jT(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 jc(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var FT=sf,BT=lf,UT=uf,GT=pf,HT=Oc,Ei=Ec([]),KT=1;function qT(e,t="success",n=8e3){if(!e)return;const r=KT++;Ei.value=[...Ei.value,{id:r,message:e,variant:t,durationMs:n}]}function WT(e){Ei.value=Ei.value.filter(t=>t.id!==e)}function VT(){const e=Ei.value;return a(FT,{duration:8e3,swipeDirection:"right",children:[e.map(t=>a(UT,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||WT(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[a(GT,{className:"toast-message",children:t.message}),a(HT,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),a(BT,{className:"toast-viewport"})]})}function zT(e){Ue(a(VT,{}),e)}function fa(e,t,n){const r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=String(n)),r}function Ae(e){return document.getElementById(e)}function Fc(e){return document.getElementById(e)}function Bc(e){return document.getElementById(e)}function yf(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function JT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function YT(e,t){const n=t.trim();if(!n)return yf(e);const r=yf(e);try{const i=new RegExp(`(${JT(n)})`,"ig");return r.replace(i,'<mark class="match">$1</mark>')}catch{return r}}async function Ai(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 XT=new Set(["BUTTON","A","SELECT"]),QT=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function ZT(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function eN(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function tN(e){return e?XT.has(e.tagName)?!0:e instanceof HTMLInputElement&&QT.has(e.type):!1}function nN(e){return e.metaKey||e.ctrlKey}function Dr(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(!ZT(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}tN(n)||eN(n)&&!nN(e)||(e.preventDefault(),t.onSubmit())}}var Jn=["feed","projects","sharing","devices","health","advanced"],bf=["sync","coordinator-admin"],Uc="codemem-tab",_f="codemem-advanced-section",wf="codemem-feed-filter",Sf="codemem-feed-scope",rN="codemem-sync-diagnostics",Cf="codemem-sync-pairing",Tf="codemem-sync-redact",Nf=["all","observations","summaries"],kf=["all","mine","theirs"],_={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,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 iN(e){return[...Jn]}function Ii(e,t){return e==="sync"||e==="coordinator-admin"?"advanced":Jn.includes(e)?e:"feed"}function Gc(e=window.location.hash){const t=e.replace(/^#/,"").split("/")[0];return bf.includes(t)?"advanced":Jn.includes(t)?t:null}function Hc(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 oN(){const e=Gc();if(e)return Ii(e,_.lastCoordinatorAdminStatus);const t=localStorage.getItem(Uc);return t&&(Jn.includes(t)||bf.includes(t))?Ii(t,_.lastCoordinatorAdminStatus):"feed"}function aN(){const e=Hc();if(e)return e;const t=localStorage.getItem(Uc);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(_f)==="teams"?"teams":"sync"}function Kc(e,t=!1){_.advancedSection=e,localStorage.setItem(_f,e),t&&(window.location.hash=`advanced/${e}`)}function xf(e,t={}){const n=Ii(e,_.lastCoordinatorAdminStatus);_.activeTab=n,localStorage.setItem(Uc,n);const r=Gc();t.canonicalHash?window.location.hash=n:r!==n&&(window.location.hash=n==="advanced"?`advanced/${_.advancedSection}`:n)}function sN(){const e=localStorage.getItem(wf)||"all";return Nf.includes(e)?e:"all"}function cN(){const e=localStorage.getItem(Sf)||"all";return kf.includes(e)?e:"all"}function lN(e){_.feedTypeFilter=Nf.includes(e)?e:"all",localStorage.setItem(wf,_.feedTypeFilter)}function Pf(e){_.feedScopeFilter=kf.includes(e)?e:"all",localStorage.setItem(Sf,_.feedScopeFilter)}function dN(){return localStorage.getItem(rN)==="1"}function uN(e){_.syncPairingOpen=e;try{localStorage.setItem(Cf,e?"1":"0")}catch{}}function Ri(){return localStorage.getItem(Tf)!=="0"}function pN(e){localStorage.setItem(Tf,e?"1":"0")}function mN(){_.activeTab=oN(),_.advancedSection=aN(),_.feedTypeFilter=sN(),_.feedScopeFilter=cN(),_.syncDiagnosticsOpen=dN();try{_.syncPairingOpen=localStorage.getItem(Cf)==="1"}catch{_.syncPairingOpen=!1}}var qc=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],Ef="codemem-theme";function Af(e){const t=qc.find(r=>r.id===e);if(t)return t;const n=e.startsWith("dark")?"dark":"light";return qc.find(r=>r.id===n)||qc[0]}function Wc(){const e=localStorage.getItem(Ef);return e?Af(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function If(e){const t=Af(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(Ef,t.id)}function fN(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(Wc()==="dark"?"dark":"light"),e.addEventListener("click",()=>{const n=Wc()==="dark"?"light":"dark";If(n),t(n)})}var hN=Un(void 0);function Di(e){const t=vn(hN);return e||t||"ltr"}var Vc="rovingFocusGroup.onEntryFocus",gN={bubbles:!1,cancelable:!0},Li="RovingFocusGroup",[zc,Rf,vN]=da(Li),[yN,Lr]=st(Li,[vN]),[bN,_N]=yN(Li),Df=F((e,t)=>a(zc.Provider,{scope:e.__scopeRovingFocusGroup,children:a(zc.Slot,{scope:e.__scopeRovingFocusGroup,children:a(wN,{...e,ref:t})})}));Df.displayName=Li;var wN=F((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=B(null),f=we(t,m),g=Di(o),[h,v]=wt({prop:s,defaultProp:c??null,onChange:l,caller:Li}),[b,w]=I(!1),S=lt(d),T=Rf(n),N=B(!1),[P,A]=I(0);return K(()=>{const M=m.current;if(M)return M.addEventListener(Vc,S),()=>M.removeEventListener(Vc,S)},[S]),a(bN,{scope:n,orientation:r,dir:g,loop:i,currentTabStopId:h,onItemFocus:re(M=>v(M),[v]),onItemShiftTab:re(()=>w(!0),[]),onFocusableItemAdd:re(()=>A(M=>M+1),[]),onFocusableItemRemove:re(()=>A(M=>M-1),[]),children:a(se.div,{tabIndex:b||P===0?-1:0,"data-orientation":r,...p,ref:f,style:{outline:"none",...e.style},onMouseDown:z(e.onMouseDown,()=>{N.current=!0}),onFocus:z(e.onFocus,M=>{const U=!N.current;if(M.target===M.currentTarget&&U&&!b){const x=new CustomEvent(Vc,gN);if(M.currentTarget.dispatchEvent(x),!x.defaultPrevented){const G=T().filter(E=>E.focusable);Mf([G.find(E=>E.active),G.find(E=>E.id===h),...G].filter(Boolean).map(E=>E.ref.current),u)}}N.current=!1}),onBlur:z(e.onBlur,()=>w(!1))})})}),Lf="RovingFocusGroupItem",$f=F((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:o,children:s,...c}=e,l=ct(),d=o||l,u=_N(Lf,n),p=u.currentTabStopId===d,m=Rf(n),{onFocusableItemAdd:f,onFocusableItemRemove:g,currentTabStopId:h}=u;return K(()=>{if(r)return f(),()=>g()},[r,f,g]),a(zc.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,v=>{r?u.onItemFocus(d):v.preventDefault()}),onFocus:z(e.onFocus,()=>u.onItemFocus(d)),onKeyDown:z(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){u.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const b=TN(v,u.orientation,u.dir);if(b!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let w=m().filter(S=>S.focusable).map(S=>S.ref.current);if(b==="last")w.reverse();else if(b==="prev"||b==="next"){b==="prev"&&w.reverse();const S=w.indexOf(v.currentTarget);w=u.loop?NN(w,S+1):w.slice(S+1)}setTimeout(()=>Mf(w))}}),children:typeof s=="function"?s({isCurrentTabStop:p,hasTabStop:h!=null}):s})})});$f.displayName=Lf;var SN={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function CN(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function TN(e,t,n){const r=CN(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return SN[r]}function Mf(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function NN(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Jc=Df,Yc=$f,ha="Tabs",[kN,BO]=st(ha,[Lr]),Of=Lr(),[xN,Xc]=kN(ha),jf=F((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:i,defaultValue:o,orientation:s="horizontal",dir:c,activationMode:l="automatic",...d}=e,u=Di(c),[p,m]=wt({prop:r,onChange:i,defaultProp:o??"",caller:ha});return a(xN,{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})})});jf.displayName=ha;var Ff="TabsList",Bf=F((e,t)=>{const{__scopeTabs:n,loop:r=!0,...i}=e,o=Xc(Ff,n),s=Of(n);return a(Jc,{asChild:!0,...s,orientation:o.orientation,dir:o.dir,loop:r,children:a(se.div,{role:"tablist","aria-orientation":o.orientation,...i,ref:t})})});Bf.displayName=Ff;var Uf="TabsTrigger",Gf=F((e,t)=>{const{__scopeTabs:n,value:r,disabled:i=!1,...o}=e,s=Xc(Uf,n),c=Of(n),l=qf(s.baseId,r),d=Wf(s.baseId,r),u=r===s.value;return a(Yc,{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)})})})});Gf.displayName=Uf;var Hf="TabsContent",Kf=F((e,t)=>{const{__scopeTabs:n,value:r,forceMount:i,children:o,...s}=e,c=Xc(Hf,n),l=qf(c.baseId,r),d=Wf(c.baseId,r),u=r===c.value,p=B(u);return K(()=>{const m=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(m)},[]),a(nt,{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})})});Kf.displayName=Hf;function qf(e,t){return`${e}-trigger-${t}`}function Wf(e,t){return`${e}-content-${t}`}var PN=jf,EN=Bf,AN=Gf,IN=Kf;function Vf({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:o,value:s}){return a(PN,{onValueChange:r,value:s,children:[a(EN,{"aria-label":e,className:n,children:i.map(c=>a(AN,{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(IN,{className:t,forceMount:n?!0:void 0,value:r,children:e})}function Ce(e){return a("input",{...e})}function RN(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 DN="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 LN(e){const{summary:t,runDevice:n}=e,r=Array.isArray(_.lastCoordinatorAdminDevices)?_.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=RN(i,String(_.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 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:f=>{f.preventDefault(),!m&&n(s,l,c,"rename")}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Ce,{class:"peer-scope-input",disabled:t.readiness!=="ready"||d,onInput:f=>{O.deviceRenameDrafts.set(s,String(f.currentTarget.value||""))},type:"text",value:u}))),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:m,type:"submit"},d&&O.deviceActionPendingKind==="rename"?"Renaming…":"Rename"),p?y("button",{class:"settings-button danger",disabled:m,onClick:()=>n(s,l,c,"disable"),type:"button"},d&&O.deviceActionPendingKind==="disable"?"Disabling…":"Disable"):y("button",{class:"settings-button",disabled:m,onClick:()=>n(s,l,c,"enable"),type:"button"},d&&O.deviceActionPendingKind==="enable"?"Enabling…":"Enable"),y("button",{class:"settings-button danger",disabled:m,onClick:()=>n(s,l,c,"remove"),type:"button"},d&&O.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 ga="Collapsible",[$N,UO]=st(ga),[MN,Qc]=$N(ga),zf=F((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:ga});return a(MN,{scope:n,disabled:o,contentId:ct(),open:l,onOpenToggle:re(()=>d(u=>!u),[d]),children:a(se.div,{"data-state":el(l),"data-disabled":o?"":void 0,...c,ref:t})})});zf.displayName=ga;var Jf="CollapsibleTrigger",Yf=F((e,t)=>{const{__scopeCollapsible:n,...r}=e,i=Qc(Jf,n);return a(se.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":el(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...r,ref:t,onClick:z(e.onClick,i.onOpenToggle)})});Yf.displayName=Jf;var Zc="CollapsibleContent",Xf=F((e,t)=>{const{forceMount:n,...r}=e,i=Qc(Zc,e.__scopeCollapsible);return a(nt,{present:n||i.open,children:({present:o})=>a(ON,{...r,ref:t,present:o})})});Xf.displayName=Zc;var ON=F((e,t)=>{const{__scopeCollapsible:n,present:r,children:i,...o}=e,s=Qc(Zc,n),[c,l]=I(r),d=B(null),u=we(t,d),p=B(0),m=p.current,f=B(0),g=f.current,h=s.open||c,v=B(h),b=B(void 0);return K(()=>{const w=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(w)},[]),We(()=>{const w=d.current;if(w){b.current=b.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,v.current||(w.style.transitionDuration=b.current.transitionDuration,w.style.animationName=b.current.animationName),l(r)}},[s.open,r]),a(se.div,{"data-state":el(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":g?`${g}px`:void 0,...e.style},children:h&&i})});function el(e){return e?"open":"closed"}var va=zf,Qf=Yf,ya=Xf,jN=["top","right","bottom","left"],_n=Math.min,vt=Math.max,ba=Math.round,_a=Math.floor,Ut=e=>({x:e,y:e}),FN={left:"right",right:"left",bottom:"top",top:"bottom"};function tl(e,t,n){return vt(e,_n(t,n))}function on(e,t){return typeof e=="function"?e(t):e}function an(e){return e.split("-")[0]}function $r(e){return e.split("-")[1]}function nl(e){return e==="x"?"y":"x"}function rl(e){return e==="y"?"height":"width"}function Gt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function il(e){return nl(Gt(e))}function BN(e,t,n){n===void 0&&(n=!1);const r=$r(e),i=il(e),o=rl(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(s=wa(s)),[s,wa(s)]}function UN(e){const t=wa(e);return[ol(e),t,ol(t)]}function ol(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}var Zf=["left","right"],eh=["right","left"],GN=["top","bottom"],HN=["bottom","top"];function KN(e,t,n){switch(e){case"top":case"bottom":return n?t?eh:Zf:t?Zf:eh;case"left":case"right":return t?GN:HN;default:return[]}}function qN(e,t,n,r){const i=$r(e);let o=KN(an(e),n==="start",r);return i&&(o=o.map(s=>s+"-"+i),t&&(o=o.concat(o.map(ol)))),o}function wa(e){const t=an(e);return FN[t]+e.slice(t.length)}function WN(e){return{top:0,right:0,bottom:0,left:0,...e}}function th(e){return typeof e!="number"?WN(e):{top:e,right:e,bottom:e,left:e}}function Sa(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 nh(e,t,n){let{reference:r,floating:i}=e;const o=Gt(t),s=il(t),c=rl(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($r(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 VN(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),g=th(f),h=c[m?p==="floating"?"reference":"floating":p],v=Sa(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})),b=p==="floating"?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,w=await(o.getOffsetParent==null?void 0:o.getOffsetParent(c.floating)),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=Sa(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:b,offsetParent:w,strategy:l}):b);return{top:(v.top-T.top+g.top)/S.y,bottom:(T.bottom-v.bottom+g.bottom)/S.y,left:(v.left-T.left+g.left)/S.x,right:(T.right-v.right+g.right)/S.x}}var zN=50,JN=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:VN},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}=nh(d,r,l),m=r,f=0;const g={};for(let h=0;h<o.length;h++){const v=o[h];if(!v)continue;const{name:b,fn:w}=v,{x:S,y:T,data:N,reset:P}=await w({x:u,y:p,initialPlacement:r,placement:m,strategy:i,middlewareData:g,rects:d,platform:c,elements:{reference:e,floating:t}});u=S??u,p=T??p,g[b]={...g[b],...N},P&&f<zN&&(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}=nh(d,m,l)),h=-1)}return{x:u,y:p,placement:m,strategy:i,middlewareData:g}},YN=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=th(u),m={x:n,y:r},f=il(i),g=rl(f),h=await s.getDimensions(d),v=f==="y",b=v?"top":"left",w=v?"bottom":"right",S=v?"clientHeight":"clientWidth",T=o.reference[g]+o.reference[f]-m[f]-o.floating[g],N=m[f]-o.reference[f],P=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=P?P[S]:0;(!A||!await(s.isElement==null?void 0:s.isElement(P)))&&(A=c.floating[S]||o.floating[g]);const M=T/2-N/2,U=A/2-h[g]/2-1,x=_n(p[b],U),G=_n(p[w],U),E=x,$=A-h[g]-G,L=A/2-h[g]/2+M,J=tl(E,L,$),H=!l.arrow&&$r(i)!=null&&L!==J&&o.reference[g]/2-(L<E?x:G)-h[g]/2<0,k=H?L<E?L-E:L-$:0;return{[f]:m[f]+k,data:{[f]:J,centerOffset:L-J-k,...H&&{alignmentOffset:k}},reset:H}}}),XN=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:g="none",flipAlignment:h=!0,...v}=on(e,t);if((n=o.arrow)!=null&&n.alignmentOffset)return{};const b=an(i),w=Gt(c),S=an(c)===c,T=await(l.isRTL==null?void 0:l.isRTL(d.floating)),N=m||(S||!h?[wa(c)]:UN(c)),P=g!=="none";!m&&P&&N.push(...qN(c,h,g,T));const A=[c,...N],M=await l.detectOverflow(t,v),U=[];let x=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&U.push(M[b]),p){const L=BN(i,s,T);U.push(M[L[0]],M[L[1]])}if(x=[...x,{placement:i,overflows:U}],!U.every(L=>L<=0)){var G,E;const L=(((G=o.flip)==null?void 0:G.index)||0)+1,J=A[L];if(J&&(!(p==="alignment"&&w!==Gt(J))||x.every(k=>Gt(k.placement)===w?k.overflows[0]>0:!0)))return{data:{index:L,overflows:x},reset:{placement:J}};let H=(E=x.filter(k=>k.overflows[0]<=0).sort((k,R)=>k.overflows[1]-R.overflows[1])[0])==null?void 0:E.placement;if(!H)switch(f){case"bestFit":{var $;const k=($=x.filter(R=>{if(P){const j=Gt(R.placement);return j===w||j==="y"}return!0}).map(R=>[R.placement,R.overflows.filter(j=>j>0).reduce((j,W)=>j+W,0)]).sort((R,j)=>R[1]-j[1])[0])==null?void 0:$[0];k&&(H=k);break}case"initialPlacement":H=c;break}if(i!==H)return{reset:{placement:H}}}return{}}}};function rh(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 jN.some(t=>e[t]>=0)}var QN=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=rh(await r.detectOverflow(t,{...o,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:ih(s)}}}case"escaped":{const s=rh(await r.detectOverflow(t,{...o,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:ih(s)}}}default:return{}}}}},oh=new Set(["left","top"]);async function ZN(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=$r(n),l=Gt(n)==="y",d=oh.has(s)?-1:1,u=o&&l?-1:1,p=on(t,e);let{mainAxis:m,crossAxis:f,alignmentAxis:g}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return c&&typeof g=="number"&&(f=c==="end"?g*-1:g),l?{x:f*u,y:m*d}:{x:m*d,y:f*u}}var ek=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 ZN(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}}}}},tk=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:s=!0,crossAxis:c=!1,limiter:l={fn:b=>{let{x:w,y:S}=b;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=nl(m);let g=u[f],h=u[m];if(s){const b=f==="y"?"top":"left",w=f==="y"?"bottom":"right",S=g+p[b],T=g-p[w];g=tl(S,g,T)}if(c){const b=m==="y"?"top":"left",w=m==="y"?"bottom":"right",S=h+p[b],T=h-p[w];h=tl(S,h,T)}const v=l.fn({...t,[f]:g,[m]:h});return{...v,data:{x:v.x-n,y:v.y-r,enabled:{[f]:s,[m]:c}}}}}},nk=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=nl(p);let f=u[m],g=u[p];const h=on(c,t),v=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]+v.mainAxis,N=o.reference[m]+o.reference[S]-v.mainAxis;f<T?f=T:f>N&&(f=N)}if(d){var b,w;const S=m==="y"?"width":"height",T=oh.has(an(i)),N=o.reference[p]-o.floating[S]+(T&&((b=s.offset)==null?void 0:b[p])||0)+(T?0:v.crossAxis),P=o.reference[p]+o.reference[S]+(T?0:((w=s.offset)==null?void 0:w[p])||0)-(T?v.crossAxis:0);g<N?g=N:g>P&&(g=P)}return{[m]:f,[p]:g}}}},rk=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=$r(i),f=Gt(i)==="y",{width:g,height:h}=o.floating;let v,b;p==="top"||p==="bottom"?(v=p,b=m===(await(s.isRTL==null?void 0:s.isRTL(c.floating))?"start":"end")?"left":"right"):(b=p,v=m==="end"?"top":"bottom");const w=h-u.top-u.bottom,S=g-u.left-u.right,T=_n(h-u[v],w),N=_n(g-u[b],S),P=!t.middlewareData.shift;let A=T,M=N;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(A=w),P&&!m){const x=vt(u.left,0),G=vt(u.right,0),E=vt(u.top,0),$=vt(u.bottom,0);f?M=g-2*(x!==0||G!==0?x+G:vt(u.left,u.right)):A=h-2*(E!==0||$!==0?E+$:vt(u.top,u.bottom))}await l({...t,availableWidth:M,availableHeight:A});const U=await s.getDimensions(c.floating);return g!==U.width||h!==U.height?{reset:{rects:!0}}:{}}}};function Ca(){return typeof window<"u"}function Mr(e){return ah(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=(ah(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function ah(e){return Ca()?e instanceof Node||e instanceof yt(e).Node:!1}function Pt(e){return Ca()?e instanceof Element||e instanceof yt(e).Element:!1}function sn(e){return Ca()?e instanceof HTMLElement||e instanceof yt(e).HTMLElement:!1}function sh(e){return!Ca()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof yt(e).ShadowRoot}function $i(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Et(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function ik(e){return/^(table|td|th)$/.test(Mr(e))}function Ta(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}var ok=/transform|translate|scale|rotate|perspective|filter/,ak=/paint|layout|strict|content/,Xn=e=>!!e&&e!=="none",al;function sl(e){const t=Pt(e)?Et(e):e;return Xn(t.transform)||Xn(t.translate)||Xn(t.scale)||Xn(t.rotate)||Xn(t.perspective)||!cl()&&(Xn(t.backdropFilter)||Xn(t.filter))||ok.test(t.willChange||"")||ak.test(t.contain||"")}function sk(e){let t=wn(e);for(;sn(t)&&!Or(t);){if(sl(t))return t;if(Ta(t))return null;t=wn(t)}return null}function cl(){return al==null&&(al=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),al}function Or(e){return/^(html|body|#document)$/.test(Mr(e))}function Et(e){return yt(e).getComputedStyle(e)}function Na(e){return Pt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function wn(e){if(Mr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||sh(e)&&e.host||Ht(e);return sh(t)?t.host:t}function ch(e){const t=wn(e);return Or(t)?e.ownerDocument?e.ownerDocument.body:e.body:sn(t)&&$i(t)?t:ch(t)}function Mi(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=ch(e),o=i===((r=e.ownerDocument)==null?void 0:r.body),s=yt(i);if(o){const c=ll(s);return t.concat(s,s.visualViewport||[],$i(i)?i:[],c&&n?Mi(c):[])}else return t.concat(i,Mi(i,[],n))}function ll(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function lh(e){const t=Et(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=ba(n)!==o||ba(r)!==s;return c&&(n=o,r=s),{width:n,height:r,$:c}}function dl(e){return Pt(e)?e:e.contextElement}function jr(e){const t=dl(e);if(!sn(t))return Ut(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=lh(t);let s=(o?ba(n.width):n.width)/r,c=(o?ba(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!c||!Number.isFinite(c))&&(c=1),{x:s,y:c}}var ck=Ut(0);function dh(e){const t=yt(e);return!cl()||!t.visualViewport?ck:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function lk(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==yt(e)?!1:t}function Qn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),o=dl(e);let s=Ut(1);t&&(r?Pt(r)&&(s=jr(r)):s=jr(e));const c=lk(o,n,r)?dh(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 g=m,h=ll(g);for(;h&&r&&f!==g;){const v=jr(h),b=h.getBoundingClientRect(),w=Et(h),S=b.left+(h.clientLeft+parseFloat(w.paddingLeft))*v.x,T=b.top+(h.clientTop+parseFloat(w.paddingTop))*v.y;l*=v.x,d*=v.y,u*=v.x,p*=v.y,l+=S,d+=T,g=yt(h),h=ll(g)}}return Sa({width:u,height:p,x:l,y:d})}function ka(e,t){const n=Na(e).scrollLeft;return t?t.left+n:Qn(Ht(e)).left+n}function uh(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ka(e,n),y:n.top+t.scrollTop}}function dk(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o=i==="fixed",s=Ht(r),c=t?Ta(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)&&((Mr(r)!=="body"||$i(s))&&(l=Na(r)),p)){const f=Qn(r);d=jr(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const m=s&&!p&&!o?uh(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 uk(e){return Array.from(e.getClientRects())}function pk(e){const t=Ht(e),n=Na(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 Et(r).direction==="rtl"&&(s+=vt(t.clientWidth,r.clientWidth)-i),{width:i,height:o,x:s,y:c}}var ph=25;function mk(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=cl();(!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,g=Math.abs(r.clientWidth-p.clientWidth-f);g<=ph&&(o-=g)}else d<=ph&&(o+=d);return{width:o,height:s,x:c,y:l}}function fk(e,t){const n=Qn(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=sn(e)?jr(e):Ut(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=mk(e,n);else if(t==="document")r=pk(Ht(e));else if(Pt(t))r=fk(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 Sa(r)}function fh(e,t){const n=wn(e);return n===t||!Pt(n)||Or(n)?!1:Et(n).position==="fixed"||fh(n,t)}function hk(e,t){const n=t.get(e);if(n)return n;let r=Mi(e,[],!1).filter(c=>Pt(c)&&Mr(c)!=="body"),i=null;const o=Et(e).position==="fixed";let s=o?wn(e):e;for(;Pt(s)&&!Or(s);){const c=Et(s),l=sl(s);!l&&c.position==="fixed"&&(i=null),(o?!l&&!i:!l&&c.position==="static"&&i&&(i.position==="absolute"||i.position==="fixed")||$i(s)&&!l&&fh(e,s))?r=r.filter(d=>d!==s):i=c,s=wn(s)}return t.set(e,r),r}function gk(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?Ta(t)?[]:hk(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 m=mh(t,o[p],i);c=vt(m.top,c),l=_n(m.right,l),d=_n(m.bottom,d),u=vt(m.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function vk(e){const{width:t,height:n}=lh(e);return{width:t,height:n}}function yk(e,t,n){const r=sn(t),i=Ht(t),o=n==="fixed",s=Qn(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((Mr(t)!=="body"||$i(i))&&(c=Na(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?uh(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 ul(e){return Et(e).position==="static"}function hh(e,t){if(!sn(e)||Et(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Ht(e)===n&&(n=n.ownerDocument.body),n}function gh(e,t){const n=yt(e);if(Ta(e))return n;if(!sn(e)){let i=wn(e);for(;i&&!Or(i);){if(Pt(i)&&!ul(i))return i;i=wn(i)}return n}let r=hh(e,t);for(;r&&ik(r)&&ul(r);)r=hh(r,t);return r&&Or(r)&&ul(r)&&!sl(r)?n:r||sk(e)||n}var bk=async function(e){const t=this.getOffsetParent||gh,n=this.getDimensions,r=await n(e.floating);return{reference:yk(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function _k(e){return Et(e).direction==="rtl"}var wk={convertOffsetParentRelativeRectToViewportRelativeRect:dk,getDocumentElement:Ht,getClippingRect:gk,getOffsetParent:gh,getElementRects:bk,getClientRects:uk,getDimensions:vk,getScale:jr,isElement:Pt,isRTL:_k};function vh(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Sk(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 g=_a(p),h=_a(i.clientWidth-(u+m)),v=_a(i.clientHeight-(p+f)),b=_a(u),w={rootMargin:-g+"px "+-h+"px "+-v+"px "+-b+"px",threshold:vt(0,_n(1,l))||1};let S=!0;function T(N){const P=N[0].intersectionRatio;if(P!==l){if(!S)return s();P?s(!1,P):r=setTimeout(()=>{s(!1,1e-7)},1e3)}P===1&&!vh(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 Ck(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=dl(e),u=i||o?[...d?Mi(d):[],...t?Mi(t):[]]:[];u.forEach(b=>{i&&b.addEventListener("scroll",n,{passive:!0}),o&&b.addEventListener("resize",n)});const p=d&&c?Sk(d,n):null;let m=-1,f=null;s&&(f=new ResizeObserver(b=>{let[w]=b;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 g,h=l?Qn(e):null;l&&v();function v(){const b=Qn(e);h&&!vh(h,b)&&n(),h=b,g=requestAnimationFrame(v)}return n(),()=>{var b;u.forEach(w=>{i&&w.removeEventListener("scroll",n),o&&w.removeEventListener("resize",n)}),p?.(),(b=f)==null||b.disconnect(),f=null,l&&cancelAnimationFrame(g)}}var Tk=ek,Nk=tk,kk=XN,xk=rk,Pk=QN,yh=YN,Ek=nk,Ak=(e,t,n)=>{const r=new Map,i={platform:wk,...n},o={...i.platform,_c:r};return JN(e,t,{...i,platform:o})},xa=typeof document<"u"?gt:function(){};function Pa(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(!Pa(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)&&!Pa(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function bh(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function _h(e,t){const n=bh(e);return Math.round(t*n)/n}function pl(e){const t=B(e);return xa(()=>{t.current=e}),t}function Ik(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);Pa(m,r)||f(r);const[g,h]=I(null),[v,b]=I(null),w=re(R=>{R!==P.current&&(P.current=R,h(R))},[]),S=re(R=>{R!==A.current&&(A.current=R,b(R))},[]),T=o||g,N=s||v,P=B(null),A=B(null),M=B(u),U=l!=null,x=pl(l),G=pl(i),E=pl(d),$=re(()=>{if(!P.current||!A.current)return;const R={placement:t,strategy:n,middleware:m};G.current&&(R.platform=G.current),Ak(P.current,A.current,R).then(j=>{const W={...j,isPositioned:E.current!==!1};L.current&&!Pa(M.current,W)&&(M.current=W,jo(()=>{p(W)}))})},[m,t,n,G,E]);xa(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,p(R=>({...R,isPositioned:!1})))},[d]);const L=B(!1);xa(()=>(L.current=!0,()=>{L.current=!1}),[]),xa(()=>{if(T&&(P.current=T),N&&(A.current=N),T&&N){if(x.current)return x.current(T,N,$);$()}},[T,N,$,x,U]);const J=ke(()=>({reference:P,floating:A,setReference:w,setFloating:S}),[w,S]),H=ke(()=>({reference:T,floating:N}),[T,N]),k=ke(()=>{const R={position:n,left:0,top:0};if(!H.floating)return R;const j=_h(H.floating,u.x),W=_h(H.floating,u.y);return c?{...R,transform:"translate("+j+"px, "+W+"px)",...bh(H.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:j,top:W}},[n,c,H.floating,u.x,u.y]);return ke(()=>({...u,update:$,refs:J,elements:H,floatingStyles:k}),[u,$,J,H,k])}var Rk=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?yh({element:r.current,padding:i}).fn(n):{}:r?yh({element:r,padding:i}).fn(n):{}}}},Dk=(e,t)=>{const n=Tk(e);return{name:n.name,fn:n.fn,options:[e,t]}},Lk=(e,t)=>{const n=Nk(e);return{name:n.name,fn:n.fn,options:[e,t]}},$k=(e,t)=>({fn:Ek(e).fn,options:[e,t]}),Mk=(e,t)=>{const n=kk(e);return{name:n.name,fn:n.fn,options:[e,t]}},Ok=(e,t)=>{const n=xk(e);return{name:n.name,fn:n.fn,options:[e,t]}},jk=(e,t)=>{const n=Pk(e);return{name:n.name,fn:n.fn,options:[e,t]}},Fk=(e,t)=>{const n=Rk(e);return{name:n.name,fn:n.fn,options:[e,t]}},Bk="Arrow",wh=F((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"})})});wh.displayName=Bk;var Uk=wh;function ml(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 fl="Popper",[Sh,Sn]=st(fl),[Gk,Ch]=Sh(fl),Th=e=>{const{__scopePopper:t,children:n}=e,[r,i]=I(null);return a(Gk,{scope:t,anchor:r,onAnchorChange:i,children:n})};Th.displayName=fl;var Nh="PopperAnchor",kh=F((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,o=Ch(Nh,n),s=B(null),c=we(t,s),l=B(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})});kh.displayName=Nh;var hl="PopperContent",[Hk,Kk]=Sh(hl),xh=F((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:g,...h}=e,v=Ch(hl,n),[b,w]=I(null),S=we(t,X=>w(X)),[T,N]=I(null),P=ml(T),A=P?.width??0,M=P?.height??0,U=r+(o!=="center"?"-"+o:""),x=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},G=Array.isArray(d)?d:[d],E=G.length>0,$={padding:x,boundary:G.filter(Wk),altBoundary:E},{refs:L,floatingStyles:J,placement:H,isPositioned:k,middlewareData:R}=Ik({strategy:"fixed",placement:U,whileElementsMounted:(...X)=>Ck(...X,{animationFrame:f==="always"}),elements:{reference:v.anchor},middleware:[Dk({mainAxis:i+M,alignmentAxis:s}),l&&Lk({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?$k():void 0,...$}),l&&Mk({...$}),Ok({...$,apply:({elements:X,rects:_e,availableWidth:he,availableHeight:Q})=>{const{width:$e,height:ue}=_e.reference,q=X.floating.style;q.setProperty("--radix-popper-available-width",`${he}px`),q.setProperty("--radix-popper-available-height",`${Q}px`),q.setProperty("--radix-popper-anchor-width",`${$e}px`),q.setProperty("--radix-popper-anchor-height",`${ue}px`)}}),T&&Fk({element:T,padding:c}),Vk({arrowWidth:A,arrowHeight:M}),m&&jk({strategy:"referenceHidden",...$})]}),[j,W]=Ah(H),ge=lt(g);We(()=>{k&&ge?.()},[k,ge]);const le=R.arrow?.x,ce=R.arrow?.y,be=R.arrow?.centerOffset!==0,[Y,fe]=I();return We(()=>{b&&fe(window.getComputedStyle(b).zIndex)},[b]),a("div",{ref:L.setFloating,"data-radix-popper-content-wrapper":"",style:{...J,transform:k?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(Hk,{scope:n,placedSide:j,onArrowChange:N,arrowX:le,arrowY:ce,shouldHideArrow:be,children:a(se.div,{"data-side":j,"data-align":W,...h,ref:S,style:{...h.style,animation:k?void 0:"none"}})})})});xh.displayName=hl;var Ph="PopperArrow",qk={top:"bottom",right:"left",bottom:"top",left:"right"},Eh=F(function(t,n){const{__scopePopper:r,...i}=t,o=Kk(Ph,r),s=qk[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(Uk,{...i,ref:n,style:{...i.style,display:"block"}})})});Eh.displayName=Ph;function Wk(e){return e!==null}var Vk=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]=Ah(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="",g="";return l==="bottom"?(f=o?u:`${p}px`,g=`${-c}px`):l==="top"?(f=o?u:`${p}px`,g=`${r.floating.height+c}px`):l==="right"?(f=`${-c}px`,g=o?u:`${m}px`):l==="left"&&(f=`${r.floating.width+c}px`,g=o?u:`${m}px`),{data:{x:f,y:g}}}});function Ah(e){const[t,n="center"]=e.split("-");return[t,n]}var Oi=Th,ji=kh,Ea=xh,Aa=Eh,Ia="Popover",[Ih,GO]=st(Ia,[Sn]),Fi=Sn(),[zk,Cn]=Ih(Ia),Rh=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!1}=e,c=Fi(t),l=B(null),[d,u]=I(!1),[p,m]=wt({prop:r,defaultProp:i??!1,onChange:o,caller:Ia});return a(Oi,{...c,children:a(zk,{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})})};Rh.displayName=Ia;var Dh="PopoverAnchor",Lh=F((e,t)=>{const{__scopePopover:n,...r}=e,i=Cn(Dh,n),o=Fi(n),{onCustomAnchorAdd:s,onCustomAnchorRemove:c}=i;return K(()=>(s(),()=>c()),[s,c]),a(ji,{...o,...r,ref:t})});Lh.displayName=Dh;var $h="PopoverTrigger",Mh=F((e,t)=>{const{__scopePopover:n,...r}=e,i=Cn($h,n),o=Fi(n),s=we(t,i.triggerRef),c=a(se.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Uh(i.open),...r,ref:s,onClick:z(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:a(ji,{asChild:!0,...o,children:c})});Mh.displayName=$h;var gl="PopoverPortal",[Jk,Yk]=Ih(gl,{forceMount:void 0}),Oh=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,o=Cn(gl,t);return a(Jk,{scope:t,forceMount:n,children:a(nt,{present:n||o.open,children:a(qn,{asChild:!0,container:i,children:r})})})};Oh.displayName=gl;var Fr="PopoverContent",jh=F((e,t)=>{const n=Yk(Fr,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,o=Cn(Fr,e.__scopePopover);return a(nt,{present:r||o.open,children:o.modal?a(Qk,{...i,ref:t}):a(Zk,{...i,ref:t})})});jh.displayName=Fr;var Xk=Hn("PopoverContent.RemoveScroll"),Qk=F((e,t)=>{const n=Cn(Fr,e.__scopePopover),r=B(null),i=we(t,r),o=B(!1);return K(()=>{const s=r.current;if(s)return Jo(s)},[]),a(_i,{as:Xk,allowPinchZoom:!0,children:a(Fh,{...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})})})}),Zk=F((e,t)=>{const n=Cn(Fr,e.__scopePopover),r=B(!1),i=B(!1);return a(Fh,{...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()}})}),Fh=F((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:s,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onInteractOutside:u,...p}=e,m=Cn(Fr,n),f=Fi(n);return Uo(),a(yi,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:o,children:a(Kn,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:a(Ea,{"data-state":Uh(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)"}})})})}),Bh="PopoverClose",ex=F((e,t)=>{const{__scopePopover:n,...r}=e,i=Cn(Bh,n);return a(se.button,{type:"button",...r,ref:t,onClick:z(e.onClick,()=>i.onOpenChange(!1))})});ex.displayName=Bh;var tx="PopoverArrow",nx=F((e,t)=>{const{__scopePopover:n,...r}=e,i=Fi(n);return a(Aa,{...i,...r,ref:t})});nx.displayName=tx;function Uh(e){return e?"open":"closed"}var Gh=Rh,rx=Lh,ix=Mh,Hh=Oh,Kh=jh;function vl(e){return e.trim()}function qh({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=B(null),g=ke(()=>{const x=new Set,G=[];for(const E of[...n,...e]){const $=vl(E);!$||x.has($)||(x.add($),G.push($))}return G.sort((E,$)=>E.localeCompare($))},[n,e]),h=vl(d),v=h.toLowerCase(),b=ke(()=>v?g.filter(x=>x.toLowerCase().includes(v)):g,[g,v]),w=h?g.some(x=>x.toLowerCase()===v):!1,S=!!h&&!w,T=b.length+(S?1:0);K(()=>{p>=T&&m(Math.max(0,T-1))},[T,p]),K(()=>{if(!c)return;const x=requestAnimationFrame(()=>f.current?.focus());return()=>cancelAnimationFrame(x)},[c]);const N=x=>{e.includes(x)?t(e.filter(G=>G!==x)):t(Array.from(new Set([...e,x])))},P=x=>{const G=vl(x);G&&(t(Array.from(new Set([...e,G]))),u(""),m(0))},A=x=>{if(x<b.length){const G=b[x];G&&N(G);return}S&&P(h)},M=x=>{if(x.key==="ArrowDown"){x.preventDefault(),m(G=>Math.min(T-1,G+1));return}if(x.key==="ArrowUp"){x.preventDefault(),m(G=>Math.max(0,G-1));return}if(x.key==="Enter"){x.preventDefault(),A(p);return}},U=x=>{t(e.filter(G=>G!==x))};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(x=>a("li",{class:"project-scope-picker-selected-chip",children:[a("span",{children:x}),o?null:a("button",{"aria-label":`Remove ${x}`,class:"project-scope-picker-selected-remove",onClick:()=>U(x),type:"button",children:"×"})]},x))}),a(Gh,{onOpenChange:x=>{l(x),x||(u(""),m(0))},open:c,children:[a(ix,{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(Hh,{children:a(Kh,{align:"start",class:"project-scope-picker-popover",sideOffset:6,children:[a("input",{"aria-label":"Search projects",class:"project-scope-picker-search",onInput:x=>{u(x.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:[b.length===0&&!S?a("div",{class:"project-scope-picker-empty-row",children:"No projects yet. Type a name to create one."}):null,b.map((x,G)=>{const E=e.includes(x);return a("button",{"aria-selected":E,class:G===p?"project-scope-picker-row project-scope-picker-row--active":"project-scope-picker-row",onClick:()=>{m(G),N(x)},onMouseEnter:()=>m(G),role:"option",type:"button",children:[a("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:E?"✓":""}),a("span",{class:"project-scope-picker-row-label",children:x})]},x)}),S?a("button",{"aria-selected":!1,class:p===b.length?"project-scope-picker-row project-scope-picker-row--create project-scope-picker-row--active":"project-scope-picker-row project-scope-picker-row--create",onClick:()=>P(h),onMouseEnter:()=>m(b.length),role:"option",type:"button",children:[a("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:"+"}),a("span",{class:"project-scope-picker-row-label",children:`Create "${h}"`})]}):null]})]})})]})]})}function yl(e){const t=B({value:e,previous:e});return ke(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Ra="Switch",[ox,HO]=st(Ra),[ax,sx]=ox(Ra),Wh=F((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),g=we(t,S=>f(S)),h=B(!1),v=m?u||!!m.closest("form"):!0,[b,w]=wt({prop:i,defaultProp:o??!1,onChange:d,caller:Ra});return a(ax,{scope:n,checked:b,disabled:c,children:[a(se.button,{type:"button",role:"switch","aria-checked":b,"aria-required":s,"data-state":Yh(b),"data-disabled":c?"":void 0,disabled:c,value:l,...p,ref:g,onClick:z(e.onClick,S=>{w(T=>!T),v&&(h.current=S.isPropagationStopped(),h.current||S.stopPropagation())})}),v&&a(Jh,{control:m,bubbles:!h.current,name:r,value:l,checked:b,required:s,disabled:c,form:u,style:{transform:"translateX(-100%)"}})]})});Wh.displayName=Ra;var Vh="SwitchThumb",zh=F((e,t)=>{const{__scopeSwitch:n,...r}=e,i=sx(Vh,n);return a(se.span,{"data-state":Yh(i.checked),"data-disabled":i.disabled?"":void 0,...r,ref:t})});zh.displayName=Vh;var cx="SwitchBubbleInput",Jh=F(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...i},o)=>{const s=B(null),c=we(s,o),l=yl(n),d=ml(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}})});Jh.displayName=cx;function Yh(e){return e?"checked":"unchecked"}var lx=Wh,dx=zh;function Br({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:o,onCheckedChange:s,thumbClassName:c}){return a(lx,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:o,onCheckedChange:s,children:a(dx,{className:c})})}function ne(e,t="success"){qT(e,t)}function Xh(e){return`${DN}:${String(e||"").trim()}`}function ux(e){try{return localStorage.getItem(Xh(e))||""}catch{return""}}function px(e,t){try{localStorage.setItem(Xh(e),t)}catch{}}function Zn(){return String(_.coordinatorAdminTargetGroup||"").trim()}function bl(e){_.coordinatorAdminTargetGroup=e,px(_.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function Ur(){return(Array.isArray(_.lastCoordinatorAdminGroups)?_.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 mx(){const e=new Map;for(const t of Ur())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 fx(){const e=Zn();return Ur().find(t=>t.group_id===e)||null}function Qh(){const e=_.lastCoordinatorAdminStatus,t=Ur(),n=String(e?.active_group||"").trim(),r=ux(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 bl(c),c}function hx(){const e=new Map,t=new Map,n=Array.isArray(_.lastCoordinatorAdminDevices)?_.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 gx(e,t){return t&&t.groupId===e?t:null}function vx(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 yx(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 bx(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function _x(e){const t=bx(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function wx(e){const t=gx(e.groupId,e.setupGuide);return{autoGrant:yx(e.preferences,t),defaultSpace:vx(e.preferences,t),spaces:_x(e.scopeManagement)}}var _l=null,Da=null,wl=null;function Sx(){return _l}function Sl(e){Da=e}function Zh(e){wl=e}function Cx(e){return wl===e}function Tx(e){return e?e.kind==="confirm"?!1:e.kind==="input"?null:{action:"cancel"}:null}function Cl(e){return!_l||!Da?!0:(console.warn(`Ignored sync ${e} dialog request because another sync dialog is already open.`),!1)}function La(e){_l=e,wl?.(e)}function Tn(e){const t=Da;Da=null,La(null),t?.(e)}function Nx(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var kx=F(function({value:t,onValueChange:n,suggestions:r,onSubmit:i,maxSuggestions:o=20,onKeyDown:s,onFocus:c,onBlur:l,className:d,...u},p){const m=B(null);Lo(p,()=>m.current,[]);const[f,g]=I(!1),[h,v]=I(-1),b=ke(()=>{const N=t.trim().toLowerCase();return(N?r.filter(P=>P.toLowerCase().includes(N)):r).slice(0,o)},[t,r,o]);K(()=>{h>=b.length&&v(b.length-1)},[b.length,h]);const w=f&&b.length>0,S=N=>{n(N),g(!1),v(-1),m.current?.focus()};return a(Gh,{open:w,onOpenChange:g,children:[a(rx,{asChild:!0,children:a("input",{...u,ref:m,className:d,value:t,onInput:N=>{n(N.currentTarget.value),g(!0),v(-1)},onFocus:N=>{c?.(N)},onBlur:N=>{window.setTimeout(()=>g(!1),120),l?.(N)},onKeyDown:N=>{if(N.key==="ArrowDown"){N.preventDefault(),g(!0),v(P=>b.length===0?-1:Math.min(P+1,b.length-1));return}if(N.key==="ArrowUp"){N.preventDefault(),f||g(!0),v(P=>Math.max(P-1,-1));return}if(N.key==="Escape"&&w){N.preventDefault(),g(!1),v(-1);return}if((N.key==="Tab"||N.key==="Enter")&&h>=0){const P=b[h];if(P){N.preventDefault(),S(P);return}}if(N.key==="Enter"&&i){N.preventDefault(),i();return}s?.(N)},role:"combobox","aria-autocomplete":"list","aria-expanded":w,"aria-controls":"autocompleteListbox","aria-activedescendant":h>=0?`autocomplete-option-${h}`:void 0})}),a(Hh,{children:a(Kh,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:N=>N.preventDefault(),onCloseAutoFocus:N=>N.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:a("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:b.map((N,P)=>{const A=P===h;return a("div",{"aria-selected":A,className:A?"autocomplete-option active":"autocomplete-option",id:`autocomplete-option-${P}`,onMouseDown:M=>{M.preventDefault(),S(N)},onMouseEnter:()=>v(P),role:"option",tabIndex:-1,children:N},N)})})})})]})}),Tl="Radio",[xx,eg]=st(Tl),[Px,Ex]=xx(Tl),tg=F((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=we(t,v=>m(v)),g=B(!1),h=p?d||!!p.closest("form"):!0;return a(Px,{scope:n,checked:i,disabled:s,children:[a(se.button,{type:"button",role:"radio","aria-checked":i,"data-state":og(i),"data-disabled":s?"":void 0,disabled:s,value:c,...u,ref:f,onClick:z(e.onClick,v=>{i||l?.(),h&&(g.current=v.isPropagationStopped(),g.current||v.stopPropagation())})}),h&&a(ig,{control:p,bubbles:!g.current,name:r,value:c,checked:i,required:o,disabled:s,form:d,style:{transform:"translateX(-100%)"}})]})});tg.displayName=Tl;var ng="RadioIndicator",rg=F((e,t)=>{const{__scopeRadio:n,forceMount:r,...i}=e,o=Ex(ng,n);return a(nt,{present:r||o.checked,children:a(se.span,{"data-state":og(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:t})})});rg.displayName=ng;var Ax="RadioBubbleInput",ig=F(({__scopeRadio:e,control:t,checked:n,bubbles:r=!0,...i},o)=>{const s=B(null),c=we(s,o),l=yl(n),d=ml(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}})});ig.displayName=Ax;function og(e){return e?"checked":"unchecked"}var Ix=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],$a="RadioGroup",[Rx,KO]=st($a,[Lr,eg]),ag=Lr(),sg=eg(),[Dx,Lx]=Rx($a),cg=F((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=ag(n),g=Di(d),[h,v]=wt({prop:o,defaultProp:i??null,onChange:p,caller:$a});return a(Dx,{scope:n,name:r,required:s,disabled:c,value:h,onValueChange:v,children:a(Jc,{asChild:!0,...f,orientation:l,dir:g,loop:u,children:a(se.div,{role:"radiogroup","aria-required":s,"aria-orientation":l,"data-disabled":c?"":void 0,dir:g,...m,ref:t})})})});cg.displayName=$a;var lg="RadioGroupItem",dg=F((e,t)=>{const{__scopeRadioGroup:n,disabled:r,...i}=e,o=Lx(lg,n),s=o.disabled||r,c=ag(n),l=sg(n),d=B(null),u=we(t,d),p=o.value===i.value,m=B(!1);return K(()=>{const f=h=>{Ix.includes(h.key)&&(m.current=!0)},g=()=>m.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",g),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",g)}},[]),a(Yc,{asChild:!0,...c,focusable:!s,active:p,children:a(tg,{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()})})})});dg.displayName=lg;var $x="RadioGroupIndicator",ug=F((e,t)=>{const{__scopeRadioGroup:n,...r}=e;return a(rg,{...sg(n),...r,ref:t})});ug.displayName=$x;var Mx=cg,Ox=dg,jx=ug;function Fx({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:o,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return a(Mx,{"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}`,g=`radio-option-label-${m}`;return a("label",{className:i,htmlFor:f,children:[a(Ox,{id:f,"aria-labelledby":g,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:a(jx,{className:r})}),a("span",{className:o,id:g,children:p.label})]},p.value)})})}function pg(e,[t,n]){return Math.min(n,Math.max(t,e))}var Bx=[" ","Enter","ArrowUp","ArrowDown"],Ux=[" ","Enter"],er="Select",[Ma,Oa,Gx]=da(er),[Gr,qO]=st(er,[Gx,Sn]),ja=Sn(),[Hx,Nn]=Gr(er),[Kx,qx]=Gr(er),mg=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:g}=e,h=ja(t),[v,b]=I(null),[w,S]=I(null),[T,N]=I(!1),P=Di(d),[A,M]=wt({prop:r,defaultProp:i??!1,onChange:o,caller:er}),[U,x]=wt({prop:s,defaultProp:c,onChange:l,caller:er}),G=B(null),E=v?g||!!v.closest("form"):!0,[$,L]=I(new Set),J=Array.from($).map(H=>H.props.value).join(";");return a(Oi,{...h,children:a(Hx,{required:f,scope:t,trigger:v,onTriggerChange:b,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:T,onValueNodeHasChildrenChange:N,contentId:ct(),value:U,onValueChange:x,open:A,onOpenChange:M,dir:P,triggerPointerDownPosRef:G,disabled:m,children:[a(Ma.Provider,{scope:t,children:a(Kx,{scope:e.__scopeSelect,onNativeOptionAdd:re(H=>{L(k=>new Set(k).add(H))},[]),onNativeOptionRemove:re(H=>{L(k=>{const R=new Set(k);return R.delete(H),R})},[]),children:n})}),E?a(Dg,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:p,value:U,onChange:H=>x(H.target.value),disabled:m,form:g,children:[U===void 0?a("option",{value:""}):null,Array.from($)]},J):null]})})};mg.displayName=er;var fg="SelectTrigger",hg=F((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...i}=e,o=ja(n),s=Nn(fg,n),c=s.disabled||r,l=we(t,s.onTriggerChange),d=Oa(n),u=B("touch"),[p,m,f]=$g(h=>{const v=d().filter(w=>!w.disabled),b=Mg(v,h,v.find(w=>w.value===s.value));b!==void 0&&s.onValueChange(b.value)}),g=h=>{c||(s.onOpenChange(!0),f()),h&&(s.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return a(ji,{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":Lg(s.value)?"":void 0,...i,ref:l,onClick:z(i.onClick,h=>{h.currentTarget.focus(),u.current!=="mouse"&&g(h)}),onPointerDown:z(i.onPointerDown,h=>{u.current=h.pointerType;const v=h.target;v.hasPointerCapture(h.pointerId)&&v.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(g(h),h.preventDefault())}),onKeyDown:z(i.onKeyDown,h=>{const v=p.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&m(h.key),!(v&&h.key===" ")&&Bx.includes(h.key)&&(g(),h.preventDefault())})})})});hg.displayName=fg;var gg="SelectValue",vg=F((e,t)=>{const{__scopeSelect:n,className:r,style:i,children:o,placeholder:s="",...c}=e,l=Nn(gg,n),{onValueNodeHasChildrenChange:d}=l,u=o!==void 0,p=we(t,l.onValueNodeChange);return We(()=>{d(u)},[d,u]),a(se.span,{...c,ref:p,style:{pointerEvents:"none"},children:Lg(l.value)?a(te,{children:s}):o})});vg.displayName=gg;var Wx="SelectIcon",yg=F((e,t)=>{const{__scopeSelect:n,children:r,...i}=e;return a(se.span,{"aria-hidden":!0,...i,ref:t,children:r||"▼"})});yg.displayName=Wx;var Vx="SelectPortal",bg=e=>a(qn,{asChild:!0,...e});bg.displayName=Vx;var tr="SelectContent",_g=F((e,t)=>{const n=Nn(tr,e.__scopeSelect),[r,i]=I();if(We(()=>{i(new DocumentFragment)},[]),!n.open){const o=r;return o?en(a(wg,{scope:e.__scopeSelect,children:a(Ma.Slot,{scope:e.__scopeSelect,children:a("div",{children:e.children})})}),o):null}return a(Sg,{...e,ref:t})});_g.displayName=tr;var At=10,[wg,kn]=Gr(tr),zx="SelectContentImpl",Jx=Hn("SelectContent.RemoveScroll"),Sg=F((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:g,hideWhenDetached:h,avoidCollisions:v,...b}=e,w=Nn(tr,n),[S,T]=I(null),[N,P]=I(null),A=we(t,X=>T(X)),[M,U]=I(null),[x,G]=I(null),E=Oa(n),[$,L]=I(!1),J=B(!1);K(()=>{if(S)return Jo(S)},[S]),Uo();const H=re(X=>{const[_e,...he]=E().map(ue=>ue.ref.current),[Q]=he.slice(-1),$e=document.activeElement;for(const ue of X)if(ue===$e||(ue?.scrollIntoView({block:"nearest"}),ue===_e&&N&&(N.scrollTop=0),ue===Q&&N&&(N.scrollTop=N.scrollHeight),ue?.focus(),document.activeElement!==$e))return},[E,N]),k=re(()=>H([M,S]),[H,M,S]);K(()=>{$&&k()},[$,k]);const{onOpenChange:R,triggerPointerDownPosRef:j}=w;K(()=>{if(S){let X={x:0,y:0};const _e=Q=>{X={x:Math.abs(Math.round(Q.pageX)-(j.current?.x??0)),y:Math.abs(Math.round(Q.pageY)-(j.current?.y??0))}},he=Q=>{X.x<=10&&X.y<=10?Q.preventDefault():S.contains(Q.target)||R(!1),document.removeEventListener("pointermove",_e),j.current=null};return j.current!==null&&(document.addEventListener("pointermove",_e),document.addEventListener("pointerup",he,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",_e),document.removeEventListener("pointerup",he,{capture:!0})}}},[S,R,j]),K(()=>{const X=()=>R(!1);return window.addEventListener("blur",X),window.addEventListener("resize",X),()=>{window.removeEventListener("blur",X),window.removeEventListener("resize",X)}},[R]);const[W,ge]=$g(X=>{const _e=E().filter(Q=>!Q.disabled),he=Mg(_e,X,_e.find(Q=>Q.ref.current===document.activeElement));he&&setTimeout(()=>he.ref.current.focus())}),le=re((X,_e,he)=>{const Q=!J.current&&!he;(w.value!==void 0&&w.value===_e||Q)&&(U(X),Q&&(J.current=!0))},[w.value]),ce=re(()=>S?.focus(),[S]),be=re((X,_e,he)=>{const Q=!J.current&&!he;(w.value!==void 0&&w.value===_e||Q)&&G(X)},[w.value]),Y=r==="popper"?Nl:Cg,fe=Y===Nl?{side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:g,hideWhenDetached:h,avoidCollisions:v}:{};return a(wg,{scope:n,content:S,viewport:N,onViewportChange:P,itemRefCallback:le,selectedItem:M,onItemLeave:ce,itemTextRefCallback:be,focusSelectedItem:k,selectedItemText:x,position:r,isPositioned:$,searchRef:W,children:a(_i,{as:Jx,allowPinchZoom:!0,children:a(yi,{asChild:!0,trapped:w.open,onMountAutoFocus:X=>{X.preventDefault()},onUnmountAutoFocus:z(i,X=>{w.trigger?.focus({preventScroll:!0}),X.preventDefault()}),children:a(Kn,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:X=>X.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:a(Y,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:X=>X.preventDefault(),...b,...fe,onPlaced:()=>L(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:z(b.onKeyDown,X=>{const _e=X.ctrlKey||X.altKey||X.metaKey;if(X.key==="Tab"&&X.preventDefault(),!_e&&X.key.length===1&&ge(X.key),["ArrowUp","ArrowDown","Home","End"].includes(X.key)){let he=E().filter(Q=>!Q.disabled).map(Q=>Q.ref.current);if(["ArrowUp","End"].includes(X.key)&&(he=he.slice().reverse()),["ArrowUp","ArrowDown"].includes(X.key)){const Q=X.target,$e=he.indexOf(Q);he=he.slice($e+1)}setTimeout(()=>H(he)),X.preventDefault()}})})})})})})});Sg.displayName=zx;var Yx="SelectItemAlignedPosition",Cg=F((e,t)=>{const{__scopeSelect:n,onPlaced:r,...i}=e,o=Nn(tr,n),s=kn(tr,n),[c,l]=I(null),[d,u]=I(null),p=we(t,P=>u(P)),m=Oa(n),f=B(!1),g=B(!0),{viewport:h,selectedItem:v,selectedItemText:b,focusSelectedItem:w}=s,S=re(()=>{if(o.trigger&&o.valueNode&&c&&d&&h&&v&&b){const P=o.trigger.getBoundingClientRect(),A=d.getBoundingClientRect(),M=o.valueNode.getBoundingClientRect(),U=b.getBoundingClientRect();if(o.dir!=="rtl"){const he=U.left-A.left,Q=M.left-he,$e=P.left-Q,ue=P.width+$e,q=Math.max(ue,A.width),oe=window.innerWidth-At,qe=pg(Q,[At,Math.max(At,oe-q)]);c.style.minWidth=ue+"px",c.style.left=qe+"px"}else{const he=A.right-U.right,Q=window.innerWidth-M.right-he,$e=window.innerWidth-P.right-Q,ue=P.width+$e,q=Math.max(ue,A.width),oe=window.innerWidth-At,qe=pg(Q,[At,Math.max(At,oe-q)]);c.style.minWidth=ue+"px",c.style.right=qe+"px"}const x=m(),G=window.innerHeight-At*2,E=h.scrollHeight,$=window.getComputedStyle(d),L=parseInt($.borderTopWidth,10),J=parseInt($.paddingTop,10),H=parseInt($.borderBottomWidth,10),k=parseInt($.paddingBottom,10),R=L+J+E+k+H,j=Math.min(v.offsetHeight*5,R),W=window.getComputedStyle(h),ge=parseInt(W.paddingTop,10),le=parseInt(W.paddingBottom,10),ce=P.top+P.height/2-At,be=G-ce,Y=v.offsetHeight/2,fe=v.offsetTop+Y,X=L+J+fe,_e=R-X;if(X<=ce){const he=x.length>0&&v===x[x.length-1].ref.current;c.style.bottom="0px";const Q=d.clientHeight-h.offsetTop-h.offsetHeight,$e=X+Math.max(be,Y+(he?le:0)+Q+H);c.style.height=$e+"px"}else{const he=x.length>0&&v===x[0].ref.current;c.style.top="0px";const Q=Math.max(ce,L+h.offsetTop+(he?ge:0)+Y)+_e;c.style.height=Q+"px",h.scrollTop=X-ce+h.offsetTop}c.style.margin=`${At}px 0`,c.style.minHeight=j+"px",c.style.maxHeight=G+"px",r?.(),requestAnimationFrame(()=>f.current=!0)}},[m,o.trigger,o.valueNode,c,d,h,v,b,o.dir,r]);We(()=>S(),[S]);const[T,N]=I();return We(()=>{d&&N(window.getComputedStyle(d).zIndex)},[d]),a(Qx,{scope:n,contentWrapper:c,shouldExpandOnScrollRef:f,onScrollButtonChange:re(P=>{P&&g.current===!0&&(S(),w?.(),g.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}})})})});Cg.displayName=Yx;var Xx="SelectPopperPosition",Nl=F((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:i=At,...o}=e,s=ja(n);return a(Ea,{...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)"}})});Nl.displayName=Xx;var[Qx,kl]=Gr(tr,{}),xl="SelectViewport",Tg=F((e,t)=>{const{__scopeSelect:n,nonce:r,...i}=e,o=kn(xl,n),s=kl(xl,n),c=we(t,o.onViewportChange),l=B(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(Ma.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 g=window.innerHeight-At*2,h=parseFloat(p.style.minHeight),v=parseFloat(p.style.height),b=Math.max(h,v);if(b<g){const w=b+f,S=Math.min(g,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})})})]})});Tg.displayName=xl;var Ng="SelectGroup",[Zx,eP]=Gr(Ng),tP=F((e,t)=>{const{__scopeSelect:n,...r}=e,i=ct();return a(Zx,{scope:n,id:i,children:a(se.div,{role:"group","aria-labelledby":i,...r,ref:t})})});tP.displayName=Ng;var kg="SelectLabel",nP=F((e,t)=>{const{__scopeSelect:n,...r}=e,i=eP(kg,n);return a(se.div,{id:i.id,...r,ref:t})});nP.displayName=kg;var Fa="SelectItem",[rP,xg]=Gr(Fa),Pg=F((e,t)=>{const{__scopeSelect:n,value:r,disabled:i=!1,textValue:o,...s}=e,c=Nn(Fa,n),l=kn(Fa,n),d=c.value===r,[u,p]=I(o??""),[m,f]=I(!1),g=we(t,w=>l.itemRefCallback?.(w,r,i)),h=ct(),v=B("touch"),b=()=>{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(rP,{scope:n,value:r,disabled:i,textId:h,isSelected:d,onItemTextChange:re(w=>{p(S=>S||(w?.textContent??"").trim())},[]),children:a(Ma.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:g,onFocus:z(s.onFocus,()=>f(!0)),onBlur:z(s.onBlur,()=>f(!1)),onClick:z(s.onClick,()=>{v.current!=="mouse"&&b()}),onPointerUp:z(s.onPointerUp,()=>{v.current==="mouse"&&b()}),onPointerDown:z(s.onPointerDown,w=>{v.current=w.pointerType}),onPointerMove:z(s.onPointerMove,w=>{v.current=w.pointerType,i?l.onItemLeave?.():v.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===" "||(Ux.includes(w.key)&&b(),w.key===" "&&w.preventDefault())})})})})});Pg.displayName=Fa;var Bi="SelectItemText",Eg=F((e,t)=>{const{__scopeSelect:n,className:r,style:i,...o}=e,s=Nn(Bi,n),c=kn(Bi,n),l=xg(Bi,n),d=qx(Bi,n),[u,p]=I(null),m=we(t,b=>p(b),l.onItemTextChange,b=>c.itemTextRefCallback?.(b,l.value,l.disabled)),f=u?.textContent,g=ke(()=>a("option",{value:l.value,disabled:l.disabled,children:f},l.value),[l.disabled,l.value,f]),{onNativeOptionAdd:h,onNativeOptionRemove:v}=d;return We(()=>(h(g),()=>v(g)),[h,v,g]),a(te,{children:[a(se.span,{id:l.textId,...o,ref:m}),l.isSelected&&s.valueNode&&!s.valueNodeHasChildren?en(o.children,s.valueNode):null]})});Eg.displayName=Bi;var Ag="SelectItemIndicator",Ig=F((e,t)=>{const{__scopeSelect:n,...r}=e;return xg(Ag,n).isSelected?a(se.span,{"aria-hidden":!0,...r,ref:t}):null});Ig.displayName=Ag;var Pl="SelectScrollUpButton",iP=F((e,t)=>{const n=kn(Pl,e.__scopeSelect),r=kl(Pl,e.__scopeSelect),[i,o]=I(!1),s=we(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(Rg,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});iP.displayName=Pl;var El="SelectScrollDownButton",oP=F((e,t)=>{const n=kn(El,e.__scopeSelect),r=kl(El,e.__scopeSelect),[i,o]=I(!1),s=we(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(Rg,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});oP.displayName=El;var Rg=F((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...i}=e,o=kn("SelectScrollButton",n),s=B(null),c=Oa(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()})})}),aP="SelectSeparator",sP=F((e,t)=>{const{__scopeSelect:n,...r}=e;return a(se.div,{"aria-hidden":!0,...r,ref:t})});sP.displayName=aP;var Al="SelectArrow",cP=F((e,t)=>{const{__scopeSelect:n,...r}=e,i=ja(n),o=Nn(Al,n),s=kn(Al,n);return o.open&&s.position==="popper"?a(Aa,{...i,...r,ref:t}):null});cP.displayName=Al;var lP="SelectBubbleInput",Dg=F(({__scopeSelect:e,value:t,...n},r)=>{const i=B(null),o=we(r,i),s=yl(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:{...of,...n.style},ref:o,defaultValue:t})});Dg.displayName=lP;function Lg(e){return e===""||e===void 0}function $g(e){const t=lt(e),n=B(""),r=B(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 Mg(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=dP(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 dP(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var uP=mg,pP=hg,mP=vg,fP=yg,hP=bg,gP=_g,vP=Tg,yP=Pg,bP=Eg,_P=Ig,Og="__codemem-empty-select__";function wP(){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 SP(){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 Il(e){return e===""?Og:e}function CP(e){return e===Og?"":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?Il(u):void 0;return a(uP,{disabled:r,onValueChange:f=>s(CP(f)),value:m,children:[a(pP,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[a(mP,{placeholder:l}),a(fP,{className:"sync-radix-select-icon","aria-hidden":"true",children:a(wP,{})})]}),a(hP,{children:a(gP,{className:n,position:"popper",children:a(vP,{className:p,children:c.map(f=>a(yP,{className:o,disabled:f.disabled,value:Il(f.value),children:[a(bP,{children:f.label}),a(_P,{className:"sync-radix-select-indicator",children:a(SP,{})})]},Il(f.value)))})})})]})}function TP({descriptionId:e,request:t}){const[n,r]=I("choice"),[i,o]=I(t.actors.find(v=>v.isLocal)?.actorId||t.actors[0]?.actorId||""),[s,c]=I("");K(()=>{r("choice");const v=t.actors.find(w=>w.isLocal)?.actorId||t.actors[0]?.actorId||"",b=t.actors.find(w=>w.actorId!==v)?.actorId||"";o(v),c(b)},[t]);const l=t.actors.find(v=>v.actorId===i)||t.actors[0],d=t.actors.filter(v=>v.actorId!==i),u=d.find(v=>v.actorId===s)||d[0],p=t.actors.map(v=>({label:a(te,{children:[v.label,v.isLocal?" (You)":""]}),value:v.actorId})),m=d.map(v=>({label:`${v.label}${v.isLocal?" (You)":""}`,value:v.actorId})),f=!!(l?.actorId&&u?.actorId),g=()=>{!l?.actorId||!u?.actorId||Tn({action:"merge",primaryActorId:l.actorId,secondaryActorId:u.actorId})},h=v=>{const b=v.target instanceof HTMLElement?v.target:null;v.defaultPrevented||v.isComposing||v.key!=="Enter"||b?.closest(".sync-dialog-radio-list")&&f&&(v.preventDefault(),g())};return n==="choice"?a("div",{className:"sync-dialog-stack",children:a("ul",{className:"sync-dialog-choice-list",children:[a("li",{children:a("button",{autoFocus:!0,className:"settings-button","data-primary-action":"true","data-sync-primary-action":"true",onClick:()=>r("merge"),type:"button",children:"These are both me"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>Tn({action:"different-people"}),type:"button",children:"These are different people"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>Tn({action:"cancel"}),type:"button",children:"Decide later"})})]})}):a("div",{className:"sync-dialog-stack",onKeyDown:v=>{h(v),Dr(v,{onSubmit:g,disabled:!f})},children:[a("div",{className:"small",id:e,children:"Choose which person should remain after combining these duplicates."}),a(Fx,{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:g,type:"button",children:"Combine people"})]})]})}function NP({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"){Tn(!0);return}if(t.kind==="duplicate-person")return;const m=r.trim(),f=t.validate?.(m)||null;if(f){s(f);return}Tn(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(Mo,{ariaLabel:`Close ${t.title}`,onClick:()=>Tn(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(kx,{"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(Ce,{"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(TP,{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:()=>Tn(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?a("button",{autoFocus:!0,className:`settings-button ${Nx(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function kP(){const[e,t]=I(Sx());K(()=>(Zh(t),()=>{Cx(t)&&Zh(null)}),[]);const n=!!e,r=ke(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=ke(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?a(wi,{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||Tn(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?a(NP,{descriptionId:i,request:e,titleId:r}):null}):null}var nr=null;function Ba(){nr?.isConnected||(nr=document.getElementById("syncDialogMount"),nr||(nr=document.createElement("div"),nr.id="syncDialogMount",document.body.appendChild(nr)),Ue(a(kP,{}),nr))}function Kt(e){return Ba(),Cl("confirm")?new Promise(t=>{Sl(n=>t(!!n)),La({kind:"confirm",...e})}):Promise.resolve(!1)}function Rl(e){return Ba(),Cl("input")?new Promise(t=>{Sl(n=>t(typeof n=="string"?n:null)),La({kind:"input",...e})}):Promise.resolve(null)}function xP(e){return Ba(),Cl("duplicate-person")?new Promise(t=>{Sl(n=>t(n||{action:"cancel"})),La({kind:"duplicate-person",...e})}):Promise.resolve(Tx({kind:"duplicate-person",...e}))}function PP(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 EP(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function jg(e){const t=String(e.label||"").trim()||"Untitled Space",n=EP(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 AP(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 IP(e,t,n){return`Revoke ${t||n||"this device"} from ${jg(e).title}?`}function RP(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 DP(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 LP(){return{loaded:!1,loading:!1,error:"",includeInactive:!1,devicesLoaded:!1,scopes:[],membersByScope:new Map,devices:[],createScopeId:"",createLabel:"",createKind:"team",actionPendingKey:"",actionPendingKind:""}}function Dl(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=LP(),O.groupScopeManagementDrafts.set(e,t)),t}function bt(e,t){O.groupScopeManagementDrafts.set(e,t)}async function Hr(e,t,n=dt(e).includeInactive){bt(e,{...dt(e),loading:!0,error:"",includeInactive:n}),t();try{const[r,i]=await Promise.all([R_(e,n),Lu(e,!0)]),o=Dl(r),s=Dl(i),c=await Promise.all(o.map(async l=>{const d=String(l.scope_id||"").trim();return d?[d,Dl(await L_(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 Ll(e,t){O.groupScopeManagementOpen.add(e),dt(e),t(),Hr(e,t)}function Fg(e,t){O.groupScopeManagementOpen.delete(e),O.groupScopeManagementDrafts.delete(e),t()}async function $P(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 D_(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 Hr(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 MP(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,t,{device_id:n,role:"member"}),ne("Device granted access to the Space."),await Hr(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 OP(e,t,n,r,i){const o=String(t.scope_id||"").trim();if(!o||!await Kt({title:IP(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 M_(e,o,n),ne("Space access revoked. Future sync is blocked for that device."),await Hr(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 jP(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=RP(DP(n.devices,_.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",m=AP(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,m.detail),y("span",{class:"peer-meta"},m.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:()=>{MP(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:()=>{OP(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 FP(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=jg(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."),jP(e,t,n,r,i))}function BP(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,o=O.groupScopeManagementDrafts.get(t);if(!o)return null;const s=PP(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(te,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(Br,{"aria-labelledby":`coord-admin-domain-inactive-${t}`,checked:o.includeInactive,className:"coordinator-admin-switch",disabled:c,onCheckedChange:l=>{Hr(t,i,l)},thumbClassName:"coordinator-admin-switch-thumb"})),y("form",{class:"coordinator-admin-form",onSubmit:l=>{l.preventDefault(),!c&&$P(t,i)}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New Space id"),y(Ce,{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})),y("label",{class:"coordinator-admin-field"},y("span",null,"Label"),y(Ce,{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})),y("label",{class:"coordinator-admin-field"},y("span",null,"Kind"),y(Ce,{class:"peer-scope-input",disabled:c,onInput:l=>{bt(t,{...dt(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:()=>{Hr(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=>FP(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 Bg(){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 UP(){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 $l(e,t){const n=UP();O.groupPreferencesDrafts.set(e,n),O.groupPreferencesOpen.add(e),t();try{const r=await ww(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 Ua(e,t){O.groupPreferencesOpen.delete(e),O.groupPreferencesDrafts.delete(e),t()}async function GP(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 Sw(e,r),ne("Team defaults saved. New devices use these filters and Space settings."),Ua(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 HP(e,t,n){const r=O.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(te,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(Br,{"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"})),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:o},"Auto-grant default Space on join"),y(Br,{"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?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(qh,{"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}),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(qh,{"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?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:()=>{GP(e,t)},type:"button"},r.saving?"Saving…":"Save defaults"),y("button",{class:"settings-button",disabled:r.saving,onClick:()=>Ua(e,t),type:"button"},"Cancel")))}function KP(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 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:()=>{O.groupPreferencesOpen.add(t.groupId),$l(t.groupId,e)},type:"button"},"Review Team defaults"),y("button",{class:"settings-button",onClick:()=>{Ll(t.groupId,e)},type:"button"},"Check Spaces"),y("button",{class:"settings-button",onClick:()=>{O.inviteGroup=t.groupId,O.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:()=>{O.teamSetupGuide=null,e()},type:"button"},"Dismiss")))}function qP(e,t){return t?e?"Restoring…":"Archiving…":e?"Unarchive":"Archive"}function WP(e){const{summary:t,createGroup:n,runGroup:r,renderShell:i,reloadData:o}=e,s=String(_.lastCoordinatorAdminStatus?.active_group||"").trim(),c=Zn(),l=Ur(),d=l.filter(g=>!g.archived_at),u=l.filter(g=>g.archived_at),p=O.showArchivedGroups?l:d,m=c?l.some(g=>g.group_id===c):!1,f=[`${d.length} active`];return u.length&&f.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"},f.join(" · ")):null,!m&&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,KP(i),(()=>{const g=t.readiness!=="ready"||O.groupActionPendingKind==="create";return y("form",{class:"coordinator-admin-form",onSubmit:h=>{h.preventDefault(),!g&&n()}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New Team id"),y(Ce,{class:"peer-scope-input",disabled:g,onInput:h=>{O.createGroupId=String(h.currentTarget.value||"")},placeholder:"team-alpha",type:"text",value:O.createGroupId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Ce,{class:"peer-scope-input",disabled:g,onInput:h=>{O.createGroupDisplayName=String(h.currentTarget.value||"")},placeholder:"Team Alpha",type:"text",value:O.createGroupDisplayName}))),y("div",{class:"section-actions coordinator-admin-groups-toolbar"},y("div",{class:"coordinator-admin-primary-actions"},y("button",{class:"settings-button",disabled:g,type:"submit"},O.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(Br,{"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?y("div",{class:"peer-list"},p.map(g=>{const h=g.group_id===c,v=O.groupActionPendingId===g.group_id,b=!!g.archived_at,w=O.groupRenameDrafts.get(g.group_id)??g.display_name??g.group_id,S=O.groupPreferencesOpen.has(g.group_id),T=O.groupScopeManagementOpen.has(g.group_id),N=b?"unarchive":"archive",P=qP(b,v&&O.groupActionPendingKind===N),A=wx({groupId:g.group_id,preferences:O.groupPreferencesDrafts.get(g.group_id),scopeManagement:O.groupScopeManagementDrafts.get(g.group_id),setupGuide:O.teamSetupGuide});return y("div",{class:"peer-card peer-card--padded",key:g.group_id},y("div",{class:"peer-title"},y("strong",null,w)),y("div",{class:"peer-submeta"},b?"Archived Team":"Active Team"),y("div",{class:"peer-meta"},`Advanced: Team ID ${g.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,A.defaultSpace)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Auto-grant"),y("strong",null,A.autoGrant)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Spaces"),y("strong",null,A.spaces))),s===g.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(Ce,{class:"peer-scope-input",disabled:t.readiness!=="ready"||v,onInput:M=>{O.groupRenameDrafts.set(g.group_id,String(M.currentTarget.value||""))},type:"text",value:w})),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:t.readiness!=="ready"||h,onClick:()=>{bl(g.group_id),o()},type:"button"},h?"Managing":"Manage Team"),y("button",{class:"settings-button",disabled:t.readiness!=="ready"||v,onClick:()=>r(g.group_id,w,"rename"),type:"button"},v&&O.groupActionPendingKind==="rename"?"Renaming…":"Rename"),y("button",{"aria-expanded":S,"aria-controls":`coord-admin-project-defaults-drawer-${g.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":S?"open":"closed",disabled:t.readiness!=="ready"||v,onClick:()=>{S?Ua(g.group_id,i):$l(g.group_id,i)},type:"button"},y("span",null,"Team defaults"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(Bg,null))),y("button",{"aria-expanded":T,"aria-controls":`coord-admin-spaces-drawer-${g.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":T?"open":"closed",disabled:t.readiness!=="ready"||v,onClick:()=>{T?Fg(g.group_id,i):Ll(g.group_id,i)},type:"button"},y("span",null,"Spaces & access"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(Bg,null))),y("button",{class:b?"settings-button":"settings-button danger",disabled:t.readiness!=="ready"||v,onClick:()=>r(g.group_id,g.display_name||g.group_id,N),type:"button"},P)),y(va,{open:S,onOpenChange:M=>{M?$l(g.group_id,i):Ua(g.group_id,i)}},y(ya,{"aria-label":`Project defaults for ${w}`,class:"coordinator-admin-group-preferences",id:`coord-admin-project-defaults-drawer-${g.group_id}`},S?HP(g.group_id,i,t.readiness==="ready"):null)),y(va,{open:T,onOpenChange:M=>{M?Ll(g.group_id,i):Fg(g.group_id,i)}},y(ya,{"aria-label":`Spaces for ${w}`,class:"coordinator-admin-group-preferences coordinator-admin-domain-management",id:`coord-admin-spaces-drawer-${g.group_id}`},T?BP({groupId:g.group_id,ready:t.readiness==="ready",renderShell:i,summary:t}):null)))})):y("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 Kr(e){return a("textarea",{...e})}function VP(e){const{summary:t,createInvite:n,renderShell:r}=e,i=_.lastCoordinatorAdminStatus,o=Zn()||String(i?.active_group||"").trim(),s=O.inviteGroup.trim()||o,c=String(_.lastTeamInvite?.encoded||"").trim(),l=Array.isArray(_.lastTeamInvite?.warnings)?_.lastTeamInvite?.warnings:[],d=t.readiness!=="ready"||O.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(Ce,{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})),y("label",{class:"coordinator-admin-field"},y("span",null,"Join policy"),y(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"})),y("label",{class:"coordinator-admin-field"},y("span",null,"Expires in (hours)"),y(Ce,{class:"peer-scope-input",disabled:t.readiness!=="ready",min:"1",onInput:u=>{O.inviteTtlHours=String(u.currentTarget.value||"")},type:"number",value:O.inviteTtlHours}))),y("div",{class:"section-actions"},y("button",{class:"settings-button",disabled:d,type:"submit"},O.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(Kr,{class:"feed-search coordinator-admin-output",readOnly:!0,value:c}),y("button",{class:"settings-button sync-action-copy",type:"button",onClick:u=>Ai(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."),_.lastShareOperations.length>0?y("ul",{class:"peer-scope-rejections-list","aria-label":"Project sharing operations"},..._.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 zP(e){const{summary:t,reviewJoinRequest:n}=e,r=Array.isArray(_.lastCoordinatorAdminJoinRequests)?_.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=O.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&&O.joinReviewPendingAction==="approve"?"Approving…":"Approve"),y("button",{class:"settings-button danger",disabled:!o||u,onClick:()=>n(o,"deny"),type:"button"},u&&O.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 JP(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 P_({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,g=String(m?.scope_id||"");O.createGroupId="",O.createGroupDisplayName="",O.teamSetupGuide={groupId:l,displayName:String(u.group?.display_name||d||l),defaultSpaceScopeId:g,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(),bl(l),await n(),u.setup_warning?ne("Team created, but default Space setup needs repair.","warning"):g?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 E_(l,d),ne("Team renamed.","success")),u==="archive"&&(await A_(l),ne("Team archived.","success")),u==="unarchive"&&(await I_(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=_.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 $u({group_id:u,policy:O.invitePolicy,ttl_hours:p});_.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 j_(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 F_(l,d,m),ne("Device renamed.","success")}p==="disable"&&(await B_(l,d),ne("Device disabled.","success")),p==="enable"&&(await U_(l,d),ne("Device enabled.","success")),p==="remove"&&(await G_(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 YP(){const e=_.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:XP,runGroupAction:QP,createInviteFromAdminPanel:ZP,reviewJoinRequestFromAdminPanel:eE,runDeviceAction:tE}=JP({renderShell:()=>rr(),reloadData:()=>Ml()});function rr(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=_.lastCoordinatorAdminStatus,n=YP(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!fx()?.archived_at,c=n.readiness==="ready",l=n.readiness==="ready"&&!s,d=n.readiness==="ready",u=n.readiness==="ready",p=Zn(),m=Ur().filter(b=>!b.archived_at).length,f=Ur().filter(b=>b.archived_at).length,g=Array.isArray(_.lastCoordinatorAdminJoinRequests)?_.lastCoordinatorAdminJoinRequests.length:0,h=Array.isArray(_.lastCoordinatorAdminDevices)?_.lastCoordinatorAdminDevices.length:0,v=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"),Ue(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,`${m} active${f?` · ${f} archived`:""}`)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Selected Team activity"),y("strong",null,`${g} join requests · ${h} devices`))),v?y("div",{class:"peer-meta coordinator-admin-inline-warning"},v):null,r?y("div",{class:"section-meta coordinator-admin-inline-meta"},`Coordinator: ${r}`):null),y("div",{class:"card coordinator-admin-sections"},y(Vf,{ariaLabel:"Teams sections",listClassName:"coordinator-admin-tabs-list",onValueChange:b=>{O.activeSection=b||"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:O.activeSection},WP({summary:n,createGroup:()=>{XP()},runGroup:(b,w,S)=>{QP(b,w,S)},renderShell:rr,reloadData:()=>{Ml()}}),VP({summary:n,createInvite:()=>{ZP()},renderShell:rr}),zP({summary:n,reviewJoinRequest:(b,w)=>{eE(b,w)}}),LN({summary:n,runDevice:(b,w,S,T)=>{tE(b,w,S,T)}})),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 nE(){rr()}async function Ml(){try{_.lastCoordinatorAdminStatus=await No()}catch{_.lastCoordinatorAdminStatus=null,_.lastCoordinatorAdminJoinRequests=[],_.lastCoordinatorAdminDevices=[],O.deviceRenameDrafts.clear(),O.deviceRenameServerNames.clear(),rr();return}const e=String(_.lastCoordinatorAdminStatus?.active_group||"").trim();if(Qh(),_.lastCoordinatorAdminStatus?.readiness==="ready"){try{const n=await Vu();_.lastShareOperations=Array.isArray(n.items)?n.items:[]}catch{}try{const n=await Du(O.showArchivedGroups);_.lastCoordinatorAdminGroups=Array.isArray(n?.items)?n.items:[],mx(),Qh()}catch{_.lastCoordinatorAdminGroups=[],O.groupRenameDrafts.clear()}const t=Zn();try{const n=await O_(t||e);_.lastCoordinatorAdminJoinRequests=Array.isArray(n?.items)?n.items:[]}catch{_.lastCoordinatorAdminJoinRequests=[]}try{const n=await Lu(t||e,!0);_.lastCoordinatorAdminDevices=Array.isArray(n?.items)?n.items:[],hx()}catch{_.lastCoordinatorAdminDevices=[]}try{O.availableProjects=await ko()}catch{O.availableProjects=[]}}else _.lastCoordinatorAdminGroups=[],O.groupRenameDrafts.clear(),_.lastCoordinatorAdminJoinRequests=[],_.lastCoordinatorAdminDevices=[],O.deviceRenameDrafts.clear(),O.deviceRenameServerNames.clear();rr()}var Ol=new WeakMap,Ug={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},rE={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},iE={available:"Available",offline:"Offline",unknown:"Availability unknown"};function jl(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function oE(e,t){return t.get(e)??rE}function aE(e){return e.reduce((t,n)=>!t||Ug[n.state]>Ug[t.state]?n:t,null)}function sE(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 cE(e,t,n,r){const i=new Map(e.identities.filter(d=>d.status==="active"&&d.mergedIntoIdentityId===null).map(d=>[d.identityId,d.displayName])),o=new Map(e.teams.filter(d=>d.status==="active").map(d=>[d.teamId,d.displayName])),s=new Map(n.map(d=>[d.canonicalProjectIdentity,d.displayName])),c=new Map(r.map(d=>[d.deviceId,d.state])),l=new Map(t.items.map(d=>[d.canonicalProjectIdentity,d]));return{devices:e.identityDevices.filter(d=>d.status==="active"&&i.has(d.identityId)).map(d=>{const u=new Set(e.teamMemberships.filter(S=>S.status==="active"&&S.identityId===d.identityId&&o.has(S.teamId)).map(S=>S.teamId)),p=jl(e.projectRecipients.filter(S=>S.status==="active"&&S.recipientKind==="identity"&&S.identityId===d.identityId).map(S=>S.canonicalProjectIdentity)),m=new Map;for(const S of e.projectRecipients){if(S.status!=="active"||S.recipientKind!=="team"||!u.has(S.teamId))continue;const T=m.get(S.canonicalProjectIdentity)??new Set;T.add(S.teamId),m.set(S.canonicalProjectIdentity,T)}const f=(S,T=[])=>{const N=s.get(S);if(!N)return null;const P=oE(S,l);return{displayName:N,teamNames:jl([...T].flatMap(A=>{const M=o.get(A);return M?[M]:[]})),state:P.state,statusLabel:P.label,statusCopy:P.explanation,deliveredCopiesMayRemain:P.deliveredCopiesMayRemain}},g=p.flatMap(S=>{const T=f(S);return T?[T]:[]}),h=jl(m.keys()).flatMap(S=>{const T=f(S,m.get(S));return T?[T]:[]}),v=[...g,...h],b=aE(v),w=c.get(d.deviceId)??"unknown";return{deviceId:d.deviceId,displayName:d.displayName,identityName:i.get(d.identityId)??"Identity unavailable",availability:w,availabilityLabel:iE[w],directProjects:g,inheritedProjects:h,unavailableProjectCount:p.length+m.size-v.length,statusState:b?.state??"no_projects",statusLabel:b?.statusLabel??"No shared Projects",statusCopy:b?.statusCopy??"This device has no current Project access.",deliveredCopiesMayRemain:v.some(S=>S.deliveredCopiesMayRemain),action:sE(w,b?.state??"no_projects")}}).sort((d,u)=>d.displayName.localeCompare(u.displayName)||d.identityName.localeCompare(u.identityName)),revokedDeviceCount:e.identityDevices.filter(d=>d.status==="revoked"&&i.has(d.identityId)).length}}function Gg({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}),n.teamNames.length?` through ${n.teamNames.join(", ")}`:"",a("span",{className:"small",children:[" ","— ",n.statusLabel,". ",n.statusCopy]})]},`${n.displayName}:${n.teamNames.join(":")}`))})}function lE({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})]}),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(Gg,{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(Gg,{empty:"No Projects are inherited through Teams.",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&&Ol.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 Ga(e,t,n,r,i,o={}){const s=document.activeElement,c=s instanceof HTMLElement&&e.contains(s)?Ol.get(s):void 0,l=cE(t,n,r,i);Ue(a("section",{"aria-labelledby":"devices-heading",className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[a("div",{className:"recipient-policy-sharing-header",children:[a("h2",{id:"devices-heading",children:"Devices"}),a("p",{className:"small",children:"See where Codemem runs and which Projects each active device receives."})]}),a(lE,{options:o,projection:l})]}),e),c&&([...e.querySelectorAll("button")].find(d=>{const u=Ol.get(d);return u?.deviceId===c.deviceId&&u.target===c.target})??document.getElementById("tabBtn-devices"))?.focus()}function dE(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 uE(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 qr(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 xn(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 Hg(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function pE(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 Fl(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 Ui(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 mE(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 Ha(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 Kg(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function fE(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function hE(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 qg(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function gE(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function vE(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 Ka(e){if(!e||typeof e!="object")return{};const t=e,n=t.import_metadata;return n&&typeof n=="object"?{...n,...t}:t}function yE(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 bE(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 Wg(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 Vg(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()}:${Vg(e)}`}function _E(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function wE(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function SE(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===_.lastStatsPayload?.identity?.actor_id?"You":n||t||"Unknown author"}function zg(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 CE(e,t){const n=new Set(t.map(ft));return zg(e.filter(r=>!n.has(ft(r))),t)}var WO=560;function TE(){const e=document.documentElement,t=Math.max(e.scrollHeight,document.body.scrollHeight);return window.innerHeight+window.scrollY>=t-560}function qa(e,t,n){const r=e.pagination?.has_more;return typeof r=="boolean"?r:t>=n}function Wa(e,t){const n=e.pagination?.next_offset;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:t}function NE(e,t){const n=new Set(t.map(ft));return e.filter(r=>!n.has(ft(r))).length}var[Va,VO]=st("Tooltip",[Sn]),za=Sn(),Jg="TooltipProvider",kE=700,Bl="tooltip.open",[xE,Ul]=Va(Jg),Yg=e=>{const{__scopeTooltip:t,delayDuration:n=kE,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:o}=e,s=B(!0),c=B(!1),l=B(0);return K(()=>{const d=l.current;return()=>window.clearTimeout(d)},[]),a(xE,{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})};Yg.displayName=Jg;var Gi="Tooltip",[PE,Hi]=Va(Gi),Xg=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:o,disableHoverableContent:s,delayDuration:c}=e,l=Ul(Gi,e.__scopeTooltip),d=za(t),[u,p]=I(null),m=ct(),f=B(0),g=s??l.disableHoverableContent,h=c??l.delayDuration,v=B(!1),[b,w]=wt({prop:r,defaultProp:i??!1,onChange:A=>{A?(l.onOpen(),document.dispatchEvent(new CustomEvent(Bl))):l.onClose(),o?.(A)},caller:Gi}),S=ke(()=>b?v.current?"delayed-open":"instant-open":"closed",[b]),T=re(()=>{window.clearTimeout(f.current),f.current=0,v.current=!1,w(!0)},[w]),N=re(()=>{window.clearTimeout(f.current),f.current=0,w(!1)},[w]),P=re(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{v.current=!0,w(!0),f.current=0},h)},[h,w]);return K(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),a(Oi,{...d,children:a(PE,{scope:t,contentId:m,open:b,stateAttribute:S,trigger:u,onTriggerChange:p,onTriggerEnter:re(()=>{l.isOpenDelayedRef.current?P():T()},[l.isOpenDelayedRef,P,T]),onTriggerLeave:re(()=>{g?N():(window.clearTimeout(f.current),f.current=0)},[N,g]),onOpen:T,onClose:N,disableHoverableContent:g,children:n})})};Xg.displayName=Gi;var Gl="TooltipTrigger",Qg=F((e,t)=>{const{__scopeTooltip:n,...r}=e,i=Hi(Gl,n),o=Ul(Gl,n),s=za(n),c=we(t,B(null),i.onTriggerChange),l=B(!1),d=B(!1),u=re(()=>l.current=!1,[]);return K(()=>()=>document.removeEventListener("pointerup",u),[u]),a(ji,{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)})})});Qg.displayName=Gl;var Hl="TooltipPortal",[EE,AE]=Va(Hl,{forceMount:void 0}),Zg=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,o=Hi(Hl,t);return a(EE,{scope:t,forceMount:n,children:a(nt,{present:n||o.open,children:a(qn,{asChild:!0,container:i,children:r})})})};Zg.displayName=Hl;var Wr="TooltipContent",ev=F((e,t)=>{const n=AE(Wr,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...o}=e,s=Hi(Wr,e.__scopeTooltip);return a(nt,{present:r||s.open,children:s.disableHoverableContent?a(tv,{side:i,...o,ref:t}):a(IE,{side:i,...o,ref:t})})}),IE=F((e,t)=>{const n=Hi(Wr,e.__scopeTooltip),r=Ul(Wr,e.__scopeTooltip),i=B(null),o=we(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((g,h)=>{const v=g.currentTarget,b={x:g.clientX,y:g.clientY},w=ME(b,$E(b,v.getBoundingClientRect())),S=OE(h.getBoundingClientRect());c(FE([...w,...S])),p(!0)},[p]);return K(()=>()=>m(),[m]),K(()=>{if(l&&u){const g=v=>f(v,u),h=v=>f(v,l);return l.addEventListener("pointerleave",g),u.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",g),u.removeEventListener("pointerleave",h)}}},[l,u,f,m]),K(()=>{if(s){const g=h=>{const v=h.target,b={x:h.clientX,y:h.clientY},w=l?.contains(v)||u?.contains(v),S=!jE(b,s);w?m():S&&(m(),d())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,u,s,d,m]),a(tv,{...e,ref:o})}),[RE,DE]=Va(Gi,{isInside:!1}),LE=rS("TooltipContent"),tv=F((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:s,...c}=e,l=Hi(Wr,n),d=za(n),{onClose:u}=l;return K(()=>(document.addEventListener(Bl,u),()=>document.removeEventListener(Bl,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(Kn,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:u,children:a(Ea,{"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(LE,{children:r}),a(RE,{scope:n,isInside:!0,children:a(bT,{id:l.contentId,role:"tooltip",children:i||r})})]})})});ev.displayName=Wr;var nv="TooltipArrow",rv=F((e,t)=>{const{__scopeTooltip:n,...r}=e,i=za(n);return DE(nv,n).isInside?null:a(Aa,{...i,...r,ref:t})});rv.displayName=nv;function $E(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 ME(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 OE(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 jE(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 FE(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),BE(t)}function BE(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 UE=Yg,GE=Xg,HE=Qg,KE=Zg,qE=ev,WE=rv;function Kl({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return a(UE,{delayDuration:t,skipDelayDuration:n,children:e})}function Ja({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(GE,{children:[a(HE,{asChild:o,children:e}),a(KE,{children:a(qE,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,a(WE,{className:"tooltip-arrow"})]})})]})}function VE(e){e.dataset.feedRenderRoot="preact"}function zE(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function JE(e,t){VE(e),Ue(y(Kl,null,t),e)}function YE(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function XE(e){return e.split(/\n|,/).map(t=>t.trim()).filter(Boolean)}function ql(e){return JSON.stringify([e.project,e.query.trim(),e.workingSetFiles])}function QE(e){const t=Ka(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=Ha(e?.facts||t?.facts||[]),l=c.length?c:yE(r||n),d=l.length?l:bE(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function ZE(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 eA(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function tA(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function nA(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function rA(e,t){const n=_.feedTypeFilter==="observations"?" · observations":_.feedTypeFilter==="summaries"?" · session summaries":"",r=_E(_.feedScopeFilter),i=!_.feedQuery.trim()&&_.lastFeedFilteredCount?` · ${_.lastFeedFilteredCount} observations filtered`:"";return`${e} items${n}${r}${_.feedQuery.trim()?` · matching "${_.feedQuery.trim()}"`:""}${i}${t?" · scroll for more":""}`}function Ya({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 iA({open:e}){const[t,n]=I(()=>String(_.feedQuery||"")),[r,i]=I(!1),[o,s]=I(!1),[c,l]=I(""),[d,u]=I(!1),[p,m]=I(""),[f,g]=I(""),[h,v]=I(null),b=B(0),w=String(_.feedQuery||""),S=String(t||"").trim(),T=_.currentProject||null,N=XE(c),P=ql({project:T,query:S,workingSetFiles:N}),A=h&&ql({project:h.inputs.project,query:h.inputs.query,workingSetFiles:h.inputs.working_set_files})===P?h:null,M=p&&f===P?p:"";K(()=>{b.current+=1,u(!1),m(""),g(""),v(L=>!L||L.inputs.query!==S||L.inputs.project!==T?null:L)},[P]),K(()=>{e&&!r&&(n(YE({feedQuery:w,hasInspectorOverride:o,inspectorQuery:t})),i(!0))},[w,o,r,t,e]);const U=async()=>{const L=S,J=T,H=N,k=ql({project:J,query:L,workingSetFiles:H}),R=b.current+1;if(b.current=R,!L){m("Enter a query to inspect."),g(k),v(null);return}u(!0),m(""),g("");try{const j=await W_({context:L,project:J,working_set_files:H});if(R!==b.current)return;v(j)}catch(j){if(R!==b.current)return;m(j instanceof Error?j.message:String(j)),g(k),v(null)}finally{R===b.current&&u(!1)}},x=A?.retrieval.candidates.filter(L=>L.disposition==="selected")||[],G=A?.retrieval.candidates.filter(L=>L.disposition==="dropped")||[],E=A?.retrieval.candidates.filter(L=>L.disposition==="deduped")||[],$=A?.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),v(null),m(""),g("")},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:()=>{U()},type:"button"},d?"Tracing…":"Run trace"),A?y("span",{className:"section-meta"},`mode=${A.mode.selected} · candidates=${A.retrieval.candidate_count} · tokens=${A.output.estimated_tokens}`):null),h&&!A?y("div",{className:"section-meta",style:"margin-top:8px;"},"Trace inputs changed. Run trace again for the current query, project, and working set."):null,M?y("div",{className:"section-meta",style:"margin-top:8px; color:#d96c6c;"},M):null]),A?y(te,null,[y(Ya,{label:"Selected",candidates:x}),y(Ya,{label:"Dropped",candidates:G}),y(Ya,{label:"Deduped",candidates:E}),y(Ya,{label:"Trimmed",candidates:$}),y("div",{className:"feed-card-body"},[A.assembly.collapsed_groups.length?y("div",{className:"section-meta"},`Collapsed duplicates: ${A.assembly.collapsed_groups.map(L=>`kept #${L.kept} from [${L.dropped.join(", ")}]`).join(" · ")}`):null,A.assembly.trim_reasons.length?y("div",{className:"section-meta"},`Trim reasons: ${A.assembly.trim_reasons.join(", ")}`):null,y("div",{className:"section-meta"},"Final pack"),y("pre",{style:"white-space:pre-wrap; overflow:auto;"},A.output.pack_text)])]):null])):null}var oA={kind:"kind-chip",provenance:"provenance-chip",tag:"tag-chip",badge:"badge",scope:"peer-scope-chip"};function Wl({variant:e,tone:t,title:n,children:r}){const i=oA[e];return a("span",{className:t?`${i} ${t}`:i,title:n,children:r})}function iv(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 aA(e){if(Array.isArray(e))return e}function sA(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 cA(){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 lA(e,t){return aA(e)||sA(e,t)||dA(e,t)||cA()}function dA(e,t){if(e){if(typeof e=="string")return iv(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)?iv(e,t):void 0}}var ov=Object.entries,av=Object.setPrototypeOf,uA=Object.isFrozen,pA=Object.getPrototypeOf,mA=Object.getOwnPropertyDescriptor,Je=Object.freeze,Ye=Object.seal,Vr=Object.create,sv=typeof Reflect<"u"&&Reflect,Vl=sv.apply,zl=sv.construct;Je||(Je=function(t){return t}),Ye||(Ye=function(t){return t}),Vl||(Vl=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)}),zl||(zl=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 Ki=He(Array.prototype.forEach),fA=He(Array.prototype.lastIndexOf),cv=He(Array.prototype.pop),zr=He(Array.prototype.push),hA=He(Array.prototype.splice),Pn=Array.isArray,qi=He(String.prototype.toLowerCase),Jl=He(String.prototype.toString),lv=He(String.prototype.match),Wi=He(String.prototype.replace),dv=He(String.prototype.indexOf),gA=He(String.prototype.trim),vA=He(Number.prototype.toString),yA=He(Boolean.prototype.toString),uv=typeof BigInt>"u"?null:He(BigInt.prototype.toString),pv=typeof Symbol>"u"?null:He(Symbol.prototype.toString),Ve=He(Object.prototype.hasOwnProperty),Vi=He(Object.prototype.toString),Xe=He(RegExp.prototype.test),or=bA(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 Vl(e,t,r)}}function bA(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return zl(e,n)}}function Te(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:qi;if(av&&av(e,null),!Pn(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i=="string"){const o=n(i);o!==i&&(uA(t)||(t[r]=o),i=o)}e[i]=!0}return e}function _A(e){for(let t=0;t<e.length;t++)Ve(e,t)||(e[t]=null);return e}function ut(e){const t=Vr(null);for(const r of ov(e)){var n=lA(r,2);const i=n[0],o=n[1];Ve(e,i)&&(Pn(o)?t[i]=_A(o):o&&typeof o=="object"&&o.constructor===Object?t[i]=ut(o):t[i]=o)}return t}function wA(e){switch(typeof e){case"string":return e;case"number":return vA(e);case"boolean":return yA(e);case"bigint":return uv?uv(e):"0";case"symbol":return pv?pv(e):"Symbol()";case"undefined":return Vi(e);case"function":case"object":{if(e===null)return Vi(e);const t=e,n=qt(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 qt(e,t){for(;e!==null;){const r=mA(e,t);if(r){if(r.get)return He(r.get);if(typeof r.value=="function")return He(r.value)}e=pA(e)}function n(){return null}return n}function SA(e){try{return Xe(e,""),!0}catch{return!1}}var mv=Je(["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"]),Yl=Je(["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"]),Xl=Je(["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"]),CA=Je(["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"]),Ql=Je(["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"]),TA=Je(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),fv=Je(["#text"]),hv=Je(["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"]),Zl=Je(["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"]),gv=Je(["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"]),Xa=Je(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),NA=Ye(/{{[\w\W]*|^[\w\W]*}}/g),kA=Ye(/<%[\w\W]*|^[\w\W]*%>/g),xA=Ye(/\${[\w\W]*/g),PA=Ye(/^data-[\-\w.\u00B7-\uFFFF]+$/),EA=Ye(/^aria-[\-\w]+$/),vv=Ye(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),AA=Ye(/^(?:\w+script|data):/i),IA=Ye(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),RA=Ye(/^html$/i),DA=Ye(/^[a-z][.\w]*(-[.\w]+)+$/i),yv=Ye(/<[/\w!]/g),LA=Ye(/<[/\w]/g),$A=Ye(/<\/no(script|embed|frames)/i),MA=Ye(/\/>/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},OA=function(){return typeof window>"u"?null:window},jA=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}},bv=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},En=function(t,n,r,i){return Ve(t,n)&&Pn(t[n])?Te(i.base?ut(i.base):{},t[n],i.transform):r};function _v(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:OA();const t=ee=>_v(ee);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=qt(p,"cloneNode"),f=qt(p,"remove"),g=qt(p,"nextSibling"),h=qt(p,"childNodes"),v=qt(p,"parentNode"),b=qt(p,"shadowRoot"),w=qt(p,"attributes"),S=s&&s.prototype?qt(s.prototype,"nodeType"):null,T=s&&s.prototype?qt(s.prototype,"nodeName"):null;if(typeof o=="function"){const ee=n.createElement("template");ee.content&&ee.content.ownerDocument&&(n=ee.content.ownerDocument)}let N,P="",A,M=!1,U=0;const x=function(){if(U>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){x(),U++;try{return N.createHTML(C)}finally{U--}},E=function(C){x(),U++;try{return N.createScriptURL(C)}finally{U--}},$=function(){return M||(A=jA(u,i),M=!0),A},L=n,J=L.implementation,H=L.createNodeIterator,k=L.createDocumentFragment,R=L.getElementsByTagName,j=r.importNode;let W=bv();t.isSupported=typeof ov=="function"&&typeof v=="function"&&J&&J.createHTMLDocument!==void 0;const ge=NA,le=kA,ce=xA,be=PA,Y=EA,fe=AA,X=IA,_e=DA;let he=vv,Q=null;const $e=Te({},[...mv,...Yl,...Xl,...Ql,...fv]);let ue=null;const q=Te({},[...hv,...Zl,...gv,...Xa]);let oe=Object.seal(Vr(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}})),qe=null,Me=null;const et=Object.seal(Vr(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let pn=!0,Lt=!0,Nt=!1,$t=!0,tt=!1,Mt=!0,pe=!1,ae=!1,Ge=null,On=null,So=!1,mn=!1,br=!1,jn=!1,ht=!0,Fn=!1;const c_="user-content-";let vu=!0,yu=!1,si={},Yt=null;const bu=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 l_=null;const d_=Te({},["audio","video","img","source","image","track"]);let _u=null;const u_=Te({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ls="http://www.w3.org/1998/Math/MathML",$s="http://www.w3.org/2000/svg",Xt="http://www.w3.org/1999/xhtml";let ci=Xt,wu=!1,Su=null;const gO=Te({},[Ls,$s,Xt],Jl),p_=Je(["mi","mo","mn","ms","mtext"]);let Cu=Te({},p_);const m_=Je(["annotation-xml"]);let Tu=Te({},m_);const vO=Te({},["title","style","font","a","script"]);let Co=null;const yO=["application/xhtml+xml","text/html"],bO="text/html";let Be=null,li=null;const _O=n.createElement("form"),f_=function(C){return C instanceof RegExp||C instanceof Function},Nu=function(){let C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(li&&li===C)return;(!C||typeof C!="object")&&(C={}),C=ut(C),Co=yO.indexOf(C.PARSER_MEDIA_TYPE)===-1?bO:C.PARSER_MEDIA_TYPE,Be=Co==="application/xhtml+xml"?Jl:qi,Q=En(C,"ALLOWED_TAGS",$e,{transform:Be}),ue=En(C,"ALLOWED_ATTR",q,{transform:Be}),Su=En(C,"ALLOWED_NAMESPACES",gO,{transform:Jl}),_u=En(C,"ADD_URI_SAFE_ATTR",u_,{transform:Be,base:u_}),l_=En(C,"ADD_DATA_URI_TAGS",d_,{transform:Be,base:d_}),Yt=En(C,"FORBID_CONTENTS",bu,{transform:Be}),qe=En(C,"FORBID_TAGS",ut({}),{transform:Be}),Me=En(C,"FORBID_ATTR",ut({}),{transform:Be}),si=Ve(C,"USE_PROFILES")?C.USE_PROFILES&&typeof C.USE_PROFILES=="object"?ut(C.USE_PROFILES):C.USE_PROFILES:!1,pn=C.ALLOW_ARIA_ATTR!==!1,Lt=C.ALLOW_DATA_ATTR!==!1,Nt=C.ALLOW_UNKNOWN_PROTOCOLS||!1,$t=C.ALLOW_SELF_CLOSE_IN_ATTR!==!1,tt=C.SAFE_FOR_TEMPLATES||!1,Mt=C.SAFE_FOR_XML!==!1,pe=C.WHOLE_DOCUMENT||!1,mn=C.RETURN_DOM||!1,br=C.RETURN_DOM_FRAGMENT||!1,jn=C.RETURN_TRUSTED_TYPE||!1,So=C.FORCE_BODY||!1,ht=C.SANITIZE_DOM!==!1,Fn=C.SANITIZE_NAMED_PROPS||!1,vu=C.KEEP_CONTENT!==!1,yu=C.IN_PLACE||!1,he=SA(C.ALLOWED_URI_REGEXP)?C.ALLOWED_URI_REGEXP:vv,ci=typeof C.NAMESPACE=="string"?C.NAMESPACE:Xt,Cu=Ve(C,"MATHML_TEXT_INTEGRATION_POINTS")&&C.MATHML_TEXT_INTEGRATION_POINTS&&typeof C.MATHML_TEXT_INTEGRATION_POINTS=="object"?ut(C.MATHML_TEXT_INTEGRATION_POINTS):Te({},p_),Tu=Ve(C,"HTML_INTEGRATION_POINTS")&&C.HTML_INTEGRATION_POINTS&&typeof C.HTML_INTEGRATION_POINTS=="object"?ut(C.HTML_INTEGRATION_POINTS):Te({},m_);const D=Ve(C,"CUSTOM_ELEMENT_HANDLING")&&C.CUSTOM_ELEMENT_HANDLING&&typeof C.CUSTOM_ELEMENT_HANDLING=="object"?ut(C.CUSTOM_ELEMENT_HANDLING):Vr(null);if(oe=Vr(null),Ve(D,"tagNameCheck")&&f_(D.tagNameCheck)&&(oe.tagNameCheck=D.tagNameCheck),Ve(D,"attributeNameCheck")&&f_(D.attributeNameCheck)&&(oe.attributeNameCheck=D.attributeNameCheck),Ve(D,"allowCustomizedBuiltInElements")&&typeof D.allowCustomizedBuiltInElements=="boolean"&&(oe.allowCustomizedBuiltInElements=D.allowCustomizedBuiltInElements),Ye(oe),tt&&(Lt=!1),br&&(mn=!0),si&&(Q=Te({},fv),ue=Vr(null),si.html===!0&&(Te(Q,mv),Te(ue,hv)),si.svg===!0&&(Te(Q,Yl),Te(ue,Zl),Te(ue,Xa)),si.svgFilters===!0&&(Te(Q,Xl),Te(ue,Zl),Te(ue,Xa)),si.mathMl===!0&&(Te(Q,Ql),Te(ue,gv),Te(ue,Xa))),et.tagCheck=null,et.attributeCheck=null,Ve(C,"ADD_TAGS")&&(typeof C.ADD_TAGS=="function"?et.tagCheck=C.ADD_TAGS:Pn(C.ADD_TAGS)&&(Q===$e&&(Q=ut(Q)),Te(Q,C.ADD_TAGS,Be))),Ve(C,"ADD_ATTR")&&(typeof C.ADD_ATTR=="function"?et.attributeCheck=C.ADD_ATTR:Pn(C.ADD_ATTR)&&(ue===q&&(ue=ut(ue)),Te(ue,C.ADD_ATTR,Be))),Ve(C,"ADD_URI_SAFE_ATTR")&&Pn(C.ADD_URI_SAFE_ATTR)&&Te(_u,C.ADD_URI_SAFE_ATTR,Be),Ve(C,"FORBID_CONTENTS")&&Pn(C.FORBID_CONTENTS)&&(Yt===bu&&(Yt=ut(Yt)),Te(Yt,C.FORBID_CONTENTS,Be)),Ve(C,"ADD_FORBID_CONTENTS")&&Pn(C.ADD_FORBID_CONTENTS)&&(Yt===bu&&(Yt=ut(Yt)),Te(Yt,C.ADD_FORBID_CONTENTS,Be)),vu&&(Q["#text"]=!0),pe&&Te(Q,["html","head","body"]),Q.table&&(Te(Q,["tbody"]),delete qe.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 Z=N;N=C.TRUSTED_TYPES_POLICY;try{P=G("")}catch(ie){throw N=Z,ie}}else C.TRUSTED_TYPES_POLICY===null?(N=void 0,P=""):(N===void 0&&(N=$()),N&&typeof P=="string"&&(P=G("")));Je&&Je(C),li=C},h_=Te({},[...Yl,...Xl,...CA]),g_=Te({},[...Ql,...TA]),wO=function(C,D,Z){return D.namespaceURI===Xt?C==="svg":D.namespaceURI===Ls?C==="svg"&&(Z==="annotation-xml"||Cu[Z]):!!h_[C]},SO=function(C,D,Z){return D.namespaceURI===Xt?C==="math":D.namespaceURI===$s?C==="math"&&Tu[Z]:!!g_[C]},CO=function(C,D,Z){return D.namespaceURI===$s&&!Tu[Z]||D.namespaceURI===Ls&&!Cu[Z]?!1:!g_[C]&&(vO[C]||!h_[C])},TO=function(C){let D=v(C);(!D||!D.tagName)&&(D={namespaceURI:ci,tagName:"template"});const Z=qi(C.tagName),ie=qi(D.tagName);return Su[C.namespaceURI]?C.namespaceURI===$s?wO(Z,D,ie):C.namespaceURI===Ls?SO(Z,D,ie):C.namespaceURI===Xt?CO(Z,D,ie):!!(Co==="application/xhtml+xml"&&Su[C.namespaceURI]):!1},Bn=function(C){zr(t.removed,{element:C});try{v(C).removeChild(C)}catch{if(f(C),!v(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")}},v_=function(C){const D=h(C);if(D){const ie=[];Ki(D,Se=>{zr(ie,Se)}),Ki(ie,Se=>{try{f(Se)}catch{}})}const Z=w(C);if(Z)for(let ie=Z.length-1;ie>=0;--ie){const Se=Z[ie],Ee=Se&&Se.name;if(typeof Ee=="string")try{C.removeAttribute(Ee)}catch{}}},_r=function(C,D){try{zr(t.removed,{attribute:D.getAttributeNode(C),from:D})}catch{zr(t.removed,{attribute:null,from:D})}if(D.removeAttribute(C),C==="is")if(mn||br)try{Bn(D)}catch{}else try{D.setAttribute(C,"")}catch{}},NO=function(C){const D=w(C);if(D)for(let Z=D.length-1;Z>=0;--Z){const ie=D[Z],Se=ie&&ie.name;if(!(typeof Se!="string"||ue[Be(Se)]))try{C.removeAttribute(Se)}catch{}}},kO=function(C){const D=[C];for(;D.length>0;){const Z=D.pop();(S?S(Z):Z.nodeType)===Wt.element&&NO(Z);const ie=h(Z);if(ie)for(let Se=ie.length-1;Se>=0;--Se)D.push(ie[Se])}},y_=function(C){let D=null,Z=null;if(So)C="<remove></remove>"+C;else{const Ee=lv(C,/^[\r\n\t ]+/);Z=Ee&&Ee[0]}Co==="application/xhtml+xml"&&ci===Xt&&(C='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+C+"</body></html>");const ie=N?G(C):C;if(ci===Xt)try{D=new d().parseFromString(ie,Co)}catch{}if(!D||!D.documentElement){D=J.createDocument(ci,"template",null);try{D.documentElement.innerHTML=wu?P:ie}catch{}}const Se=D.body||D.documentElement;return C&&Z&&Se.insertBefore(n.createTextNode(Z),Se.childNodes[0]||null),ci===Xt?R.call(D,pe?"html":"body")[0]:pe?D.documentElement:Se},b_=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)},Ms=function(C){return C=Wi(C,ge," "),C=Wi(C,le," "),C=Wi(C,ce," "),C},ku=function(C){var D;C.normalize();const Z=H.call(C.ownerDocument||C,C,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let ie=Z.nextNode();for(;ie;)ie.data=Ms(ie.data),ie=Z.nextNode();const Se=(D=C.querySelectorAll)===null||D===void 0?void 0:D.call(C,"template");Se&&Ki(Se,Ee=>{di(Ee.content)&&ku(Ee.content)})},Os=function(C){const D=T?T(C):null;return typeof D!="string"||Be(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)},di=function(C){if(!S||typeof C!="object"||C===null)return!1;try{return S(C)===Wt.documentFragment}catch{return!1}},To=function(C){if(!S||typeof C!="object"||C===null)return!1;try{return typeof S(C)=="number"}catch{return!1}};function fn(ee,C,D){ee.length!==0&&Ki(ee,Z=>{Z.call(t,C,D,li)})}const xO=function(C,D){return!!(Mt&&C.hasChildNodes()&&!To(C.firstElementChild)&&Xe(yv,C.textContent)&&Xe(yv,C.innerHTML)||Mt&&C.namespaceURI===Xt&&D==="style"&&To(C.firstElementChild)||C.nodeType===Wt.processingInstruction||Mt&&C.nodeType===Wt.comment&&Xe(LA,C.data))},PO=function(C,D){if(!qe[D]&&S_(D)&&(oe.tagNameCheck instanceof RegExp&&Xe(oe.tagNameCheck,D)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(D)))return!1;if(vu&&!Yt[D]){const Z=v(C),ie=h(C);if(ie&&Z){const Se=ie.length;for(let Ee=Se-1;Ee>=0;--Ee){const Oe=yu?ie[Ee]:m(ie[Ee],!0);Z.insertBefore(Oe,g(C))}}}return Bn(C),!0},__=function(C){if(fn(W.beforeSanitizeElements,C,null),Os(C))return Bn(C),!0;const D=Be(T?T(C):C.nodeName);if(fn(W.uponSanitizeElement,C,{tagName:D,allowedTags:Q}),xO(C,D))return Bn(C),!0;if(qe[D]||!(et.tagCheck instanceof Function&&et.tagCheck(D))&&!Q[D])return PO(C,D);if((S?S(C):C.nodeType)===Wt.element&&!TO(C)||(D==="noscript"||D==="noembed"||D==="noframes")&&Xe($A,C.innerHTML))return Bn(C),!0;if(tt&&C.nodeType===Wt.text){const Z=Ms(C.textContent);C.textContent!==Z&&(zr(t.removed,{element:C.cloneNode()}),C.textContent=Z)}return fn(W.afterSanitizeElements,C,null),!1},w_=function(C,D,Z){if(Me[D]||ht&&(D==="id"||D==="name")&&(Z in n||Z in _O))return!1;const ie=ue[D]||et.attributeCheck instanceof Function&&et.attributeCheck(D,C);if(!(Lt&&Xe(be,D))){if(!(pn&&Xe(Y,D))){if(ie){if(!_u[D]){if(!Xe(he,Wi(Z,X,""))){if(!((D==="src"||D==="xlink:href"||D==="href")&&C!=="script"&&dv(Z,"data:")===0&&l_[C])){if(!(Nt&&!Xe(fe,Wi(Z,X,"")))){if(Z)return!1}}}}}else if(!(S_(C)&&(oe.tagNameCheck instanceof RegExp&&Xe(oe.tagNameCheck,C)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(C))&&(oe.attributeNameCheck instanceof RegExp&&Xe(oe.attributeNameCheck,D)||oe.attributeNameCheck instanceof Function&&oe.attributeNameCheck(D,C))||D==="is"&&oe.allowCustomizedBuiltInElements&&(oe.tagNameCheck instanceof RegExp&&Xe(oe.tagNameCheck,Z)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(Z))))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"]),S_=function(C){return!EO[qi(C)]&&Xe(_e,C)},AO=function(C,D,Z,ie){if(N&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!Z)switch(u.getAttributeType(C,D)){case"TrustedHTML":return G(ie);case"TrustedScriptURL":return E(ie)}return ie},IO=function(C,D,Z,ie){try{Z?C.setAttributeNS(Z,D,ie):C.setAttribute(D,ie),Os(C)?Bn(C):cv(t.removed)}catch{_r(D,C)}},C_=function(C){fn(W.beforeSanitizeAttributes,C,null);const D=C.attributes;if(!D||Os(C))return;const Z={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ue,forceKeepAttr:void 0};let ie=D.length;const Se=Be(C.nodeName);for(;ie--;){const Ee=D[ie],Oe=Ee.name,kt=Ee.namespaceURI,hn=Ee.value,Ot=Be(Oe),Pu=hn;let mt=Oe==="value"?Pu:gA(Pu);if(Z.attrName=Ot,Z.attrValue=mt,Z.keepAttr=!0,Z.forceKeepAttr=void 0,fn(W.uponSanitizeAttribute,C,Z),mt=Z.attrValue,Fn&&(Ot==="id"||Ot==="name")&&dv(mt,c_)!==0&&(_r(Oe,C),mt=c_+mt),Mt&&Xe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,mt)){_r(Oe,C);continue}if(Ot==="attributename"&&lv(mt,"href")){_r(Oe,C);continue}if(!Z.forceKeepAttr){if(!Z.keepAttr){_r(Oe,C);continue}if(!$t&&Xe(MA,mt)){_r(Oe,C);continue}if(tt&&(mt=Ms(mt)),!w_(Se,Ot,mt)){_r(Oe,C);continue}mt=AO(Se,Ot,kt,mt),mt!==Pu&&IO(C,Oe,kt,mt)}}fn(W.afterSanitizeAttributes,C,null)},js=function(C){let D=null;const Z=b_(C);for(fn(W.beforeSanitizeShadowDOM,C,null);D=Z.nextNode();)if(fn(W.uponSanitizeShadowNode,D,null),__(D),C_(D),di(D.content)&&js(D.content),(S?S(D):D.nodeType)===Wt.element){const ie=b(D);di(ie)&&(xu(ie),js(ie))}fn(W.afterSanitizeShadowDOM,C,null)},xu=function(C){const D=[{node:C,shadow:null}];for(;D.length>0;){const Z=D.pop();if(Z.shadow){js(Z.shadow);continue}const ie=Z.node,Se=(S?S(ie):ie.nodeType)===Wt.element,Ee=h(ie);if(Ee)for(let Oe=Ee.length-1;Oe>=0;--Oe)D.push({node:Ee[Oe],shadow:null});if(Se){const Oe=T?T(ie):null;if(typeof Oe=="string"&&Be(Oe)==="template"){const kt=ie.content;di(kt)&&D.push({node:kt,shadow:null})}}if(Se){const Oe=b(ie);di(Oe)&&D.push({node:null,shadow:Oe},{node:Oe,shadow:null})}}};return t.sanitize=function(ee){let C=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},D=null,Z=null,ie=null,Se=null;if(wu=!ee,wu&&(ee="<!-->"),typeof ee!="string"&&!To(ee)&&(ee=wA(ee),typeof ee!="string"))throw or("dirty is not a string, aborting");if(!t.isSupported)return ee;ae?(Q=Ge,ue=On):Nu(C),(W.uponSanitizeElement.length>0||W.uponSanitizeAttribute.length>0)&&(Q=ut(Q)),W.uponSanitizeAttribute.length>0&&(ue=ut(ue)),t.removed=[];const Ee=yu&&typeof ee!="string"&&To(ee);if(Ee){const hn=T?T(ee):ee.nodeName;if(typeof hn=="string"){const Ot=Be(hn);if(!Q[Ot]||qe[Ot])throw or("root node is forbidden and cannot be sanitized in-place")}if(Os(ee))throw or("root node is clobbered and cannot be sanitized in-place");try{xu(ee)}catch(Ot){throw v_(ee),Ot}}else if(To(ee))D=y_("<!---->"),Z=D.ownerDocument.importNode(ee,!0),Z.nodeType===Wt.element&&Z.nodeName==="BODY"||Z.nodeName==="HTML"?D=Z:D.appendChild(Z),xu(Z);else{if(!mn&&!tt&&!pe&&ee.indexOf("<")===-1)return N&&jn?G(ee):ee;if(D=y_(ee),!D)return mn?null:jn?P:""}D&&So&&Bn(D.firstChild);const Oe=b_(Ee?ee:D);try{for(;ie=Oe.nextNode();)__(ie),C_(ie),di(ie.content)&&js(ie.content)}catch(hn){throw Ee&&v_(ee),hn}if(Ee)return Ki(t.removed,hn=>{hn.element&&kO(hn.element)}),tt&&ku(ee),ee;if(mn){if(tt&&ku(D),br)for(Se=k.call(D.ownerDocument);D.firstChild;)Se.appendChild(D.firstChild);else Se=D;return(ue.shadowroot||ue.shadowrootmode)&&(Se=j.call(r,Se,!0)),Se}let kt=pe?D.outerHTML:D.innerHTML;return pe&&Q["!doctype"]&&D.ownerDocument&&D.ownerDocument.doctype&&D.ownerDocument.doctype.name&&Xe(RA,D.ownerDocument.doctype.name)&&(kt="<!DOCTYPE "+D.ownerDocument.doctype.name+`>
|
|
48
|
-
`+kt),
|
|
49
|
-
]`).replace("lheading",Tv).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},XA=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,QA=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,xv=/^( {2,}|\\)\n(?!\s*$)/,ZA=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Yr=/[\p{P}\p{S}]/u,Za=/[\s\p{P}\p{S}]/u,ad=/[^\s\p{P}\p{S}]/u,eI=Ne(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Za).getRegex(),Pv=/(?!~)[\p{P}\p{S}]/u,tI=/(?!~)[\s\p{P}\p{S}]/u,nI=/(?:[^\s\p{P}\p{S}]|~)/u,rI=Ne(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",FA?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ev=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,iI=Ne(Ev,"u").replace(/punct/g,Yr).getRegex(),oI=Ne(Ev,"u").replace(/punct/g,Pv).getRegex(),Av="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",aI=Ne(Av,"gu").replace(/notPunctSpace/g,ad).replace(/punctSpace/g,Za).replace(/punct/g,Yr).getRegex(),sI=Ne(Av,"gu").replace(/notPunctSpace/g,nI).replace(/punctSpace/g,tI).replace(/punct/g,Pv).getRegex(),cI=Ne("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ad).replace(/punctSpace/g,Za).replace(/punct/g,Yr).getRegex(),lI=Ne(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Yr).getRegex(),dI=Ne("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,ad).replace(/punctSpace/g,Za).replace(/punct/g,Yr).getRegex(),uI=Ne(/\\(punct)/,"gu").replace(/punct/g,Yr).getRegex(),pI=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(),mI=Ne(id).replace("(?:-->|$)","-->").getRegex(),fI=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",mI).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),es=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,hI=Ne(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",es).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Iv=Ne(/^!?\[(label)\]\[(ref)\]/).replace("label",es).replace("ref",rd).getRegex(),Rv=Ne(/^!?\[(ref)\](?:\[\])?/).replace("ref",rd).getRegex(),gI=Ne("reflink|nolink(?!\\()","g").replace("reflink",Iv).replace("nolink",Rv).getRegex(),Dv=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,sd={_backpedal:sr,anyPunctuation:uI,autolink:pI,blockSkip:rI,br:xv,code:QA,del:sr,delLDelim:sr,delRDelim:sr,emStrongLDelim:iI,emStrongRDelimAst:aI,emStrongRDelimUnd:cI,escape:XA,link:hI,nolink:Rv,punctuation:eI,reflink:Iv,reflinkSearch:gI,tag:fI,text:ZA,url:sr},vI={...sd,link:Ne(/^!?\[(label)\]\((.*?)\)/).replace("label",es).getRegex(),reflink:Ne(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",es).getRegex()},cd={...sd,emStrongRDelimAst:sI,emStrongLDelim:oI,delLDelim:lI,delRDelim:dI,url:Ne(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Dv).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",Dv).getRegex()},yI={...cd,br:Ne(xv).replace("{2,}","*").getRegex(),text:Ne(cd.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ts={normal:od,gfm:JA,pedantic:YA},Ji={normal:sd,gfm:cd,breaks:yI,pedantic:vI},bI={"&":"&","<":"<",">":">",'"':""","'":"'"},Lv=e=>bI[e];function
|
|
50
|
-
`),n=t.length-1;for(;n>=0&&
|
|
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},CC="DialogDescriptionWarning",TC=({contentRef:e,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Rm(CC).contentName}}.`;return K(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},NC=Sm,kC=Nm,xC=km,PC=xm;function wi({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:g}){return a(NC,{modal:o,open:p,onOpenChange:u,children:p?a(kC,{children:[a(xC,{asChild:!0,children:a("div",{className:m,id:f})}),a(PC,{"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??(g?a("div",{id:g}):null)})})]}):null})}var Dm=500,Qo=null,Si=null,Ci=null;function Ti(e){return Si?Si(e)?(Ci=document.activeElement instanceof HTMLElement?document.activeElement:null,!0):!1:(Ci=document.activeElement instanceof HTMLElement?document.activeElement:null,Qo=e,!0)}function it(e){return e.recipientKind==="identity"?`identity:${e.identityId}`:`team:${e.teamId}`}function Lm(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 Tc(e){return e.recipientKind==="identity"?it({recipientKind:"identity",identityId:e.identityId}):it({recipientKind:"team",teamId:e.teamId})}function EC(e,t){return Tc(e)===it(t)}function $m(e,t){return e instanceof Us?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function Mm({checked:e,description:t,disabled:n,label:r,onChange:i}){const o=`recipient-policy-choice-${gi()}`;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 AC(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=Tc(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 Om(e){return e.mode==="project-add"?[...new Set(e.projectIds)]:e.mode==="project-manage"?[e.projectId]:[]}function IC(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(Tc):n.filter(r=>EC(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function RC(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 DC(e,t,n){return e.mode==="project-add"?Om(e).flatMap(r=>t.flatMap(i=>{const o=Lm(i);return o?[{canonicalProjectIdentity:r,recipient:o,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=Lm(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 LC(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 jm(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 $C(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 MC(e){const t=new Set;return e.filter(n=>t.has(n.deviceId)?!1:(t.add(n.deviceId),!0))}function OC({preview:e,recipientLabels:t}){const n=MC(e.effectiveDevices),r=$C(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:["— ",jm(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:["— ",jm(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 jC({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 FC({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,g]=I(null),[h,v]=I(""),[b,w]=I(!1),S=B(!1),T=xe(()=>AC(e,r),[e,r]),N=xe(()=>new Map([...e.teams.map(Y=>[`team:${Y.teamId}`,Y.displayName]),...e.identities.map(Y=>[`identity:${Y.identityId}`,Y.displayName])]),[e]),P=xe(()=>new Set(n.map(Y=>Y.canonicalProjectIdentity)),[n]);if(K(()=>{if(Si=Y=>{if(S.current)return!1;const fe=IC(Y,e);return i(Y),l(fe),s(Y.mode==="recipient-add"?[]:fe),u(null),m(null),g(null),v(""),w(!1),S.current=!1,!0},Qo){const Y=Qo;Qo=null,Si(Y)}return()=>{Si=null}},[e]),K(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const A=LC(r),M=Om(r),U=r.mode==="recipient-manage"?!1:M.some(Y=>!P.has(Y)),x=(r.mode==="recipient-add"||r.mode==="recipient-manage")&&!T.some(Y=>Y.key===it(r.recipient)),G=t.loading||t.loadError||U||x,E=DC(r,o,c),$=E.length>Dm,L=(r.mode==="project-add"||r.mode==="recipient-add")&&o.length===0,J=r.mode!=="project-add"&&r.mode!=="recipient-add"&&E.length===0,H=RC(n,r,c),k=p?.status==="applied",R=p?k?"Recipient access updated":"Recipient access needs attention":d?"Review recipient access":A.title,j=p?k?"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.":A.description,V=()=>{S.current||(i(null),u(null),m(null),g(null),v(""))},ge=Y=>{s(fe=>fe.includes(Y)?fe.filter(X=>X!==Y):[...fe,Y]),g(null),v("")},le=async()=>{if(!(G||L||J||$||S.current)){S.current=!0,w(!0),g(null),v("Reviewing exact recipient access changes.");try{u(await iw({version:1,changes:E})),v("Review ready. Confirm the exact changes.")}catch(Y){g($m(Y,"Unable to review recipient access changes.")),v("")}finally{S.current=!1,w(!1)}}},ce=async()=>{if(!(!d||S.current)){S.current=!0,w(!0),g(null),v("Saving recipient access changes.");try{const Y=await ow({version:1,changes:d.normalizedChanges,reviewedPolicyDigest:d.reviewedPolicyDigest});m(Y),v("");try{await t.onCommitted?.(Y)}catch{g("Recipient access was saved, but this view could not refresh.")}}catch(Y){Y instanceof Us&&(u(null),v("")),g($m(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.":x&&(be="This recipient is no longer available. Refresh and try again."),a(wi,{ariaDescribedby:"recipient-policy-management-description",ariaLabelledby:"recipient-policy-management-title",contentClassName:"modal recipient-policy-management-dialog",contentId:"recipientPolicyManagementDialog",onCloseAutoFocus:Y=>{Y.preventDefault();const fe=r.mode.startsWith("project-")?"tabBtn-projects":"tabBtn-sharing",X=Ci?.isConnected?Ci:document.getElementById(fe);X instanceof HTMLElement&&X.focus(),Ci=null},onOpenAutoFocus:Y=>{const fe=document.getElementById("recipient-policy-management-title");fe&&(Y.preventDefault(),fe.focus())},onOpenChange:Y=>{Y||V()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyManagementDialogBackdrop",children:a("div",{"aria-busy":b||t.loading?"true":"false",className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"recipient-policy-management-title",tabIndex:-1,children:R}),a(Mo,{ariaLabel:`Close ${R}`,className:"modal-close-button recipient-policy-management-target",disabled:b,onClick:V})]}),a("div",{className:"modal-body recipient-policy-management-selection",children:[a("p",{className:"small",id:"recipient-policy-management-description",children:j}),be?a("p",{"aria-live":"polite",role:t.loadError?"alert":"status",children:be}):p&&d?a(jC,{preview:d,result:p}):d?a(OC,{preview:d,recipientLabels:N}):r.mode==="recipient-add"||r.mode==="recipient-manage"?a("fieldset",{className:"sync-dialog-radio-list",disabled:b,children:[a("legend",{children:A.legend}),H.length?H.map(Y=>a(Mm,{checked:o.includes(Y.canonicalProjectIdentity),description:Y.description,disabled:b,label:Y.displayName,onChange:()=>ge(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:b,children:[a("legend",{children:A.legend}),T.length?T.map(Y=>a(Mm,{checked:o.includes(Y.key),description:Y.description,disabled:b,label:Y.label,onChange:()=>ge(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 ",E.length.toLocaleString()," access changes. Review at most ",Dm.toLocaleString()," changes at a time; reduce the selection and try again."]}):null]}),a("div",{className:"modal-footer recipient-policy-management-actions",children:[a("button",{className:"settings-button recipient-policy-management-target",disabled:b,onClick:d&&!p?()=>{u(null),v("")}:V,type:"button",children:p?"Done":d?"Back":"Cancel"}),!p&&!be?a("button",{className:"settings-button sync-dialog-confirm recipient-policy-management-target",disabled:b||!d&&(L||J||$),onClick:()=>{d?ce():le()},type:"button",children:b?d?"Saving…":"Reviewing…":d?"Confirm changes":"Review changes"}):null]})]})})}function Fm(e,t,n,r={}){Ue(a(FC,{intent:n,options:r,projects:t}),e)}function Zo(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function BC(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 ea(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,Er=null;function ta(e=[],t=""){if(Er){const n=Er(e,t);return n||(Pr=null),n}return Pr={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function Bm(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 UC(e){const t=`share-project-${gi()}`,n=Bm(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 GC({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 HC({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),[g,h]=I(!1),[v,b]=I(null),[w,S]=I(!1),T=xe(()=>e.filter(Bm),[e]);K(()=>{if(Er=(x,G="")=>{if(t)return!1;const E=[...new Set(x)],$=E.some(L=>!T.some(J=>J.workspace_identity===L));return o(G.trim()),c($?[]:E),S($),d(null),p(null),f($?"The original project selection is no longer available. Refresh Projects and try again.":null),b(null),r(!0),!0},Pr){const x=Pr;Pr=null,Er(x.projectIds,x.teammateName)}return()=>{Er=null}},[T,t]),K(()=>{t&&(Pr=null,r(!1),o(""),c([]),d(null),p(null),f(null),b(null),S(!1))},[t]);const N=()=>{g||r(!1)},P=x=>{c(G=>G.includes(x)?G.filter(E=>E!==x):[...G,x])},A=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 uw({teammate_name:i.trim(),project_ids:s}))}catch(x){f(Um(x,"Unable to review this invitation."))}finally{h(!1)}},M=async()=>{if(l){f(null),h(!0);try{p(await pw({teammate_name:l.teammate.display_name,project_ids:l.projects.map(x=>x.project_id),reviewed_project_set_digest:l.reviewed_project_set_digest}))}catch(x){x instanceof Error&&x.message==="reviewed_project_set_changed"&&d(null),f(Um(x,"Unable to create this invitation."))}finally{h(!1)}}},U=async()=>{if(u){f(null),b(null);try{if(!navigator.clipboard)throw new Error("Clipboard access is unavailable.");await navigator.clipboard.writeText(u.invite.link),b("Invite copied.")}catch(x){f(x instanceof Error?x.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:()=>Er?.([]),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(wi,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:x=>{x||N()},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:g,onClick:N,type:"button",children:"×"})]}),a("div",{"aria-busy":g,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(x=>x.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"}),v?a("p",{role:"status",children:v}):null]}):l?a(GC,{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:x=>o(x.currentTarget.value),type:"text",value:i})]}),a("fieldset",{className:"sync-dialog-radio-list",children:[a("legend",{children:"Select exact projects"}),e.map(x=>a(UC,{onToggle:P,project:x,selected:s.includes(x.workspace_identity)},x.workspace_identity))]})]}),m?a("p",{role:"alert",children:m}):null]}),a("div",{className:"modal-footer",children:[a("button",{className:"settings-button",disabled:g,onClick:N,type:"button",children:u?"Done":"Cancel"}),u?null:a("button",{className:"settings-button sync-dialog-confirm",disabled:g||w,onClick:()=>{l?M():A()},type:"button",children:g?l?"Creating invite…":"Reviewing…":l?"Create invite":"Review sharing"})]})]})}):null]})}function Gm(e,t,n={}){Ue(a(HC,{inventoryError:n.inventoryError===!0,projects:t}),e)}var KC=/^(?:local:|identity:|pending_)/iu,qC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,VC=/^[0-9a-f]{12,}$/iu;function Hm(e){const t=String(e??"").trim();return!t||KC.test(t)||qC.test(t)||VC.test(t)?"":t}function na(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 WC(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 ra(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 Ni(e){return`${e.toLocaleString()} existing ${e===1?"memory":"memories"}`}function zC({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})," — ",Ni(t.existingMemoryCount)," and future activity"]},t.canonicalProjectIdentity))})}function JC({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(zC,{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 YC({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," — ",Ni(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," — ",Ni(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," — ",Ni(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 Km({preview:e}){return e.journey==="team"?a(JC,{preview:e}):a(YC,{preview:e})}function XC({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})," —"," ",Ni(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 QC({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 ZC({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 qm(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function eT({intent:e}){const t=e.teams.filter(q=>q.status==="active"),n=e.identities.filter(q=>q.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,g]=I(null),[h,v]=I(null),[b,w]=I(null),[S,T]=I(""),[N,P]=I(""),[A,M]=I(null),[U,x]=I(!1),[G,E]=I(""),[$,L]=I(""),J=B(null),H=B(0),k=B(""),R=B(!1);K(()=>{if(b){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,b]);const j=()=>{H.current+=1,k.current="",R.current=!1,u(""),m(null),g(null),v(null),w(null),T(""),P(""),M(null),E(""),L("")},V=(q,oe)=>{j(),J.current=oe,i(q)},ge=()=>{U||(i(null),j())},le=q=>{H.current+=1,k.current=q,u(q)},ce=q=>{s(q),l(q==="team_member"?t[0]?.teamId??"":n[0]?.identityId??""),j()},be=async()=>{if(c){x(!0),L(""),E("Reviewing invitation…");try{m((await aw(qm(o,c))).preview),E("Review ready. Confirm the invitation details.")}catch(q){L(ra(q,"Unable to review this invitation.")),E("")}finally{x(!1)}}},Y=async()=>{if(p){x(!0),L(""),E("Creating invitation…");try{M(await sw({...qm(o,c),reviewed_onboarding_digest:p.reviewedOnboardingDigest})),E("Invitation created.")}catch(q){q instanceof Error&&q.message==="reviewed_onboarding_stale"&&m(null),L(ra(q,"Unable to create this invitation.")),E("")}finally{x(!1)}}},fe=async()=>{const q=k.current.trim(),oe=H.current;if(!q){L("Paste an invitation first.");return}const qe=()=>H.current===oe&&k.current.trim()===q;x(!0),L(""),E("Reviewing invitation…");try{const Me=await ju(q);if(!qe())return;g(Me),Me.kind==="project_share_invite"&&(T(Hm(Me.recipient_name)),P(Hm(Me.device_name))),E(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(!qe())return;L(ra(Me,"Unable to review this invitation.")),E("")}finally{x(!1)}},X=async()=>{if(!(U||R.current||b)&&!(!f||f.kind==="legacy_team_invite")&&!(f.kind==="project_share_invite"&&!(f.projects?.length??0))&&!(f.kind==="project_share_invite"&&(na(S,"Identity display name")||na(N,"Device display name")))){R.current=!0,x(!0),L(""),E("Accepting invitation…");try{const q=f.kind==="project_share_invite"?await Bs(d.trim(),{recipient_name:S.trim(),device_name:N.trim()}):await Bs(d.trim(),{recipient_name:f.recipient_name,device_name:f.device_name,reviewed_onboarding_digest:f.onboarding.reviewedOnboardingDigest});if(f.kind==="project_share_invite")v(WC(q)),E("");else{const oe=f.kind;w({kind:oe,restartRequired:q.restart_required===!0||q.setup_state==="restart_required",detail:(typeof q.detail=="string"?q.detail.trim():"")||"Restart codemem before continuing.",deliveryPending:oe==="add_device"&&(f.onboarding?.projects?.length??0)>0}),E("")}}catch(q){R.current=!1;const oe=q instanceof Error?q.message.trim():"";L(ra(q,f.kind==="project_share_invite"&&oe?oe:"Unable to accept this invitation.")),E("")}finally{x(!1)}}},_e=async()=>{const q=A?.invite.link||A?.invite.encoded||"";if(!q){L("The invitation text is unavailable.");return}try{await navigator.clipboard.writeText(q),E("Invitation copied.")}catch{L("Unable to copy the invitation.")}},he=f?.kind==="team_member"||f?.kind==="add_device"?f.onboarding:null,Q=f?.kind==="project_share_invite"?f:null,$e=Q?na(S,"Identity display name"):"",ue=Q?na(N,"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=>{ce("team_member"),V("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=>{ce("add_device"),V("create",q.currentTarget)},type:"button",children:"Add a device"}),a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>ta(),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=>V("accept",q.currentTarget),type:"button",children:"Review invitation"}),a("p",{className:"small",children:"Legacy invitation import remains under Advanced Team administration."})]}),r?a(wi,{ariaDescribedby:"recipient-invitation-description",ariaLabelledby:"recipient-invitation-title",contentClassName:"modal recipient-policy-invitation-dialog",contentId:"recipientInvitationDialog",onCloseAutoFocus:q=>{q.preventDefault(),J.current?.focus(),J.current=null},onOpenAutoFocus:q=>{q.preventDefault(),document.getElementById("recipient-invitation-title")?.focus()},onOpenChange:q=>{q||ge()},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:b?"Invitation accepted":r==="create"?"Create invitation":"Review invitation"}),a(Mo,{ariaLabel:"Close invitation",className:"modal-close-button recipient-policy-sharing-target-24",disabled:U,onClick:ge})]}),a("div",{className:"modal-body",children:[a("p",{className:"small",id:"recipient-invitation-description",children:b?"The invitation has been accepted.":"Confirm exactly what this invitation includes before continuing."}),r==="create"&&!p&&!A?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"&&!f&&!b?a("label",{className:"field",htmlFor:"recipient-invitation-value",children:[a("span",{children:"Invitation"}),a("textarea",{id:"recipient-invitation-value",onInput:q=>{le(q.currentTarget.value),g(null),v(null),E(""),L("")},rows:5,value:d})]}):null,p?a(Km,{preview:p}):null,he&&!b?a(Km,{preview:he}):null,Q&&!h?a(XC,{deviceName:N,deviceNameError:ue,invite:Q,onDeviceNameChange:q=>{P(q),L("")},onRecipientNameChange:q=>{T(q),L("")},recipientName:S,recipientNameError:$e}):null,h?a(QC,{result:h}):null,b?a(ZC,{result:b}):null,A?a("div",{children:[a("p",{children:"Share the invitation with the recipient."}),a("button",{className:"settings-button",onClick:()=>{_e()},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:ge,type:"button",children:A||h||b?"Done":"Cancel"}),r==="create"&&!A?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&&!b?a("button",{className:"settings-button sync-dialog-confirm",disabled:U,onClick:()=>{fe()},type:"button",children:U?"Reviewing…":"Review invitation"}):he&&!b||Q&&!h?a("button",{className:"settings-button sync-dialog-confirm",disabled:U||!!(Q&&(!Q.projects?.length||$e||ue)),onClick:()=>{X()},type:"button",children:U?"Accepting…":Q?"Accept Project access":"Accept invitation"}):null]})]})}):null]})}var Wn=[{id:"teams",label:"Teams"},{id:"identities",label:"Identities"},{id:"received",label:"Received"},{id:"invitations",label:"Invitations"}];function bn(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function Ar(e,t){return e.length?e.join(", "):t}function Nc(e,t){return[...new Set(e)].flatMap(n=>{const r=t.get(n);return r?[r.displayName]:[]})}function Vm({descriptionId:e,displayName:t,recipient:n}){const r=()=>{Ti({mode:"recipient-manage",recipient:n})},i=()=>{Ti({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 tT({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=Nc(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:[bn(l.length,"active member")," —"," ",Ar(l,"No active members")]})]}),a("div",{children:[a("dt",{children:"Registered devices"}),a("dd",{children:bn(d,"active registered device")})]}),a("div",{children:[a("dt",{children:"Shared Projects"}),a("dd",{children:[bn(u.length,"active shared Project")," —"," ",Ar(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(Vm,{descriptionId:m,displayName:o.displayName,recipient:{recipientKind:"team",teamId:o.teamId}})]},o.teamId)})})}function nT({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(g=>g.status==="active"&&g.identityId===o.identityId),l=[...new Set(e.teamMemberships.filter(g=>g.status==="active"&&g.identityId===o.identityId&&r.has(g.teamId)).map(g=>g.teamId))],d=l.map(g=>r.get(g)?.displayName??""),u=Nc(e.projectRecipients.filter(g=>g.status==="active"&&g.recipientKind==="identity"&&g.identityId===o.identityId).map(g=>g.canonicalProjectIdentity),i),p=Nc(e.projectRecipients.filter(g=>g.status==="active"&&g.recipientKind==="team"&&l.includes(g.teamId)).map(g=>g.canonicalProjectIdentity),i),m=`recipient-policy-sharing-identity-title-${s}`,f=`recipient-policy-sharing-identity-add-description-${s}`;return a("article",{"aria-labelledby":m,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:m,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:[bn(c.length,"active registered device")," —"," ",Ar(c.map(g=>g.displayName),"No active devices")]})]}),a("div",{children:[a("dt",{children:"Team memberships"}),a("dd",{children:[bn(d.length,"active Team membership")," —"," ",Ar(d,"No active Team memberships")]})]}),a("div",{children:[a("dt",{children:"Directly shared Projects"}),a("dd",{children:[bn(u.length,"directly shared active Project")," —"," ",Ar(u,"No Projects shared directly")]})]}),a("div",{children:[a("dt",{children:"Projects through Teams"}),a("dd",{children:[bn(p.length,"Team-inherited Project")," —"," ",Ar(p,"No Projects inherited through Teams")]})]})]}),a("p",{className:"small",children:"Projects through Teams are shown separately and are not direct Identity shares."}),a(Vm,{descriptionId:f,displayName:o.displayName,recipient:{recipientKind:"identity",identityId:o.identityId}})]},o.identityId)})})}function rT({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:bn(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 iT({intent:e,options:t,projects:n}){const[r,i]=I("teams"),o=B([]),s=l=>{const d=Wn[l];d&&(i(d.id),o.current[l]?.focus())},c=(l,d)=>{let u=null;l.key==="ArrowRight"?u=(d+1)%Wn.length:l.key==="ArrowLeft"?u=(d-1+Wn.length)%Wn.length:l.key==="Home"?u=0:l.key==="End"&&(u=Wn.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:Wn.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))}),Wn.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(tT,{intent:e,projects:n}):l.id==="identities"?a(nT,{intent:e,projects:n}):l.id==="received"?a(rT,{received:t.received??[]}):a(eT,{intent:e})},l.id))]})}function oT(e,t,n,r={}){Ue(a(iT,{intent:n,options:r,projects:t}),e)}var kc={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function aT(){const e=[];let t=0;for(;;){const n=await Po({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return{manageable:ea(e),received:BC(e)}}var sT={loadIntent:Gs,loadProjects:aT,mountManagement:Fm,mountSharing:oT};function cT(e={}){const t={...sT,...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,[],kc,{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,[],kc,{loadError:!0}),o&&t.mountManagement(o,[],kc,{loadError:!0})}}}var lT=Symbol.for("preact-signals");function ia(){if(rn>1)rn--;else{var e,t=!1;for((function(){var i=aa;for(aa=void 0;i!==void 0;)i.S.v===i.v&&(i.S.i=i.i),i=i.o})();ki!==void 0;){var n=ki;for(ki=void 0,oa++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Jm(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if(oa=0,rn--,t)throw e}}function dT(e){if(rn>0)return e();Pc=++uT,rn++;try{return e()}finally{ia()}}var De=void 0;function xc(e){var t=De;De=void 0;try{return e()}finally{De=t}}var Wm,ki=void 0,rn=0,oa=0,uT=0,Pc=0,aa=void 0,sa=0;function zm(e){if(De!==void 0){var t=e.n;if(t===void 0||t.t!==De)return t={i:0,S:e,p:De.s,n:void 0,t:De,e:void 0,x:void 0,r:t},De.s!==void 0&&(De.s.n=t),De.s=t,e.n=t,32&De.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=De.s,t.n=void 0,De.s.n=t,De.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=lT,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:xc(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&&xc(function(){var i;(i=t.Z)==null||i.call(t)}))}},Je.prototype.subscribe=function(e){var t=this;return xi(function(){var n=t.value,r=De;De=void 0;try{e(n)}finally{De=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 xc(function(){return e.value})},Object.defineProperty(Je.prototype,"value",{get:function(){var e=zm(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(oa>100)throw new Error("Cycle detected");(function(n){rn!==0&&oa===0&&n.l!==Pc&&(n.l=Pc,aa={S:n,v:n.v,i:n.i,o:aa})})(this),this.v=e,this.i++,sa++,rn++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{ia()}}}});function Ec(e,t){return new Je(e,t)}function Jm(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 Ym(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 Xm(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=sa-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===sa))return!0;if(this.g=sa,this.f|=1,this.i>0&&!Jm(this))return this.f&=-2,!0;var e=De;try{Ym(this),De=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 De=e,Xm(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=zm(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function Qm(e,t){return new zn(e,t)}function Zm(e){var t=e.m;if(e.m=void 0,typeof t=="function"){rn++;var n=De;De=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,Ac(e),r}finally{De=n,ia()}}}function Ac(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,Zm(e)}function pT(e){if(De!==this)throw new Error("Out-of-order effect");Xm(this),De=e,this.f&=-2,8&this.f&&Ac(this),ia()}function Ir(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,Wm&&Wm.push(this)}Ir.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()}},Ir.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Zm(this),Ym(this),rn++;var e=De;return De=this,pT.bind(this,e)},Ir.prototype.N=function(){2&this.f||(this.f|=2,this.u=ki,ki=this)},Ir.prototype.d=function(){this.f|=8,1&this.f||Ac(this)},Ir.prototype.dispose=function(){this.d()};function xi(e,t){var n=new Ir(e,t);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var ef,Ic,ca,mT=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,OO=[],tf=[];xi(function(){ef=this.N})();function Rr(e,t){me[e]=t.bind(null,me[e]||function(){})}function la(e){if(ca){var t=ca;ca=void 0,t()}ca=e&&e.S()}function nf(e){var t=this,n=e.data,r=hT(n);r.value=n;var i=xe(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=Qm(function(){var f=r.value.value;return f===0?0:f===!0?"":f||""}),u=Qm(function(){return!Array.isArray(d.value)&&!Yu(d.value)}),p=xi(function(){if(this.N=rf,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}nf.displayName="ReactiveTextNode",Object.defineProperties(Je.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:nf},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),Rr("__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)}),Rr("__r",function(e,t){if(e(t),t.type!==te){la();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,o){var s;return xi(function(){s=this},{name:o}),s.c=i,s})(function(){var i;mT&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:""))),Ic=r,la(n)}}),Rr("__e",function(e,t,n,r){la(),Ic=void 0,e(t,n,r)}),Rr("diffed",function(e,t){la(),Ic=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=fT(n,l,u),o[l]=d):d.o(u,i)}}}e(t)});function fT(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,o=Ec(n),s=n.peek();return{o:function(c,l){o.value=c,s=c.peek()},d:xi(function(){this.N=rf;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})}}Rr("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)}),Rr("__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 hT(e,t){return xe(function(){return Ec(e,t)},[])}var jO=typeof requestAnimationFrame>"u"?setTimeout:function(e){var t=function(){clearTimeout(n),cancelAnimationFrame(r),e()},n=setTimeout(t,35),r=requestAnimationFrame(t)},gT=function(e){queueMicrotask(function(){queueMicrotask(e)})};function vT(){dT(function(){for(var e;e=tf.shift();)ef.call(e)})}function rf(){tf.push(this)===1&&(me.requestAnimationFrame||gT)(vT)}function da(e){const t=e+"CollectionProvider",[n,r]=st(t),[i,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=h=>{const{scope:v,children:b}=h,w=nn.useRef(null),S=nn.useRef(new Map).current;return a(i,{scope:v,itemMap:S,collectionRef:w,children:b})};s.displayName=t;const c=e+"CollectionSlot",l=Hn(c),d=nn.forwardRef((h,v)=>{const{scope:b,children:w}=h;return a(l,{ref:we(v,o(c,b).collectionRef),children:w})});d.displayName=c;const u=e+"CollectionItemSlot",p="data-radix-collection-item",m=Hn(u),f=nn.forwardRef((h,v)=>{const{scope:b,children:w,...S}=h,T=nn.useRef(null),N=we(v,T),P=o(u,b);return nn.useEffect(()=>(P.itemMap.set(T,{ref:T,...S}),()=>{P.itemMap.delete(T)})),a(m,{[p]:"",ref:N,children:w})});f.displayName=u;function g(h){const v=o(e+"CollectionConsumer",h);return nn.useCallback(()=>{const b=v.collectionRef.current;if(!b)return[];const w=Array.from(b.querySelectorAll(`[${p}]`));return Array.from(v.itemMap.values()).sort((S,T)=>w.indexOf(S.ref.current)-w.indexOf(T.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:s,Slot:d,ItemSlot:f},g,r]}var of=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"}),yT="VisuallyHidden",ua=F((e,t)=>a(se.span,{...e,ref:t,style:{...of,...e.style}}));ua.displayName=yT;var bT=ua,Rc="ToastProvider",[Dc,_T,wT]=da("Toast"),[af,FO]=st("Toast",[wT]),[ST,pa]=af(Rc),sf=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=B(!1),m=B(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${Rc}\`. Expected non-empty \`string\`.`),a(Dc.Provider,{scope:t,children:a(ST,{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})})};sf.displayName=Rc;var cf="ToastViewport",CT=["F8"],Lc="toast.viewportPause",$c="toast.viewportResume",lf=F((e,t)=>{const{__scopeToast:n,hotkey:r=CT,label:i="Notifications ({hotkey})",...o}=e,s=pa(cf,n),c=_T(n),l=B(null),d=B(null),u=B(null),p=B(null),m=we(t,p,s.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=s.toastCount>0;K(()=>{const v=b=>{r.length!==0&&r.every(w=>b[w]||b.code===w)&&p.current?.focus()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r]),K(()=>{const v=l.current,b=p.current;if(g&&v&&b){const w=()=>{if(!s.isClosePausedRef.current){const P=new CustomEvent(Lc);b.dispatchEvent(P),s.isClosePausedRef.current=!0}},S=()=>{if(s.isClosePausedRef.current){const P=new CustomEvent($c);b.dispatchEvent(P),s.isClosePausedRef.current=!1}},T=P=>{v.contains(P.relatedTarget)||S()},N=()=>{v.contains(document.activeElement)||S()};return v.addEventListener("focusin",w),v.addEventListener("focusout",T),v.addEventListener("pointermove",w),v.addEventListener("pointerleave",N),window.addEventListener("blur",w),window.addEventListener("focus",S),()=>{v.removeEventListener("focusin",w),v.removeEventListener("focusout",T),v.removeEventListener("pointermove",w),v.removeEventListener("pointerleave",N),window.removeEventListener("blur",w),window.removeEventListener("focus",S)}}},[g,s.isClosePausedRef]);const h=re(({tabbingDirection:v})=>{const b=c().map(w=>{const S=w.ref.current,T=[S,...jT(S)];return v==="forwards"?T:T.reverse()});return(v==="forwards"?b.reverse():b).flat()},[c]);return K(()=>{const v=p.current;if(v){const b=w=>{const S=w.altKey||w.ctrlKey||w.metaKey;if(w.key==="Tab"&&!S){const T=document.activeElement,N=w.shiftKey;if(w.target===v&&N){d.current?.focus();return}const P=h({tabbingDirection:N?"backwards":"forwards"}),A=P.findIndex(M=>M===T);jc(P.slice(A+1))?w.preventDefault():N?d.current?.focus():u.current?.focus()}};return v.addEventListener("keydown",b),()=>v.removeEventListener("keydown",b)}},[c,h]),a(hS,{ref:l,role:"region","aria-label":i.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&a(Mc,{ref:d,onFocusFromOutsideViewport:()=>{jc(h({tabbingDirection:"forwards"}))}}),a(Dc.Slot,{scope:n,children:a(se.ol,{tabIndex:-1,...o,ref:m})}),g&&a(Mc,{ref:u,onFocusFromOutsideViewport:()=>{jc(h({tabbingDirection:"backwards"}))}})]})});lf.displayName=cf;var df="ToastFocusProxy",Mc=F((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...i}=e,o=pa(df,n);return a(ua,{tabIndex:0,...i,ref:t,style:{position:"fixed"},onFocus:s=>{const c=s.relatedTarget;o.viewport?.contains(c)||r()}})});Mc.displayName=df;var Pi="Toast",TT="toast.swipeStart",NT="toast.swipeMove",kT="toast.swipeCancel",xT="toast.swipeEnd",uf=F((e,t)=>{const{forceMount:n,open:r,defaultOpen:i,onOpenChange:o,...s}=e,[c,l]=wt({prop:r,defaultProp:i??!0,onChange:o,caller:Pi});return a(rt,{present:n||c,children:a(AT,{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)})})})});uf.displayName=Pi;var[PT,ET]=af(Pi,{onClose(){}}),AT=F((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,...g}=e,h=pa(Pi,n),[v,b]=I(null),w=we(t,L=>b(L)),S=B(null),T=B(null),N=i||h.duration,P=B(0),A=B(N),M=B(0),{onToastAdd:U,onToastRemove:x}=h,G=lt(()=>{v?.contains(document.activeElement)&&h.viewport?.focus(),s()}),E=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=()=>{E(A.current),d?.()},H=()=>{const k=new Date().getTime()-P.current;A.current=A.current-k,window.clearTimeout(M.current),l?.()};return L.addEventListener(Lc,H),L.addEventListener($c,J),()=>{L.removeEventListener(Lc,H),L.removeEventListener($c,J)}}},[h.viewport,N,l,d,E]),K(()=>{o&&!h.isClosePausedRef.current&&E(N)},[o,N,h.isClosePausedRef,E]),K(()=>(U(),()=>x()),[U,x]);const $=xe(()=>v?gf(v):null,[v]);return h.viewport?a(te,{children:[$&&a(IT,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite",children:$}),a(PT,{scope:n,onClose:G,children:en(a(Dc.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,...g,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,k=!!T.current,R=["left","right"].includes(h.swipeDirection),j=["left","up"].includes(h.swipeDirection)?Math.min:Math.max,V=R?j(0,J):0,ge=R?0:j(0,H),le=L.pointerType==="touch"?10:2,ce={x:V,y:ge},be={originalEvent:L,delta:ce};k?(T.current=ce,ma(NT,p,be,{discrete:!1})):vf(ce,h.swipeDirection,le)?(T.current=ce,ma(TT,u,be,{discrete:!1}),L.target.setPointerCapture(L.pointerId)):(Math.abs(J)>le||Math.abs(H)>le)&&(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 k=L.currentTarget,R={originalEvent:L,delta:J};vf(J,h.swipeDirection,h.swipeThreshold)?ma(xT,f,R,{discrete:!0}):ma(kT,m,R,{discrete:!0}),k.addEventListener("click",j=>j.preventDefault(),{once:!0})}})})})}),h.viewport)})]}):null}),IT=e=>{const{__scopeToast:t,children:n,...r}=e,i=pa(Pi,t),[o,s]=I(!1),[c,l]=I(!1);return MT(()=>s(!0)),K(()=>{const d=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(d)},[]),c?null:a(qn,{asChild:!0,children:a(ua,{...r,children:o&&a(te,{children:[i.label," ",n]})})})},RT="ToastTitle",DT=F((e,t)=>{const{__scopeToast:n,...r}=e;return a(se.div,{...r,ref:t})});DT.displayName=RT;var LT="ToastDescription",pf=F((e,t)=>{const{__scopeToast:n,...r}=e;return a(se.div,{...r,ref:t})});pf.displayName=LT;var mf="ToastAction",$T=F((e,t)=>{const{altText:n,...r}=e;return n.trim()?a(hf,{altText:n,asChild:!0,children:a(Oc,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${mf}\`. Expected non-empty \`string\`.`),null)});$T.displayName=mf;var ff="ToastClose",Oc=F((e,t)=>{const{__scopeToast:n,...r}=e,i=ET(ff,n);return a(hf,{asChild:!0,children:a(se.button,{type:"button",...r,ref:t,onClick:z(e.onClick,i.onClose)})})});Oc.displayName=ff;var hf=F((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 gf(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),OT(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(...gf(n))}}),t}function ma(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?uc(i,o):i.dispatchEvent(o)}var vf=(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 MT(e=()=>{}){const t=lt(e);Ve(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function OT(e){return e.nodeType===e.ELEMENT_NODE}function jT(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 jc(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var FT=sf,BT=lf,UT=uf,GT=pf,HT=Oc,Ei=Ec([]),KT=1;function qT(e,t="success",n=8e3){if(!e)return;const r=KT++;Ei.value=[...Ei.value,{id:r,message:e,variant:t,durationMs:n}]}function VT(e){Ei.value=Ei.value.filter(t=>t.id!==e)}function WT(){const e=Ei.value;return a(FT,{duration:8e3,swipeDirection:"right",children:[e.map(t=>a(UT,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||VT(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[a(GT,{className:"toast-message",children:t.message}),a(HT,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),a(BT,{className:"toast-viewport"})]})}function zT(e){Ue(a(WT,{}),e)}function fa(e,t,n){const r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=String(n)),r}function Ie(e){return document.getElementById(e)}function Fc(e){return document.getElementById(e)}function Bc(e){return document.getElementById(e)}function yf(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function JT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function YT(e,t){const n=t.trim();if(!n)return yf(e);const r=yf(e);try{const i=new RegExp(`(${JT(n)})`,"ig");return r.replace(i,'<mark class="match">$1</mark>')}catch{return r}}async function Ai(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 XT=new Set(["BUTTON","A","SELECT"]),QT=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function ZT(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function eN(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function tN(e){return e?XT.has(e.tagName)?!0:e instanceof HTMLInputElement&&QT.has(e.type):!1}function nN(e){return e.metaKey||e.ctrlKey}function Dr(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(!ZT(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}tN(n)||eN(n)&&!nN(e)||(e.preventDefault(),t.onSubmit())}}var Jn=["feed","projects","sharing","devices","health","advanced"],bf=["sync","coordinator-admin"],Uc="codemem-tab",_f="codemem-advanced-section",wf="codemem-feed-filter",Sf="codemem-feed-scope",rN="codemem-sync-diagnostics",Cf="codemem-sync-pairing",Tf="codemem-sync-redact",Nf=["all","observations","summaries"],kf=["all","mine","theirs"],_={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,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 iN(e){return[...Jn]}function Ii(e,t){return e==="sync"||e==="coordinator-admin"?"advanced":Jn.includes(e)?e:"feed"}function Gc(e=window.location.hash){const t=e.replace(/^#/,"").split("/")[0];return bf.includes(t)?"advanced":Jn.includes(t)?t:null}function Hc(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 oN(){const e=Gc();if(e)return Ii(e,_.lastCoordinatorAdminStatus);const t=localStorage.getItem(Uc);return t&&(Jn.includes(t)||bf.includes(t))?Ii(t,_.lastCoordinatorAdminStatus):"feed"}function aN(){const e=Hc();if(e)return e;const t=localStorage.getItem(Uc);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(_f)==="teams"?"teams":"sync"}function Kc(e,t=!1){_.advancedSection=e,localStorage.setItem(_f,e),t&&(window.location.hash=`advanced/${e}`)}function xf(e,t={}){const n=Ii(e,_.lastCoordinatorAdminStatus);_.activeTab=n,localStorage.setItem(Uc,n);const r=Gc();t.canonicalHash?window.location.hash=n:r!==n&&(window.location.hash=n==="advanced"?`advanced/${_.advancedSection}`:n)}function sN(){const e=localStorage.getItem(wf)||"all";return Nf.includes(e)?e:"all"}function cN(){const e=localStorage.getItem(Sf)||"all";return kf.includes(e)?e:"all"}function lN(e){_.feedTypeFilter=Nf.includes(e)?e:"all",localStorage.setItem(wf,_.feedTypeFilter)}function Pf(e){_.feedScopeFilter=kf.includes(e)?e:"all",localStorage.setItem(Sf,_.feedScopeFilter)}function dN(){return localStorage.getItem(rN)==="1"}function uN(e){_.syncPairingOpen=e;try{localStorage.setItem(Cf,e?"1":"0")}catch{}}function Ri(){return localStorage.getItem(Tf)!=="0"}function pN(e){localStorage.setItem(Tf,e?"1":"0")}function mN(){_.activeTab=oN(),_.advancedSection=aN(),_.feedTypeFilter=sN(),_.feedScopeFilter=cN(),_.syncDiagnosticsOpen=dN();try{_.syncPairingOpen=localStorage.getItem(Cf)==="1"}catch{_.syncPairingOpen=!1}}var qc=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],Ef="codemem-theme";function Af(e){const t=qc.find(r=>r.id===e);if(t)return t;const n=e.startsWith("dark")?"dark":"light";return qc.find(r=>r.id===n)||qc[0]}function Vc(){const e=localStorage.getItem(Ef);return e?Af(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function If(e){const t=Af(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(Ef,t.id)}function fN(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(Vc()==="dark"?"dark":"light"),e.addEventListener("click",()=>{const n=Vc()==="dark"?"light":"dark";If(n),t(n)})}var hN=Un(void 0);function Di(e){const t=vn(hN);return e||t||"ltr"}var Wc="rovingFocusGroup.onEntryFocus",gN={bubbles:!1,cancelable:!0},Li="RovingFocusGroup",[zc,Rf,vN]=da(Li),[yN,Lr]=st(Li,[vN]),[bN,_N]=yN(Li),Df=F((e,t)=>a(zc.Provider,{scope:e.__scopeRovingFocusGroup,children:a(zc.Slot,{scope:e.__scopeRovingFocusGroup,children:a(wN,{...e,ref:t})})}));Df.displayName=Li;var wN=F((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=B(null),f=we(t,m),g=Di(o),[h,v]=wt({prop:s,defaultProp:c??null,onChange:l,caller:Li}),[b,w]=I(!1),S=lt(d),T=Rf(n),N=B(!1),[P,A]=I(0);return K(()=>{const M=m.current;if(M)return M.addEventListener(Wc,S),()=>M.removeEventListener(Wc,S)},[S]),a(bN,{scope:n,orientation:r,dir:g,loop:i,currentTabStopId:h,onItemFocus:re(M=>v(M),[v]),onItemShiftTab:re(()=>w(!0),[]),onFocusableItemAdd:re(()=>A(M=>M+1),[]),onFocusableItemRemove:re(()=>A(M=>M-1),[]),children:a(se.div,{tabIndex:b||P===0?-1:0,"data-orientation":r,...p,ref:f,style:{outline:"none",...e.style},onMouseDown:z(e.onMouseDown,()=>{N.current=!0}),onFocus:z(e.onFocus,M=>{const U=!N.current;if(M.target===M.currentTarget&&U&&!b){const x=new CustomEvent(Wc,gN);if(M.currentTarget.dispatchEvent(x),!x.defaultPrevented){const G=T().filter(E=>E.focusable);Mf([G.find(E=>E.active),G.find(E=>E.id===h),...G].filter(Boolean).map(E=>E.ref.current),u)}}N.current=!1}),onBlur:z(e.onBlur,()=>w(!1))})})}),Lf="RovingFocusGroupItem",$f=F((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:o,children:s,...c}=e,l=ct(),d=o||l,u=_N(Lf,n),p=u.currentTabStopId===d,m=Rf(n),{onFocusableItemAdd:f,onFocusableItemRemove:g,currentTabStopId:h}=u;return K(()=>{if(r)return f(),()=>g()},[r,f,g]),a(zc.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,v=>{r?u.onItemFocus(d):v.preventDefault()}),onFocus:z(e.onFocus,()=>u.onItemFocus(d)),onKeyDown:z(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){u.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const b=TN(v,u.orientation,u.dir);if(b!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let w=m().filter(S=>S.focusable).map(S=>S.ref.current);if(b==="last")w.reverse();else if(b==="prev"||b==="next"){b==="prev"&&w.reverse();const S=w.indexOf(v.currentTarget);w=u.loop?NN(w,S+1):w.slice(S+1)}setTimeout(()=>Mf(w))}}),children:typeof s=="function"?s({isCurrentTabStop:p,hasTabStop:h!=null}):s})})});$f.displayName=Lf;var SN={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function CN(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function TN(e,t,n){const r=CN(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return SN[r]}function Mf(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function NN(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Jc=Df,Yc=$f,ha="Tabs",[kN,BO]=st(ha,[Lr]),Of=Lr(),[xN,Xc]=kN(ha),jf=F((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:i,defaultValue:o,orientation:s="horizontal",dir:c,activationMode:l="automatic",...d}=e,u=Di(c),[p,m]=wt({prop:r,onChange:i,defaultProp:o??"",caller:ha});return a(xN,{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})})});jf.displayName=ha;var Ff="TabsList",Bf=F((e,t)=>{const{__scopeTabs:n,loop:r=!0,...i}=e,o=Xc(Ff,n),s=Of(n);return a(Jc,{asChild:!0,...s,orientation:o.orientation,dir:o.dir,loop:r,children:a(se.div,{role:"tablist","aria-orientation":o.orientation,...i,ref:t})})});Bf.displayName=Ff;var Uf="TabsTrigger",Gf=F((e,t)=>{const{__scopeTabs:n,value:r,disabled:i=!1,...o}=e,s=Xc(Uf,n),c=Of(n),l=qf(s.baseId,r),d=Vf(s.baseId,r),u=r===s.value;return a(Yc,{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)})})})});Gf.displayName=Uf;var Hf="TabsContent",Kf=F((e,t)=>{const{__scopeTabs:n,value:r,forceMount:i,children:o,...s}=e,c=Xc(Hf,n),l=qf(c.baseId,r),d=Vf(c.baseId,r),u=r===c.value,p=B(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})})});Kf.displayName=Hf;function qf(e,t){return`${e}-trigger-${t}`}function Vf(e,t){return`${e}-content-${t}`}var PN=jf,EN=Bf,AN=Gf,IN=Kf;function Wf({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:o,value:s}){return a(PN,{onValueChange:r,value:s,children:[a(EN,{"aria-label":e,className:n,children:i.map(c=>a(AN,{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(IN,{className:t,forceMount:n?!0:void 0,value:r,children:e})}function Se(e){return a("input",{...e})}function RN(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 DN="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 LN(e){const{summary:t,runDevice:n}=e,r=Array.isArray(_.lastCoordinatorAdminDevices)?_.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=RN(i,String(_.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 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:f=>{f.preventDefault(),!m&&n(s,l,c,"rename")}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Se,{class:"peer-scope-input",disabled:t.readiness!=="ready"||d,onInput:f=>{O.deviceRenameDrafts.set(s,String(f.currentTarget.value||""))},type:"text",value:u}))),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:m,type:"submit"},d&&O.deviceActionPendingKind==="rename"?"Renaming…":"Rename"),p?y("button",{class:"settings-button danger",disabled:m,onClick:()=>n(s,l,c,"disable"),type:"button"},d&&O.deviceActionPendingKind==="disable"?"Disabling…":"Disable"):y("button",{class:"settings-button",disabled:m,onClick:()=>n(s,l,c,"enable"),type:"button"},d&&O.deviceActionPendingKind==="enable"?"Enabling…":"Enable"),y("button",{class:"settings-button danger",disabled:m,onClick:()=>n(s,l,c,"remove"),type:"button"},d&&O.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 ga="Collapsible",[$N,UO]=st(ga),[MN,Qc]=$N(ga),zf=F((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:ga});return a(MN,{scope:n,disabled:o,contentId:ct(),open:l,onOpenToggle:re(()=>d(u=>!u),[d]),children:a(se.div,{"data-state":el(l),"data-disabled":o?"":void 0,...c,ref:t})})});zf.displayName=ga;var Jf="CollapsibleTrigger",Yf=F((e,t)=>{const{__scopeCollapsible:n,...r}=e,i=Qc(Jf,n);return a(se.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":el(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...r,ref:t,onClick:z(e.onClick,i.onOpenToggle)})});Yf.displayName=Jf;var Zc="CollapsibleContent",Xf=F((e,t)=>{const{forceMount:n,...r}=e,i=Qc(Zc,e.__scopeCollapsible);return a(rt,{present:n||i.open,children:({present:o})=>a(ON,{...r,ref:t,present:o})})});Xf.displayName=Zc;var ON=F((e,t)=>{const{__scopeCollapsible:n,present:r,children:i,...o}=e,s=Qc(Zc,n),[c,l]=I(r),d=B(null),u=we(t,d),p=B(0),m=p.current,f=B(0),g=f.current,h=s.open||c,v=B(h),b=B(void 0);return K(()=>{const w=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(w)},[]),Ve(()=>{const w=d.current;if(w){b.current=b.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,v.current||(w.style.transitionDuration=b.current.transitionDuration,w.style.animationName=b.current.animationName),l(r)}},[s.open,r]),a(se.div,{"data-state":el(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":g?`${g}px`:void 0,...e.style},children:h&&i})});function el(e){return e?"open":"closed"}var va=zf,Qf=Yf,ya=Xf,jN=["top","right","bottom","left"],_n=Math.min,vt=Math.max,ba=Math.round,_a=Math.floor,Ut=e=>({x:e,y:e}),FN={left:"right",right:"left",bottom:"top",top:"bottom"};function tl(e,t,n){return vt(e,_n(t,n))}function on(e,t){return typeof e=="function"?e(t):e}function an(e){return e.split("-")[0]}function $r(e){return e.split("-")[1]}function nl(e){return e==="x"?"y":"x"}function rl(e){return e==="y"?"height":"width"}function Gt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function il(e){return nl(Gt(e))}function BN(e,t,n){n===void 0&&(n=!1);const r=$r(e),i=il(e),o=rl(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(s=wa(s)),[s,wa(s)]}function UN(e){const t=wa(e);return[ol(e),t,ol(t)]}function ol(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}var Zf=["left","right"],eh=["right","left"],GN=["top","bottom"],HN=["bottom","top"];function KN(e,t,n){switch(e){case"top":case"bottom":return n?t?eh:Zf:t?Zf:eh;case"left":case"right":return t?GN:HN;default:return[]}}function qN(e,t,n,r){const i=$r(e);let o=KN(an(e),n==="start",r);return i&&(o=o.map(s=>s+"-"+i),t&&(o=o.concat(o.map(ol)))),o}function wa(e){const t=an(e);return FN[t]+e.slice(t.length)}function VN(e){return{top:0,right:0,bottom:0,left:0,...e}}function th(e){return typeof e!="number"?VN(e):{top:e,right:e,bottom:e,left:e}}function Sa(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 nh(e,t,n){let{reference:r,floating:i}=e;const o=Gt(t),s=il(t),c=rl(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($r(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 WN(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),g=th(f),h=c[m?p==="floating"?"reference":"floating":p],v=Sa(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})),b=p==="floating"?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,w=await(o.getOffsetParent==null?void 0:o.getOffsetParent(c.floating)),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=Sa(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:b,offsetParent:w,strategy:l}):b);return{top:(v.top-T.top+g.top)/S.y,bottom:(T.bottom-v.bottom+g.bottom)/S.y,left:(v.left-T.left+g.left)/S.x,right:(T.right-v.right+g.right)/S.x}}var zN=50,JN=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:WN},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}=nh(d,r,l),m=r,f=0;const g={};for(let h=0;h<o.length;h++){const v=o[h];if(!v)continue;const{name:b,fn:w}=v,{x:S,y:T,data:N,reset:P}=await w({x:u,y:p,initialPlacement:r,placement:m,strategy:i,middlewareData:g,rects:d,platform:c,elements:{reference:e,floating:t}});u=S??u,p=T??p,g[b]={...g[b],...N},P&&f<zN&&(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}=nh(d,m,l)),h=-1)}return{x:u,y:p,placement:m,strategy:i,middlewareData:g}},YN=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=th(u),m={x:n,y:r},f=il(i),g=rl(f),h=await s.getDimensions(d),v=f==="y",b=v?"top":"left",w=v?"bottom":"right",S=v?"clientHeight":"clientWidth",T=o.reference[g]+o.reference[f]-m[f]-o.floating[g],N=m[f]-o.reference[f],P=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=P?P[S]:0;(!A||!await(s.isElement==null?void 0:s.isElement(P)))&&(A=c.floating[S]||o.floating[g]);const M=T/2-N/2,U=A/2-h[g]/2-1,x=_n(p[b],U),G=_n(p[w],U),E=x,$=A-h[g]-G,L=A/2-h[g]/2+M,J=tl(E,L,$),H=!l.arrow&&$r(i)!=null&&L!==J&&o.reference[g]/2-(L<E?x:G)-h[g]/2<0,k=H?L<E?L-E:L-$:0;return{[f]:m[f]+k,data:{[f]:J,centerOffset:L-J-k,...H&&{alignmentOffset:k}},reset:H}}}),XN=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:g="none",flipAlignment:h=!0,...v}=on(e,t);if((n=o.arrow)!=null&&n.alignmentOffset)return{};const b=an(i),w=Gt(c),S=an(c)===c,T=await(l.isRTL==null?void 0:l.isRTL(d.floating)),N=m||(S||!h?[wa(c)]:UN(c)),P=g!=="none";!m&&P&&N.push(...qN(c,h,g,T));const A=[c,...N],M=await l.detectOverflow(t,v),U=[];let x=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&U.push(M[b]),p){const L=BN(i,s,T);U.push(M[L[0]],M[L[1]])}if(x=[...x,{placement:i,overflows:U}],!U.every(L=>L<=0)){var G,E;const L=(((G=o.flip)==null?void 0:G.index)||0)+1,J=A[L];if(J&&(!(p==="alignment"&&w!==Gt(J))||x.every(k=>Gt(k.placement)===w?k.overflows[0]>0:!0)))return{data:{index:L,overflows:x},reset:{placement:J}};let H=(E=x.filter(k=>k.overflows[0]<=0).sort((k,R)=>k.overflows[1]-R.overflows[1])[0])==null?void 0:E.placement;if(!H)switch(f){case"bestFit":{var $;const k=($=x.filter(R=>{if(P){const j=Gt(R.placement);return j===w||j==="y"}return!0}).map(R=>[R.placement,R.overflows.filter(j=>j>0).reduce((j,V)=>j+V,0)]).sort((R,j)=>R[1]-j[1])[0])==null?void 0:$[0];k&&(H=k);break}case"initialPlacement":H=c;break}if(i!==H)return{reset:{placement:H}}}return{}}}};function rh(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 jN.some(t=>e[t]>=0)}var QN=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=rh(await r.detectOverflow(t,{...o,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:ih(s)}}}case"escaped":{const s=rh(await r.detectOverflow(t,{...o,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:ih(s)}}}default:return{}}}}},oh=new Set(["left","top"]);async function ZN(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=$r(n),l=Gt(n)==="y",d=oh.has(s)?-1:1,u=o&&l?-1:1,p=on(t,e);let{mainAxis:m,crossAxis:f,alignmentAxis:g}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return c&&typeof g=="number"&&(f=c==="end"?g*-1:g),l?{x:f*u,y:m*d}:{x:m*d,y:f*u}}var ek=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 ZN(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}}}}},tk=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:s=!0,crossAxis:c=!1,limiter:l={fn:b=>{let{x:w,y:S}=b;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=nl(m);let g=u[f],h=u[m];if(s){const b=f==="y"?"top":"left",w=f==="y"?"bottom":"right",S=g+p[b],T=g-p[w];g=tl(S,g,T)}if(c){const b=m==="y"?"top":"left",w=m==="y"?"bottom":"right",S=h+p[b],T=h-p[w];h=tl(S,h,T)}const v=l.fn({...t,[f]:g,[m]:h});return{...v,data:{x:v.x-n,y:v.y-r,enabled:{[f]:s,[m]:c}}}}}},nk=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=nl(p);let f=u[m],g=u[p];const h=on(c,t),v=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]+v.mainAxis,N=o.reference[m]+o.reference[S]-v.mainAxis;f<T?f=T:f>N&&(f=N)}if(d){var b,w;const S=m==="y"?"width":"height",T=oh.has(an(i)),N=o.reference[p]-o.floating[S]+(T&&((b=s.offset)==null?void 0:b[p])||0)+(T?0:v.crossAxis),P=o.reference[p]+o.reference[S]+(T?0:((w=s.offset)==null?void 0:w[p])||0)-(T?v.crossAxis:0);g<N?g=N:g>P&&(g=P)}return{[m]:f,[p]:g}}}},rk=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=$r(i),f=Gt(i)==="y",{width:g,height:h}=o.floating;let v,b;p==="top"||p==="bottom"?(v=p,b=m===(await(s.isRTL==null?void 0:s.isRTL(c.floating))?"start":"end")?"left":"right"):(b=p,v=m==="end"?"top":"bottom");const w=h-u.top-u.bottom,S=g-u.left-u.right,T=_n(h-u[v],w),N=_n(g-u[b],S),P=!t.middlewareData.shift;let A=T,M=N;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(A=w),P&&!m){const x=vt(u.left,0),G=vt(u.right,0),E=vt(u.top,0),$=vt(u.bottom,0);f?M=g-2*(x!==0||G!==0?x+G:vt(u.left,u.right)):A=h-2*(E!==0||$!==0?E+$:vt(u.top,u.bottom))}await l({...t,availableWidth:M,availableHeight:A});const U=await s.getDimensions(c.floating);return g!==U.width||h!==U.height?{reset:{rects:!0}}:{}}}};function Ca(){return typeof window<"u"}function Mr(e){return ah(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=(ah(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function ah(e){return Ca()?e instanceof Node||e instanceof yt(e).Node:!1}function Pt(e){return Ca()?e instanceof Element||e instanceof yt(e).Element:!1}function sn(e){return Ca()?e instanceof HTMLElement||e instanceof yt(e).HTMLElement:!1}function sh(e){return!Ca()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof yt(e).ShadowRoot}function $i(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Et(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function ik(e){return/^(table|td|th)$/.test(Mr(e))}function Ta(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}var ok=/transform|translate|scale|rotate|perspective|filter/,ak=/paint|layout|strict|content/,Xn=e=>!!e&&e!=="none",al;function sl(e){const t=Pt(e)?Et(e):e;return Xn(t.transform)||Xn(t.translate)||Xn(t.scale)||Xn(t.rotate)||Xn(t.perspective)||!cl()&&(Xn(t.backdropFilter)||Xn(t.filter))||ok.test(t.willChange||"")||ak.test(t.contain||"")}function sk(e){let t=wn(e);for(;sn(t)&&!Or(t);){if(sl(t))return t;if(Ta(t))return null;t=wn(t)}return null}function cl(){return al==null&&(al=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),al}function Or(e){return/^(html|body|#document)$/.test(Mr(e))}function Et(e){return yt(e).getComputedStyle(e)}function Na(e){return Pt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function wn(e){if(Mr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||sh(e)&&e.host||Ht(e);return sh(t)?t.host:t}function ch(e){const t=wn(e);return Or(t)?e.ownerDocument?e.ownerDocument.body:e.body:sn(t)&&$i(t)?t:ch(t)}function Mi(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=ch(e),o=i===((r=e.ownerDocument)==null?void 0:r.body),s=yt(i);if(o){const c=ll(s);return t.concat(s,s.visualViewport||[],$i(i)?i:[],c&&n?Mi(c):[])}else return t.concat(i,Mi(i,[],n))}function ll(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function lh(e){const t=Et(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=ba(n)!==o||ba(r)!==s;return c&&(n=o,r=s),{width:n,height:r,$:c}}function dl(e){return Pt(e)?e:e.contextElement}function jr(e){const t=dl(e);if(!sn(t))return Ut(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=lh(t);let s=(o?ba(n.width):n.width)/r,c=(o?ba(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!c||!Number.isFinite(c))&&(c=1),{x:s,y:c}}var ck=Ut(0);function dh(e){const t=yt(e);return!cl()||!t.visualViewport?ck:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function lk(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==yt(e)?!1:t}function Qn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),o=dl(e);let s=Ut(1);t&&(r?Pt(r)&&(s=jr(r)):s=jr(e));const c=lk(o,n,r)?dh(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 g=m,h=ll(g);for(;h&&r&&f!==g;){const v=jr(h),b=h.getBoundingClientRect(),w=Et(h),S=b.left+(h.clientLeft+parseFloat(w.paddingLeft))*v.x,T=b.top+(h.clientTop+parseFloat(w.paddingTop))*v.y;l*=v.x,d*=v.y,u*=v.x,p*=v.y,l+=S,d+=T,g=yt(h),h=ll(g)}}return Sa({width:u,height:p,x:l,y:d})}function ka(e,t){const n=Na(e).scrollLeft;return t?t.left+n:Qn(Ht(e)).left+n}function uh(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ka(e,n),y:n.top+t.scrollTop}}function dk(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o=i==="fixed",s=Ht(r),c=t?Ta(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)&&((Mr(r)!=="body"||$i(s))&&(l=Na(r)),p)){const f=Qn(r);d=jr(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const m=s&&!p&&!o?uh(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 uk(e){return Array.from(e.getClientRects())}function pk(e){const t=Ht(e),n=Na(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 Et(r).direction==="rtl"&&(s+=vt(t.clientWidth,r.clientWidth)-i),{width:i,height:o,x:s,y:c}}var ph=25;function mk(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=cl();(!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,g=Math.abs(r.clientWidth-p.clientWidth-f);g<=ph&&(o-=g)}else d<=ph&&(o+=d);return{width:o,height:s,x:c,y:l}}function fk(e,t){const n=Qn(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=sn(e)?jr(e):Ut(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=mk(e,n);else if(t==="document")r=pk(Ht(e));else if(Pt(t))r=fk(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 Sa(r)}function fh(e,t){const n=wn(e);return n===t||!Pt(n)||Or(n)?!1:Et(n).position==="fixed"||fh(n,t)}function hk(e,t){const n=t.get(e);if(n)return n;let r=Mi(e,[],!1).filter(c=>Pt(c)&&Mr(c)!=="body"),i=null;const o=Et(e).position==="fixed";let s=o?wn(e):e;for(;Pt(s)&&!Or(s);){const c=Et(s),l=sl(s);!l&&c.position==="fixed"&&(i=null),(o?!l&&!i:!l&&c.position==="static"&&i&&(i.position==="absolute"||i.position==="fixed")||$i(s)&&!l&&fh(e,s))?r=r.filter(d=>d!==s):i=c,s=wn(s)}return t.set(e,r),r}function gk(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?Ta(t)?[]:hk(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 m=mh(t,o[p],i);c=vt(m.top,c),l=_n(m.right,l),d=_n(m.bottom,d),u=vt(m.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function vk(e){const{width:t,height:n}=lh(e);return{width:t,height:n}}function yk(e,t,n){const r=sn(t),i=Ht(t),o=n==="fixed",s=Qn(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((Mr(t)!=="body"||$i(i))&&(c=Na(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?uh(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 ul(e){return Et(e).position==="static"}function hh(e,t){if(!sn(e)||Et(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Ht(e)===n&&(n=n.ownerDocument.body),n}function gh(e,t){const n=yt(e);if(Ta(e))return n;if(!sn(e)){let i=wn(e);for(;i&&!Or(i);){if(Pt(i)&&!ul(i))return i;i=wn(i)}return n}let r=hh(e,t);for(;r&&ik(r)&&ul(r);)r=hh(r,t);return r&&Or(r)&&ul(r)&&!sl(r)?n:r||sk(e)||n}var bk=async function(e){const t=this.getOffsetParent||gh,n=this.getDimensions,r=await n(e.floating);return{reference:yk(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function _k(e){return Et(e).direction==="rtl"}var wk={convertOffsetParentRelativeRectToViewportRelativeRect:dk,getDocumentElement:Ht,getClippingRect:gk,getOffsetParent:gh,getElementRects:bk,getClientRects:uk,getDimensions:vk,getScale:jr,isElement:Pt,isRTL:_k};function vh(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Sk(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 g=_a(p),h=_a(i.clientWidth-(u+m)),v=_a(i.clientHeight-(p+f)),b=_a(u),w={rootMargin:-g+"px "+-h+"px "+-v+"px "+-b+"px",threshold:vt(0,_n(1,l))||1};let S=!0;function T(N){const P=N[0].intersectionRatio;if(P!==l){if(!S)return s();P?s(!1,P):r=setTimeout(()=>{s(!1,1e-7)},1e3)}P===1&&!vh(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 Ck(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=dl(e),u=i||o?[...d?Mi(d):[],...t?Mi(t):[]]:[];u.forEach(b=>{i&&b.addEventListener("scroll",n,{passive:!0}),o&&b.addEventListener("resize",n)});const p=d&&c?Sk(d,n):null;let m=-1,f=null;s&&(f=new ResizeObserver(b=>{let[w]=b;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 g,h=l?Qn(e):null;l&&v();function v(){const b=Qn(e);h&&!vh(h,b)&&n(),h=b,g=requestAnimationFrame(v)}return n(),()=>{var b;u.forEach(w=>{i&&w.removeEventListener("scroll",n),o&&w.removeEventListener("resize",n)}),p?.(),(b=f)==null||b.disconnect(),f=null,l&&cancelAnimationFrame(g)}}var Tk=ek,Nk=tk,kk=XN,xk=rk,Pk=QN,yh=YN,Ek=nk,Ak=(e,t,n)=>{const r=new Map,i={platform:wk,...n},o={...i.platform,_c:r};return JN(e,t,{...i,platform:o})},xa=typeof document<"u"?gt:function(){};function Pa(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(!Pa(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)&&!Pa(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function bh(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function _h(e,t){const n=bh(e);return Math.round(t*n)/n}function pl(e){const t=B(e);return xa(()=>{t.current=e}),t}function Ik(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);Pa(m,r)||f(r);const[g,h]=I(null),[v,b]=I(null),w=re(R=>{R!==P.current&&(P.current=R,h(R))},[]),S=re(R=>{R!==A.current&&(A.current=R,b(R))},[]),T=o||g,N=s||v,P=B(null),A=B(null),M=B(u),U=l!=null,x=pl(l),G=pl(i),E=pl(d),$=re(()=>{if(!P.current||!A.current)return;const R={placement:t,strategy:n,middleware:m};G.current&&(R.platform=G.current),Ak(P.current,A.current,R).then(j=>{const V={...j,isPositioned:E.current!==!1};L.current&&!Pa(M.current,V)&&(M.current=V,jo(()=>{p(V)}))})},[m,t,n,G,E]);xa(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,p(R=>({...R,isPositioned:!1})))},[d]);const L=B(!1);xa(()=>(L.current=!0,()=>{L.current=!1}),[]),xa(()=>{if(T&&(P.current=T),N&&(A.current=N),T&&N){if(x.current)return x.current(T,N,$);$()}},[T,N,$,x,U]);const J=xe(()=>({reference:P,floating:A,setReference:w,setFloating:S}),[w,S]),H=xe(()=>({reference:T,floating:N}),[T,N]),k=xe(()=>{const R={position:n,left:0,top:0};if(!H.floating)return R;const j=_h(H.floating,u.x),V=_h(H.floating,u.y);return c?{...R,transform:"translate("+j+"px, "+V+"px)",...bh(H.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:j,top:V}},[n,c,H.floating,u.x,u.y]);return xe(()=>({...u,update:$,refs:J,elements:H,floatingStyles:k}),[u,$,J,H,k])}var Rk=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?yh({element:r.current,padding:i}).fn(n):{}:r?yh({element:r,padding:i}).fn(n):{}}}},Dk=(e,t)=>{const n=Tk(e);return{name:n.name,fn:n.fn,options:[e,t]}},Lk=(e,t)=>{const n=Nk(e);return{name:n.name,fn:n.fn,options:[e,t]}},$k=(e,t)=>({fn:Ek(e).fn,options:[e,t]}),Mk=(e,t)=>{const n=kk(e);return{name:n.name,fn:n.fn,options:[e,t]}},Ok=(e,t)=>{const n=xk(e);return{name:n.name,fn:n.fn,options:[e,t]}},jk=(e,t)=>{const n=Pk(e);return{name:n.name,fn:n.fn,options:[e,t]}},Fk=(e,t)=>{const n=Rk(e);return{name:n.name,fn:n.fn,options:[e,t]}},Bk="Arrow",wh=F((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"})})});wh.displayName=Bk;var Uk=wh;function ml(e){const[t,n]=I(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 fl="Popper",[Sh,Sn]=st(fl),[Gk,Ch]=Sh(fl),Th=e=>{const{__scopePopper:t,children:n}=e,[r,i]=I(null);return a(Gk,{scope:t,anchor:r,onAnchorChange:i,children:n})};Th.displayName=fl;var Nh="PopperAnchor",kh=F((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,o=Ch(Nh,n),s=B(null),c=we(t,s),l=B(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})});kh.displayName=Nh;var hl="PopperContent",[Hk,Kk]=Sh(hl),xh=F((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:g,...h}=e,v=Ch(hl,n),[b,w]=I(null),S=we(t,X=>w(X)),[T,N]=I(null),P=ml(T),A=P?.width??0,M=P?.height??0,U=r+(o!=="center"?"-"+o:""),x=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},G=Array.isArray(d)?d:[d],E=G.length>0,$={padding:x,boundary:G.filter(Vk),altBoundary:E},{refs:L,floatingStyles:J,placement:H,isPositioned:k,middlewareData:R}=Ik({strategy:"fixed",placement:U,whileElementsMounted:(...X)=>Ck(...X,{animationFrame:f==="always"}),elements:{reference:v.anchor},middleware:[Dk({mainAxis:i+M,alignmentAxis:s}),l&&Lk({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?$k():void 0,...$}),l&&Mk({...$}),Ok({...$,apply:({elements:X,rects:_e,availableWidth:he,availableHeight:Q})=>{const{width:$e,height:ue}=_e.reference,q=X.floating.style;q.setProperty("--radix-popper-available-width",`${he}px`),q.setProperty("--radix-popper-available-height",`${Q}px`),q.setProperty("--radix-popper-anchor-width",`${$e}px`),q.setProperty("--radix-popper-anchor-height",`${ue}px`)}}),T&&Fk({element:T,padding:c}),Wk({arrowWidth:A,arrowHeight:M}),m&&jk({strategy:"referenceHidden",...$})]}),[j,V]=Ah(H),ge=lt(g);Ve(()=>{k&&ge?.()},[k,ge]);const le=R.arrow?.x,ce=R.arrow?.y,be=R.arrow?.centerOffset!==0,[Y,fe]=I();return Ve(()=>{b&&fe(window.getComputedStyle(b).zIndex)},[b]),a("div",{ref:L.setFloating,"data-radix-popper-content-wrapper":"",style:{...J,transform:k?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(Hk,{scope:n,placedSide:j,onArrowChange:N,arrowX:le,arrowY:ce,shouldHideArrow:be,children:a(se.div,{"data-side":j,"data-align":V,...h,ref:S,style:{...h.style,animation:k?void 0:"none"}})})})});xh.displayName=hl;var Ph="PopperArrow",qk={top:"bottom",right:"left",bottom:"top",left:"right"},Eh=F(function(t,n){const{__scopePopper:r,...i}=t,o=Kk(Ph,r),s=qk[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(Uk,{...i,ref:n,style:{...i.style,display:"block"}})})});Eh.displayName=Ph;function Vk(e){return e!==null}var Wk=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]=Ah(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="",g="";return l==="bottom"?(f=o?u:`${p}px`,g=`${-c}px`):l==="top"?(f=o?u:`${p}px`,g=`${r.floating.height+c}px`):l==="right"?(f=`${-c}px`,g=o?u:`${m}px`):l==="left"&&(f=`${r.floating.width+c}px`,g=o?u:`${m}px`),{data:{x:f,y:g}}}});function Ah(e){const[t,n="center"]=e.split("-");return[t,n]}var Oi=Th,ji=kh,Ea=xh,Aa=Eh,Ia="Popover",[Ih,GO]=st(Ia,[Sn]),Fi=Sn(),[zk,Cn]=Ih(Ia),Rh=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!1}=e,c=Fi(t),l=B(null),[d,u]=I(!1),[p,m]=wt({prop:r,defaultProp:i??!1,onChange:o,caller:Ia});return a(Oi,{...c,children:a(zk,{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})})};Rh.displayName=Ia;var Dh="PopoverAnchor",Lh=F((e,t)=>{const{__scopePopover:n,...r}=e,i=Cn(Dh,n),o=Fi(n),{onCustomAnchorAdd:s,onCustomAnchorRemove:c}=i;return K(()=>(s(),()=>c()),[s,c]),a(ji,{...o,...r,ref:t})});Lh.displayName=Dh;var $h="PopoverTrigger",Mh=F((e,t)=>{const{__scopePopover:n,...r}=e,i=Cn($h,n),o=Fi(n),s=we(t,i.triggerRef),c=a(se.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Uh(i.open),...r,ref:s,onClick:z(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:a(ji,{asChild:!0,...o,children:c})});Mh.displayName=$h;var gl="PopoverPortal",[Jk,Yk]=Ih(gl,{forceMount:void 0}),Oh=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,o=Cn(gl,t);return a(Jk,{scope:t,forceMount:n,children:a(rt,{present:n||o.open,children:a(qn,{asChild:!0,container:i,children:r})})})};Oh.displayName=gl;var Fr="PopoverContent",jh=F((e,t)=>{const n=Yk(Fr,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,o=Cn(Fr,e.__scopePopover);return a(rt,{present:r||o.open,children:o.modal?a(Qk,{...i,ref:t}):a(Zk,{...i,ref:t})})});jh.displayName=Fr;var Xk=Hn("PopoverContent.RemoveScroll"),Qk=F((e,t)=>{const n=Cn(Fr,e.__scopePopover),r=B(null),i=we(t,r),o=B(!1);return K(()=>{const s=r.current;if(s)return Jo(s)},[]),a(_i,{as:Xk,allowPinchZoom:!0,children:a(Fh,{...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})})})}),Zk=F((e,t)=>{const n=Cn(Fr,e.__scopePopover),r=B(!1),i=B(!1);return a(Fh,{...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()}})}),Fh=F((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:s,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onInteractOutside:u,...p}=e,m=Cn(Fr,n),f=Fi(n);return Uo(),a(yi,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:o,children:a(Kn,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:a(Ea,{"data-state":Uh(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)"}})})})}),Bh="PopoverClose",ex=F((e,t)=>{const{__scopePopover:n,...r}=e,i=Cn(Bh,n);return a(se.button,{type:"button",...r,ref:t,onClick:z(e.onClick,()=>i.onOpenChange(!1))})});ex.displayName=Bh;var tx="PopoverArrow",nx=F((e,t)=>{const{__scopePopover:n,...r}=e,i=Fi(n);return a(Aa,{...i,...r,ref:t})});nx.displayName=tx;function Uh(e){return e?"open":"closed"}var Gh=Rh,rx=Lh,ix=Mh,Hh=Oh,Kh=jh;function vl(e){return e.trim()}function qh({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=B(null),g=xe(()=>{const x=new Set,G=[];for(const E of[...n,...e]){const $=vl(E);!$||x.has($)||(x.add($),G.push($))}return G.sort((E,$)=>E.localeCompare($))},[n,e]),h=vl(d),v=h.toLowerCase(),b=xe(()=>v?g.filter(x=>x.toLowerCase().includes(v)):g,[g,v]),w=h?g.some(x=>x.toLowerCase()===v):!1,S=!!h&&!w,T=b.length+(S?1:0);K(()=>{p>=T&&m(Math.max(0,T-1))},[T,p]),K(()=>{if(!c)return;const x=requestAnimationFrame(()=>f.current?.focus());return()=>cancelAnimationFrame(x)},[c]);const N=x=>{e.includes(x)?t(e.filter(G=>G!==x)):t(Array.from(new Set([...e,x])))},P=x=>{const G=vl(x);G&&(t(Array.from(new Set([...e,G]))),u(""),m(0))},A=x=>{if(x<b.length){const G=b[x];G&&N(G);return}S&&P(h)},M=x=>{if(x.key==="ArrowDown"){x.preventDefault(),m(G=>Math.min(T-1,G+1));return}if(x.key==="ArrowUp"){x.preventDefault(),m(G=>Math.max(0,G-1));return}if(x.key==="Enter"){x.preventDefault(),A(p);return}},U=x=>{t(e.filter(G=>G!==x))};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(x=>a("li",{class:"project-scope-picker-selected-chip",children:[a("span",{children:x}),o?null:a("button",{"aria-label":`Remove ${x}`,class:"project-scope-picker-selected-remove",onClick:()=>U(x),type:"button",children:"×"})]},x))}),a(Gh,{onOpenChange:x=>{l(x),x||(u(""),m(0))},open:c,children:[a(ix,{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(Hh,{children:a(Kh,{align:"start",class:"project-scope-picker-popover",sideOffset:6,children:[a("input",{"aria-label":"Search projects",class:"project-scope-picker-search",onInput:x=>{u(x.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:[b.length===0&&!S?a("div",{class:"project-scope-picker-empty-row",children:"No projects yet. Type a name to create one."}):null,b.map((x,G)=>{const E=e.includes(x);return a("button",{"aria-selected":E,class:G===p?"project-scope-picker-row project-scope-picker-row--active":"project-scope-picker-row",onClick:()=>{m(G),N(x)},onMouseEnter:()=>m(G),role:"option",type:"button",children:[a("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:E?"✓":""}),a("span",{class:"project-scope-picker-row-label",children:x})]},x)}),S?a("button",{"aria-selected":!1,class:p===b.length?"project-scope-picker-row project-scope-picker-row--create project-scope-picker-row--active":"project-scope-picker-row project-scope-picker-row--create",onClick:()=>P(h),onMouseEnter:()=>m(b.length),role:"option",type:"button",children:[a("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:"+"}),a("span",{class:"project-scope-picker-row-label",children:`Create "${h}"`})]}):null]})]})})]})]})}function yl(e){const t=B({value:e,previous:e});return xe(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Ra="Switch",[ox,HO]=st(Ra),[ax,sx]=ox(Ra),Vh=F((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),g=we(t,S=>f(S)),h=B(!1),v=m?u||!!m.closest("form"):!0,[b,w]=wt({prop:i,defaultProp:o??!1,onChange:d,caller:Ra});return a(ax,{scope:n,checked:b,disabled:c,children:[a(se.button,{type:"button",role:"switch","aria-checked":b,"aria-required":s,"data-state":Yh(b),"data-disabled":c?"":void 0,disabled:c,value:l,...p,ref:g,onClick:z(e.onClick,S=>{w(T=>!T),v&&(h.current=S.isPropagationStopped(),h.current||S.stopPropagation())})}),v&&a(Jh,{control:m,bubbles:!h.current,name:r,value:l,checked:b,required:s,disabled:c,form:u,style:{transform:"translateX(-100%)"}})]})});Vh.displayName=Ra;var Wh="SwitchThumb",zh=F((e,t)=>{const{__scopeSwitch:n,...r}=e,i=sx(Wh,n);return a(se.span,{"data-state":Yh(i.checked),"data-disabled":i.disabled?"":void 0,...r,ref:t})});zh.displayName=Wh;var cx="SwitchBubbleInput",Jh=F(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...i},o)=>{const s=B(null),c=we(s,o),l=yl(n),d=ml(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}})});Jh.displayName=cx;function Yh(e){return e?"checked":"unchecked"}var lx=Vh,dx=zh;function Br({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:o,onCheckedChange:s,thumbClassName:c}){return a(lx,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:o,onCheckedChange:s,children:a(dx,{className:c})})}function ne(e,t="success"){qT(e,t)}function Xh(e){return`${DN}:${String(e||"").trim()}`}function ux(e){try{return localStorage.getItem(Xh(e))||""}catch{return""}}function px(e,t){try{localStorage.setItem(Xh(e),t)}catch{}}function Zn(){return String(_.coordinatorAdminTargetGroup||"").trim()}function bl(e){_.coordinatorAdminTargetGroup=e,px(_.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function Ur(){return(Array.isArray(_.lastCoordinatorAdminGroups)?_.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 mx(){const e=new Map;for(const t of Ur())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 fx(){const e=Zn();return Ur().find(t=>t.group_id===e)||null}function Qh(){const e=_.lastCoordinatorAdminStatus,t=Ur(),n=String(e?.active_group||"").trim(),r=ux(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 bl(c),c}function hx(){const e=new Map,t=new Map,n=Array.isArray(_.lastCoordinatorAdminDevices)?_.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 gx(e,t){return t&&t.groupId===e?t:null}function vx(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 yx(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 bx(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function _x(e){const t=bx(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function wx(e){const t=gx(e.groupId,e.setupGuide);return{autoGrant:yx(e.preferences,t),defaultSpace:vx(e.preferences,t),spaces:_x(e.scopeManagement)}}var _l=null,Da=null,wl=null;function Sx(){return _l}function Sl(e){Da=e}function Zh(e){wl=e}function Cx(e){return wl===e}function Tx(e){return e?e.kind==="confirm"?!1:e.kind==="input"?null:{action:"cancel"}:null}function Cl(e){return!_l||!Da?!0:(console.warn(`Ignored sync ${e} dialog request because another sync dialog is already open.`),!1)}function La(e){_l=e,wl?.(e)}function Tn(e){const t=Da;Da=null,La(null),t?.(e)}function Nx(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var kx=F(function({value:t,onValueChange:n,suggestions:r,onSubmit:i,maxSuggestions:o=20,onKeyDown:s,onFocus:c,onBlur:l,className:d,...u},p){const m=B(null);Lo(p,()=>m.current,[]);const[f,g]=I(!1),[h,v]=I(-1),b=xe(()=>{const N=t.trim().toLowerCase();return(N?r.filter(P=>P.toLowerCase().includes(N)):r).slice(0,o)},[t,r,o]);K(()=>{h>=b.length&&v(b.length-1)},[b.length,h]);const w=f&&b.length>0,S=N=>{n(N),g(!1),v(-1),m.current?.focus()};return a(Gh,{open:w,onOpenChange:g,children:[a(rx,{asChild:!0,children:a("input",{...u,ref:m,className:d,value:t,onInput:N=>{n(N.currentTarget.value),g(!0),v(-1)},onFocus:N=>{c?.(N)},onBlur:N=>{window.setTimeout(()=>g(!1),120),l?.(N)},onKeyDown:N=>{if(N.key==="ArrowDown"){N.preventDefault(),g(!0),v(P=>b.length===0?-1:Math.min(P+1,b.length-1));return}if(N.key==="ArrowUp"){N.preventDefault(),f||g(!0),v(P=>Math.max(P-1,-1));return}if(N.key==="Escape"&&w){N.preventDefault(),g(!1),v(-1);return}if((N.key==="Tab"||N.key==="Enter")&&h>=0){const P=b[h];if(P){N.preventDefault(),S(P);return}}if(N.key==="Enter"&&i){N.preventDefault(),i();return}s?.(N)},role:"combobox","aria-autocomplete":"list","aria-expanded":w,"aria-controls":"autocompleteListbox","aria-activedescendant":h>=0?`autocomplete-option-${h}`:void 0})}),a(Hh,{children:a(Kh,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:N=>N.preventDefault(),onCloseAutoFocus:N=>N.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:a("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:b.map((N,P)=>{const A=P===h;return a("div",{"aria-selected":A,className:A?"autocomplete-option active":"autocomplete-option",id:`autocomplete-option-${P}`,onMouseDown:M=>{M.preventDefault(),S(N)},onMouseEnter:()=>v(P),role:"option",tabIndex:-1,children:N},N)})})})})]})}),Tl="Radio",[xx,eg]=st(Tl),[Px,Ex]=xx(Tl),tg=F((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=we(t,v=>m(v)),g=B(!1),h=p?d||!!p.closest("form"):!0;return a(Px,{scope:n,checked:i,disabled:s,children:[a(se.button,{type:"button",role:"radio","aria-checked":i,"data-state":og(i),"data-disabled":s?"":void 0,disabled:s,value:c,...u,ref:f,onClick:z(e.onClick,v=>{i||l?.(),h&&(g.current=v.isPropagationStopped(),g.current||v.stopPropagation())})}),h&&a(ig,{control:p,bubbles:!g.current,name:r,value:c,checked:i,required:o,disabled:s,form:d,style:{transform:"translateX(-100%)"}})]})});tg.displayName=Tl;var ng="RadioIndicator",rg=F((e,t)=>{const{__scopeRadio:n,forceMount:r,...i}=e,o=Ex(ng,n);return a(rt,{present:r||o.checked,children:a(se.span,{"data-state":og(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:t})})});rg.displayName=ng;var Ax="RadioBubbleInput",ig=F(({__scopeRadio:e,control:t,checked:n,bubbles:r=!0,...i},o)=>{const s=B(null),c=we(s,o),l=yl(n),d=ml(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}})});ig.displayName=Ax;function og(e){return e?"checked":"unchecked"}var Ix=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],$a="RadioGroup",[Rx,KO]=st($a,[Lr,eg]),ag=Lr(),sg=eg(),[Dx,Lx]=Rx($a),cg=F((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=ag(n),g=Di(d),[h,v]=wt({prop:o,defaultProp:i??null,onChange:p,caller:$a});return a(Dx,{scope:n,name:r,required:s,disabled:c,value:h,onValueChange:v,children:a(Jc,{asChild:!0,...f,orientation:l,dir:g,loop:u,children:a(se.div,{role:"radiogroup","aria-required":s,"aria-orientation":l,"data-disabled":c?"":void 0,dir:g,...m,ref:t})})})});cg.displayName=$a;var lg="RadioGroupItem",dg=F((e,t)=>{const{__scopeRadioGroup:n,disabled:r,...i}=e,o=Lx(lg,n),s=o.disabled||r,c=ag(n),l=sg(n),d=B(null),u=we(t,d),p=o.value===i.value,m=B(!1);return K(()=>{const f=h=>{Ix.includes(h.key)&&(m.current=!0)},g=()=>m.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",g),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",g)}},[]),a(Yc,{asChild:!0,...c,focusable:!s,active:p,children:a(tg,{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()})})})});dg.displayName=lg;var $x="RadioGroupIndicator",ug=F((e,t)=>{const{__scopeRadioGroup:n,...r}=e;return a(rg,{...sg(n),...r,ref:t})});ug.displayName=$x;var Mx=cg,Ox=dg,jx=ug;function Fx({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:o,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return a(Mx,{"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}`,g=`radio-option-label-${m}`;return a("label",{className:i,htmlFor:f,children:[a(Ox,{id:f,"aria-labelledby":g,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:a(jx,{className:r})}),a("span",{className:o,id:g,children:p.label})]},p.value)})})}function pg(e,[t,n]){return Math.min(n,Math.max(t,e))}var Bx=[" ","Enter","ArrowUp","ArrowDown"],Ux=[" ","Enter"],er="Select",[Ma,Oa,Gx]=da(er),[Gr,qO]=st(er,[Gx,Sn]),ja=Sn(),[Hx,Nn]=Gr(er),[Kx,qx]=Gr(er),mg=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:g}=e,h=ja(t),[v,b]=I(null),[w,S]=I(null),[T,N]=I(!1),P=Di(d),[A,M]=wt({prop:r,defaultProp:i??!1,onChange:o,caller:er}),[U,x]=wt({prop:s,defaultProp:c,onChange:l,caller:er}),G=B(null),E=v?g||!!v.closest("form"):!0,[$,L]=I(new Set),J=Array.from($).map(H=>H.props.value).join(";");return a(Oi,{...h,children:a(Hx,{required:f,scope:t,trigger:v,onTriggerChange:b,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:T,onValueNodeHasChildrenChange:N,contentId:ct(),value:U,onValueChange:x,open:A,onOpenChange:M,dir:P,triggerPointerDownPosRef:G,disabled:m,children:[a(Ma.Provider,{scope:t,children:a(Kx,{scope:e.__scopeSelect,onNativeOptionAdd:re(H=>{L(k=>new Set(k).add(H))},[]),onNativeOptionRemove:re(H=>{L(k=>{const R=new Set(k);return R.delete(H),R})},[]),children:n})}),E?a(Dg,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:p,value:U,onChange:H=>x(H.target.value),disabled:m,form:g,children:[U===void 0?a("option",{value:""}):null,Array.from($)]},J):null]})})};mg.displayName=er;var fg="SelectTrigger",hg=F((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...i}=e,o=ja(n),s=Nn(fg,n),c=s.disabled||r,l=we(t,s.onTriggerChange),d=Oa(n),u=B("touch"),[p,m,f]=$g(h=>{const v=d().filter(w=>!w.disabled),b=Mg(v,h,v.find(w=>w.value===s.value));b!==void 0&&s.onValueChange(b.value)}),g=h=>{c||(s.onOpenChange(!0),f()),h&&(s.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return a(ji,{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":Lg(s.value)?"":void 0,...i,ref:l,onClick:z(i.onClick,h=>{h.currentTarget.focus(),u.current!=="mouse"&&g(h)}),onPointerDown:z(i.onPointerDown,h=>{u.current=h.pointerType;const v=h.target;v.hasPointerCapture(h.pointerId)&&v.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(g(h),h.preventDefault())}),onKeyDown:z(i.onKeyDown,h=>{const v=p.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&m(h.key),!(v&&h.key===" ")&&Bx.includes(h.key)&&(g(),h.preventDefault())})})})});hg.displayName=fg;var gg="SelectValue",vg=F((e,t)=>{const{__scopeSelect:n,className:r,style:i,children:o,placeholder:s="",...c}=e,l=Nn(gg,n),{onValueNodeHasChildrenChange:d}=l,u=o!==void 0,p=we(t,l.onValueNodeChange);return Ve(()=>{d(u)},[d,u]),a(se.span,{...c,ref:p,style:{pointerEvents:"none"},children:Lg(l.value)?a(te,{children:s}):o})});vg.displayName=gg;var Vx="SelectIcon",yg=F((e,t)=>{const{__scopeSelect:n,children:r,...i}=e;return a(se.span,{"aria-hidden":!0,...i,ref:t,children:r||"▼"})});yg.displayName=Vx;var Wx="SelectPortal",bg=e=>a(qn,{asChild:!0,...e});bg.displayName=Wx;var tr="SelectContent",_g=F((e,t)=>{const n=Nn(tr,e.__scopeSelect),[r,i]=I();if(Ve(()=>{i(new DocumentFragment)},[]),!n.open){const o=r;return o?en(a(wg,{scope:e.__scopeSelect,children:a(Ma.Slot,{scope:e.__scopeSelect,children:a("div",{children:e.children})})}),o):null}return a(Sg,{...e,ref:t})});_g.displayName=tr;var At=10,[wg,kn]=Gr(tr),zx="SelectContentImpl",Jx=Hn("SelectContent.RemoveScroll"),Sg=F((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:g,hideWhenDetached:h,avoidCollisions:v,...b}=e,w=Nn(tr,n),[S,T]=I(null),[N,P]=I(null),A=we(t,X=>T(X)),[M,U]=I(null),[x,G]=I(null),E=Oa(n),[$,L]=I(!1),J=B(!1);K(()=>{if(S)return Jo(S)},[S]),Uo();const H=re(X=>{const[_e,...he]=E().map(ue=>ue.ref.current),[Q]=he.slice(-1),$e=document.activeElement;for(const ue of X)if(ue===$e||(ue?.scrollIntoView({block:"nearest"}),ue===_e&&N&&(N.scrollTop=0),ue===Q&&N&&(N.scrollTop=N.scrollHeight),ue?.focus(),document.activeElement!==$e))return},[E,N]),k=re(()=>H([M,S]),[H,M,S]);K(()=>{$&&k()},[$,k]);const{onOpenChange:R,triggerPointerDownPosRef:j}=w;K(()=>{if(S){let X={x:0,y:0};const _e=Q=>{X={x:Math.abs(Math.round(Q.pageX)-(j.current?.x??0)),y:Math.abs(Math.round(Q.pageY)-(j.current?.y??0))}},he=Q=>{X.x<=10&&X.y<=10?Q.preventDefault():S.contains(Q.target)||R(!1),document.removeEventListener("pointermove",_e),j.current=null};return j.current!==null&&(document.addEventListener("pointermove",_e),document.addEventListener("pointerup",he,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",_e),document.removeEventListener("pointerup",he,{capture:!0})}}},[S,R,j]),K(()=>{const X=()=>R(!1);return window.addEventListener("blur",X),window.addEventListener("resize",X),()=>{window.removeEventListener("blur",X),window.removeEventListener("resize",X)}},[R]);const[V,ge]=$g(X=>{const _e=E().filter(Q=>!Q.disabled),he=Mg(_e,X,_e.find(Q=>Q.ref.current===document.activeElement));he&&setTimeout(()=>he.ref.current.focus())}),le=re((X,_e,he)=>{const Q=!J.current&&!he;(w.value!==void 0&&w.value===_e||Q)&&(U(X),Q&&(J.current=!0))},[w.value]),ce=re(()=>S?.focus(),[S]),be=re((X,_e,he)=>{const Q=!J.current&&!he;(w.value!==void 0&&w.value===_e||Q)&&G(X)},[w.value]),Y=r==="popper"?Nl:Cg,fe=Y===Nl?{side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:g,hideWhenDetached:h,avoidCollisions:v}:{};return a(wg,{scope:n,content:S,viewport:N,onViewportChange:P,itemRefCallback:le,selectedItem:M,onItemLeave:ce,itemTextRefCallback:be,focusSelectedItem:k,selectedItemText:x,position:r,isPositioned:$,searchRef:V,children:a(_i,{as:Jx,allowPinchZoom:!0,children:a(yi,{asChild:!0,trapped:w.open,onMountAutoFocus:X=>{X.preventDefault()},onUnmountAutoFocus:z(i,X=>{w.trigger?.focus({preventScroll:!0}),X.preventDefault()}),children:a(Kn,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:X=>X.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:a(Y,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:X=>X.preventDefault(),...b,...fe,onPlaced:()=>L(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:z(b.onKeyDown,X=>{const _e=X.ctrlKey||X.altKey||X.metaKey;if(X.key==="Tab"&&X.preventDefault(),!_e&&X.key.length===1&&ge(X.key),["ArrowUp","ArrowDown","Home","End"].includes(X.key)){let he=E().filter(Q=>!Q.disabled).map(Q=>Q.ref.current);if(["ArrowUp","End"].includes(X.key)&&(he=he.slice().reverse()),["ArrowUp","ArrowDown"].includes(X.key)){const Q=X.target,$e=he.indexOf(Q);he=he.slice($e+1)}setTimeout(()=>H(he)),X.preventDefault()}})})})})})})});Sg.displayName=zx;var Yx="SelectItemAlignedPosition",Cg=F((e,t)=>{const{__scopeSelect:n,onPlaced:r,...i}=e,o=Nn(tr,n),s=kn(tr,n),[c,l]=I(null),[d,u]=I(null),p=we(t,P=>u(P)),m=Oa(n),f=B(!1),g=B(!0),{viewport:h,selectedItem:v,selectedItemText:b,focusSelectedItem:w}=s,S=re(()=>{if(o.trigger&&o.valueNode&&c&&d&&h&&v&&b){const P=o.trigger.getBoundingClientRect(),A=d.getBoundingClientRect(),M=o.valueNode.getBoundingClientRect(),U=b.getBoundingClientRect();if(o.dir!=="rtl"){const he=U.left-A.left,Q=M.left-he,$e=P.left-Q,ue=P.width+$e,q=Math.max(ue,A.width),oe=window.innerWidth-At,qe=pg(Q,[At,Math.max(At,oe-q)]);c.style.minWidth=ue+"px",c.style.left=qe+"px"}else{const he=A.right-U.right,Q=window.innerWidth-M.right-he,$e=window.innerWidth-P.right-Q,ue=P.width+$e,q=Math.max(ue,A.width),oe=window.innerWidth-At,qe=pg(Q,[At,Math.max(At,oe-q)]);c.style.minWidth=ue+"px",c.style.right=qe+"px"}const x=m(),G=window.innerHeight-At*2,E=h.scrollHeight,$=window.getComputedStyle(d),L=parseInt($.borderTopWidth,10),J=parseInt($.paddingTop,10),H=parseInt($.borderBottomWidth,10),k=parseInt($.paddingBottom,10),R=L+J+E+k+H,j=Math.min(v.offsetHeight*5,R),V=window.getComputedStyle(h),ge=parseInt(V.paddingTop,10),le=parseInt(V.paddingBottom,10),ce=P.top+P.height/2-At,be=G-ce,Y=v.offsetHeight/2,fe=v.offsetTop+Y,X=L+J+fe,_e=R-X;if(X<=ce){const he=x.length>0&&v===x[x.length-1].ref.current;c.style.bottom="0px";const Q=d.clientHeight-h.offsetTop-h.offsetHeight,$e=X+Math.max(be,Y+(he?le:0)+Q+H);c.style.height=$e+"px"}else{const he=x.length>0&&v===x[0].ref.current;c.style.top="0px";const Q=Math.max(ce,L+h.offsetTop+(he?ge:0)+Y)+_e;c.style.height=Q+"px",h.scrollTop=X-ce+h.offsetTop}c.style.margin=`${At}px 0`,c.style.minHeight=j+"px",c.style.maxHeight=G+"px",r?.(),requestAnimationFrame(()=>f.current=!0)}},[m,o.trigger,o.valueNode,c,d,h,v,b,o.dir,r]);Ve(()=>S(),[S]);const[T,N]=I();return Ve(()=>{d&&N(window.getComputedStyle(d).zIndex)},[d]),a(Qx,{scope:n,contentWrapper:c,shouldExpandOnScrollRef:f,onScrollButtonChange:re(P=>{P&&g.current===!0&&(S(),w?.(),g.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}})})})});Cg.displayName=Yx;var Xx="SelectPopperPosition",Nl=F((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:i=At,...o}=e,s=ja(n);return a(Ea,{...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)"}})});Nl.displayName=Xx;var[Qx,kl]=Gr(tr,{}),xl="SelectViewport",Tg=F((e,t)=>{const{__scopeSelect:n,nonce:r,...i}=e,o=kn(xl,n),s=kl(xl,n),c=we(t,o.onViewportChange),l=B(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(Ma.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 g=window.innerHeight-At*2,h=parseFloat(p.style.minHeight),v=parseFloat(p.style.height),b=Math.max(h,v);if(b<g){const w=b+f,S=Math.min(g,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})})})]})});Tg.displayName=xl;var Ng="SelectGroup",[Zx,eP]=Gr(Ng),tP=F((e,t)=>{const{__scopeSelect:n,...r}=e,i=ct();return a(Zx,{scope:n,id:i,children:a(se.div,{role:"group","aria-labelledby":i,...r,ref:t})})});tP.displayName=Ng;var kg="SelectLabel",nP=F((e,t)=>{const{__scopeSelect:n,...r}=e,i=eP(kg,n);return a(se.div,{id:i.id,...r,ref:t})});nP.displayName=kg;var Fa="SelectItem",[rP,xg]=Gr(Fa),Pg=F((e,t)=>{const{__scopeSelect:n,value:r,disabled:i=!1,textValue:o,...s}=e,c=Nn(Fa,n),l=kn(Fa,n),d=c.value===r,[u,p]=I(o??""),[m,f]=I(!1),g=we(t,w=>l.itemRefCallback?.(w,r,i)),h=ct(),v=B("touch"),b=()=>{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(rP,{scope:n,value:r,disabled:i,textId:h,isSelected:d,onItemTextChange:re(w=>{p(S=>S||(w?.textContent??"").trim())},[]),children:a(Ma.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:g,onFocus:z(s.onFocus,()=>f(!0)),onBlur:z(s.onBlur,()=>f(!1)),onClick:z(s.onClick,()=>{v.current!=="mouse"&&b()}),onPointerUp:z(s.onPointerUp,()=>{v.current==="mouse"&&b()}),onPointerDown:z(s.onPointerDown,w=>{v.current=w.pointerType}),onPointerMove:z(s.onPointerMove,w=>{v.current=w.pointerType,i?l.onItemLeave?.():v.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===" "||(Ux.includes(w.key)&&b(),w.key===" "&&w.preventDefault())})})})})});Pg.displayName=Fa;var Bi="SelectItemText",Eg=F((e,t)=>{const{__scopeSelect:n,className:r,style:i,...o}=e,s=Nn(Bi,n),c=kn(Bi,n),l=xg(Bi,n),d=qx(Bi,n),[u,p]=I(null),m=we(t,b=>p(b),l.onItemTextChange,b=>c.itemTextRefCallback?.(b,l.value,l.disabled)),f=u?.textContent,g=xe(()=>a("option",{value:l.value,disabled:l.disabled,children:f},l.value),[l.disabled,l.value,f]),{onNativeOptionAdd:h,onNativeOptionRemove:v}=d;return Ve(()=>(h(g),()=>v(g)),[h,v,g]),a(te,{children:[a(se.span,{id:l.textId,...o,ref:m}),l.isSelected&&s.valueNode&&!s.valueNodeHasChildren?en(o.children,s.valueNode):null]})});Eg.displayName=Bi;var Ag="SelectItemIndicator",Ig=F((e,t)=>{const{__scopeSelect:n,...r}=e;return xg(Ag,n).isSelected?a(se.span,{"aria-hidden":!0,...r,ref:t}):null});Ig.displayName=Ag;var Pl="SelectScrollUpButton",iP=F((e,t)=>{const n=kn(Pl,e.__scopeSelect),r=kl(Pl,e.__scopeSelect),[i,o]=I(!1),s=we(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(Rg,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});iP.displayName=Pl;var El="SelectScrollDownButton",oP=F((e,t)=>{const n=kn(El,e.__scopeSelect),r=kl(El,e.__scopeSelect),[i,o]=I(!1),s=we(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(Rg,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});oP.displayName=El;var Rg=F((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...i}=e,o=kn("SelectScrollButton",n),s=B(null),c=Oa(n),l=re(()=>{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()})})}),aP="SelectSeparator",sP=F((e,t)=>{const{__scopeSelect:n,...r}=e;return a(se.div,{"aria-hidden":!0,...r,ref:t})});sP.displayName=aP;var Al="SelectArrow",cP=F((e,t)=>{const{__scopeSelect:n,...r}=e,i=ja(n),o=Nn(Al,n),s=kn(Al,n);return o.open&&s.position==="popper"?a(Aa,{...i,...r,ref:t}):null});cP.displayName=Al;var lP="SelectBubbleInput",Dg=F(({__scopeSelect:e,value:t,...n},r)=>{const i=B(null),o=we(r,i),s=yl(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:{...of,...n.style},ref:o,defaultValue:t})});Dg.displayName=lP;function Lg(e){return e===""||e===void 0}function $g(e){const t=lt(e),n=B(""),r=B(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 Mg(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=dP(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 dP(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var uP=mg,pP=hg,mP=vg,fP=yg,hP=bg,gP=_g,vP=Tg,yP=Pg,bP=Eg,_P=Ig,Og="__codemem-empty-select__";function wP(){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 SP(){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 Il(e){return e===""?Og:e}function CP(e){return e===Og?"":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?Il(u):void 0;return a(uP,{disabled:r,onValueChange:f=>s(CP(f)),value:m,children:[a(pP,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[a(mP,{placeholder:l}),a(fP,{className:"sync-radix-select-icon","aria-hidden":"true",children:a(wP,{})})]}),a(hP,{children:a(gP,{className:n,position:"popper",children:a(vP,{className:p,children:c.map(f=>a(yP,{className:o,disabled:f.disabled,value:Il(f.value),children:[a(bP,{children:f.label}),a(_P,{className:"sync-radix-select-indicator",children:a(SP,{})})]},Il(f.value)))})})})]})}function TP({descriptionId:e,request:t}){const[n,r]=I("choice"),[i,o]=I(t.actors.find(v=>v.isLocal)?.actorId||t.actors[0]?.actorId||""),[s,c]=I("");K(()=>{r("choice");const v=t.actors.find(w=>w.isLocal)?.actorId||t.actors[0]?.actorId||"",b=t.actors.find(w=>w.actorId!==v)?.actorId||"";o(v),c(b)},[t]);const l=t.actors.find(v=>v.actorId===i)||t.actors[0],d=t.actors.filter(v=>v.actorId!==i),u=d.find(v=>v.actorId===s)||d[0],p=t.actors.map(v=>({label:a(te,{children:[v.label,v.isLocal?" (You)":""]}),value:v.actorId})),m=d.map(v=>({label:`${v.label}${v.isLocal?" (You)":""}`,value:v.actorId})),f=!!(l?.actorId&&u?.actorId),g=()=>{!l?.actorId||!u?.actorId||Tn({action:"merge",primaryActorId:l.actorId,secondaryActorId:u.actorId})},h=v=>{const b=v.target instanceof HTMLElement?v.target:null;v.defaultPrevented||v.isComposing||v.key!=="Enter"||b?.closest(".sync-dialog-radio-list")&&f&&(v.preventDefault(),g())};return n==="choice"?a("div",{className:"sync-dialog-stack",children:a("ul",{className:"sync-dialog-choice-list",children:[a("li",{children:a("button",{autoFocus:!0,className:"settings-button","data-primary-action":"true","data-sync-primary-action":"true",onClick:()=>r("merge"),type:"button",children:"These are both me"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>Tn({action:"different-people"}),type:"button",children:"These are different people"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>Tn({action:"cancel"}),type:"button",children:"Decide later"})})]})}):a("div",{className:"sync-dialog-stack",onKeyDown:v=>{h(v),Dr(v,{onSubmit:g,disabled:!f})},children:[a("div",{className:"small",id:e,children:"Choose which person should remain after combining these duplicates."}),a(Fx,{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:g,type:"button",children:"Combine people"})]})]})}function NP({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"){Tn(!0);return}if(t.kind==="duplicate-person")return;const m=r.trim(),f=t.validate?.(m)||null;if(f){s(f);return}Tn(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(Mo,{ariaLabel:`Close ${t.title}`,onClick:()=>Tn(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(kx,{"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(Se,{"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(TP,{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:()=>Tn(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?a("button",{autoFocus:!0,className:`settings-button ${Nx(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function kP(){const[e,t]=I(Sx());K(()=>(Zh(t),()=>{Cx(t)&&Zh(null)}),[]);const n=!!e,r=xe(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=xe(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?a(wi,{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||Tn(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?a(NP,{descriptionId:i,request:e,titleId:r}):null}):null}var nr=null;function Ba(){nr?.isConnected||(nr=document.getElementById("syncDialogMount"),nr||(nr=document.createElement("div"),nr.id="syncDialogMount",document.body.appendChild(nr)),Ue(a(kP,{}),nr))}function Kt(e){return Ba(),Cl("confirm")?new Promise(t=>{Sl(n=>t(!!n)),La({kind:"confirm",...e})}):Promise.resolve(!1)}function Rl(e){return Ba(),Cl("input")?new Promise(t=>{Sl(n=>t(typeof n=="string"?n:null)),La({kind:"input",...e})}):Promise.resolve(null)}function xP(e){return Ba(),Cl("duplicate-person")?new Promise(t=>{Sl(n=>t(n||{action:"cancel"})),La({kind:"duplicate-person",...e})}):Promise.resolve(Tx({kind:"duplicate-person",...e}))}function PP(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 EP(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function jg(e){const t=String(e.label||"").trim()||"Untitled Space",n=EP(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 AP(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 IP(e,t,n){return`Revoke ${t||n||"this device"} from ${jg(e).title}?`}function RP(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 DP(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 LP(){return{loaded:!1,loading:!1,error:"",includeInactive:!1,devicesLoaded:!1,scopes:[],membersByScope:new Map,devices:[],createScopeId:"",createLabel:"",createKind:"team",actionPendingKey:"",actionPendingKind:""}}function Dl(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=LP(),O.groupScopeManagementDrafts.set(e,t)),t}function bt(e,t){O.groupScopeManagementDrafts.set(e,t)}async function Hr(e,t,n=dt(e).includeInactive){bt(e,{...dt(e),loading:!0,error:"",includeInactive:n}),t();try{const[r,i]=await Promise.all([R_(e,n),Lu(e,!0)]),o=Dl(r),s=Dl(i),c=await Promise.all(o.map(async l=>{const d=String(l.scope_id||"").trim();return d?[d,Dl(await L_(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 Ll(e,t){O.groupScopeManagementOpen.add(e),dt(e),t(),Hr(e,t)}function Fg(e,t){O.groupScopeManagementOpen.delete(e),O.groupScopeManagementDrafts.delete(e),t()}async function $P(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 D_(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 Hr(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 MP(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,t,{device_id:n,role:"member"}),ne("Device granted access to the Space."),await Hr(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 OP(e,t,n,r,i){const o=String(t.scope_id||"").trim();if(!o||!await Kt({title:IP(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 M_(e,o,n),ne("Space access revoked. Future sync is blocked for that device."),await Hr(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 jP(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=RP(DP(n.devices,_.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",m=AP(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,m.detail),y("span",{class:"peer-meta"},m.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:()=>{MP(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:()=>{OP(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 FP(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=jg(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."),jP(e,t,n,r,i))}function BP(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,o=O.groupScopeManagementDrafts.get(t);if(!o)return null;const s=PP(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(te,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(Br,{"aria-labelledby":`coord-admin-domain-inactive-${t}`,checked:o.includeInactive,className:"coordinator-admin-switch",disabled:c,onCheckedChange:l=>{Hr(t,i,l)},thumbClassName:"coordinator-admin-switch-thumb"})),y("form",{class:"coordinator-admin-form",onSubmit:l=>{l.preventDefault(),!c&&$P(t,i)}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New Space id"),y(Se,{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})),y("label",{class:"coordinator-admin-field"},y("span",null,"Label"),y(Se,{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})),y("label",{class:"coordinator-admin-field"},y("span",null,"Kind"),y(Se,{class:"peer-scope-input",disabled:c,onInput:l=>{bt(t,{...dt(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:()=>{Hr(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=>FP(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 Bg(){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 UP(){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 $l(e,t){const n=UP();O.groupPreferencesDrafts.set(e,n),O.groupPreferencesOpen.add(e),t();try{const r=await ww(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 Ua(e,t){O.groupPreferencesOpen.delete(e),O.groupPreferencesDrafts.delete(e),t()}async function GP(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 Sw(e,r),ne("Team defaults saved. New devices use these filters and Space settings."),Ua(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 HP(e,t,n){const r=O.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(te,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(Br,{"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"})),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:o},"Auto-grant default Space on join"),y(Br,{"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?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(qh,{"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}),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(qh,{"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?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:()=>{GP(e,t)},type:"button"},r.saving?"Saving…":"Save defaults"),y("button",{class:"settings-button",disabled:r.saving,onClick:()=>Ua(e,t),type:"button"},"Cancel")))}function KP(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 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:()=>{O.groupPreferencesOpen.add(t.groupId),$l(t.groupId,e)},type:"button"},"Review Team defaults"),y("button",{class:"settings-button",onClick:()=>{Ll(t.groupId,e)},type:"button"},"Check Spaces"),y("button",{class:"settings-button",onClick:()=>{O.inviteGroup=t.groupId,O.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:()=>{O.teamSetupGuide=null,e()},type:"button"},"Dismiss")))}function qP(e,t){return t?e?"Restoring…":"Archiving…":e?"Unarchive":"Archive"}function VP(e){const{summary:t,createGroup:n,runGroup:r,renderShell:i,reloadData:o}=e,s=String(_.lastCoordinatorAdminStatus?.active_group||"").trim(),c=Zn(),l=Ur(),d=l.filter(g=>!g.archived_at),u=l.filter(g=>g.archived_at),p=O.showArchivedGroups?l:d,m=c?l.some(g=>g.group_id===c):!1,f=[`${d.length} active`];return u.length&&f.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"},f.join(" · ")):null,!m&&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,KP(i),(()=>{const g=t.readiness!=="ready"||O.groupActionPendingKind==="create";return y("form",{class:"coordinator-admin-form",onSubmit:h=>{h.preventDefault(),!g&&n()}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New Team id"),y(Se,{class:"peer-scope-input",disabled:g,onInput:h=>{O.createGroupId=String(h.currentTarget.value||"")},placeholder:"team-alpha",type:"text",value:O.createGroupId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Se,{class:"peer-scope-input",disabled:g,onInput:h=>{O.createGroupDisplayName=String(h.currentTarget.value||"")},placeholder:"Team Alpha",type:"text",value:O.createGroupDisplayName}))),y("div",{class:"section-actions coordinator-admin-groups-toolbar"},y("div",{class:"coordinator-admin-primary-actions"},y("button",{class:"settings-button",disabled:g,type:"submit"},O.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(Br,{"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?y("div",{class:"peer-list"},p.map(g=>{const h=g.group_id===c,v=O.groupActionPendingId===g.group_id,b=!!g.archived_at,w=O.groupRenameDrafts.get(g.group_id)??g.display_name??g.group_id,S=O.groupPreferencesOpen.has(g.group_id),T=O.groupScopeManagementOpen.has(g.group_id),N=b?"unarchive":"archive",P=qP(b,v&&O.groupActionPendingKind===N),A=wx({groupId:g.group_id,preferences:O.groupPreferencesDrafts.get(g.group_id),scopeManagement:O.groupScopeManagementDrafts.get(g.group_id),setupGuide:O.teamSetupGuide});return y("div",{class:"peer-card peer-card--padded",key:g.group_id},y("div",{class:"peer-title"},y("strong",null,w)),y("div",{class:"peer-submeta"},b?"Archived Team":"Active Team"),y("div",{class:"peer-meta"},`Advanced: Team ID ${g.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,A.defaultSpace)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Auto-grant"),y("strong",null,A.autoGrant)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Spaces"),y("strong",null,A.spaces))),s===g.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(Se,{class:"peer-scope-input",disabled:t.readiness!=="ready"||v,onInput:M=>{O.groupRenameDrafts.set(g.group_id,String(M.currentTarget.value||""))},type:"text",value:w})),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:t.readiness!=="ready"||h,onClick:()=>{bl(g.group_id),o()},type:"button"},h?"Managing":"Manage Team"),y("button",{class:"settings-button",disabled:t.readiness!=="ready"||v,onClick:()=>r(g.group_id,w,"rename"),type:"button"},v&&O.groupActionPendingKind==="rename"?"Renaming…":"Rename"),y("button",{"aria-expanded":S,"aria-controls":`coord-admin-project-defaults-drawer-${g.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":S?"open":"closed",disabled:t.readiness!=="ready"||v,onClick:()=>{S?Ua(g.group_id,i):$l(g.group_id,i)},type:"button"},y("span",null,"Team defaults"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(Bg,null))),y("button",{"aria-expanded":T,"aria-controls":`coord-admin-spaces-drawer-${g.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":T?"open":"closed",disabled:t.readiness!=="ready"||v,onClick:()=>{T?Fg(g.group_id,i):Ll(g.group_id,i)},type:"button"},y("span",null,"Spaces & access"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(Bg,null))),y("button",{class:b?"settings-button":"settings-button danger",disabled:t.readiness!=="ready"||v,onClick:()=>r(g.group_id,g.display_name||g.group_id,N),type:"button"},P)),y(va,{open:S,onOpenChange:M=>{M?$l(g.group_id,i):Ua(g.group_id,i)}},y(ya,{"aria-label":`Project defaults for ${w}`,class:"coordinator-admin-group-preferences",id:`coord-admin-project-defaults-drawer-${g.group_id}`},S?HP(g.group_id,i,t.readiness==="ready"):null)),y(va,{open:T,onOpenChange:M=>{M?Ll(g.group_id,i):Fg(g.group_id,i)}},y(ya,{"aria-label":`Spaces for ${w}`,class:"coordinator-admin-group-preferences coordinator-admin-domain-management",id:`coord-admin-spaces-drawer-${g.group_id}`},T?BP({groupId:g.group_id,ready:t.readiness==="ready",renderShell:i,summary:t}):null)))})):y("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 Kr(e){return a("textarea",{...e})}function WP(e){const{summary:t,createInvite:n,renderShell:r}=e,i=_.lastCoordinatorAdminStatus,o=Zn()||String(i?.active_group||"").trim(),s=O.inviteGroup.trim()||o,c=String(_.lastTeamInvite?.encoded||"").trim(),l=Array.isArray(_.lastTeamInvite?.warnings)?_.lastTeamInvite?.warnings:[],d=t.readiness!=="ready"||O.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(Se,{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})),y("label",{class:"coordinator-admin-field"},y("span",null,"Join policy"),y(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"})),y("label",{class:"coordinator-admin-field"},y("span",null,"Expires in (hours)"),y(Se,{class:"peer-scope-input",disabled:t.readiness!=="ready",min:"1",onInput:u=>{O.inviteTtlHours=String(u.currentTarget.value||"")},type:"number",value:O.inviteTtlHours}))),y("div",{class:"section-actions"},y("button",{class:"settings-button",disabled:d,type:"submit"},O.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(Kr,{class:"feed-search coordinator-admin-output",readOnly:!0,value:c}),y("button",{class:"settings-button sync-action-copy",type:"button",onClick:u=>Ai(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."),_.lastShareOperations.length>0?y("ul",{class:"peer-scope-rejections-list","aria-label":"Project sharing operations"},..._.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 zP(e){const{summary:t,reviewJoinRequest:n}=e,r=Array.isArray(_.lastCoordinatorAdminJoinRequests)?_.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=O.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&&O.joinReviewPendingAction==="approve"?"Approving…":"Approve"),y("button",{class:"settings-button danger",disabled:!o||u,onClick:()=>n(o,"deny"),type:"button"},u&&O.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 JP(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 P_({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,g=String(m?.scope_id||"");O.createGroupId="",O.createGroupDisplayName="",O.teamSetupGuide={groupId:l,displayName:String(u.group?.display_name||d||l),defaultSpaceScopeId:g,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(),bl(l),await n(),u.setup_warning?ne("Team created, but default Space setup needs repair.","warning"):g?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 E_(l,d),ne("Team renamed.","success")),u==="archive"&&(await A_(l),ne("Team archived.","success")),u==="unarchive"&&(await I_(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=_.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 $u({group_id:u,policy:O.invitePolicy,ttl_hours:p});_.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 j_(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 F_(l,d,m),ne("Device renamed.","success")}p==="disable"&&(await B_(l,d),ne("Device disabled.","success")),p==="enable"&&(await U_(l,d),ne("Device enabled.","success")),p==="remove"&&(await G_(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 YP(){const e=_.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:XP,runGroupAction:QP,createInviteFromAdminPanel:ZP,reviewJoinRequestFromAdminPanel:eE,runDeviceAction:tE}=JP({renderShell:()=>rr(),reloadData:()=>Ml()});function rr(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=_.lastCoordinatorAdminStatus,n=YP(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!fx()?.archived_at,c=n.readiness==="ready",l=n.readiness==="ready"&&!s,d=n.readiness==="ready",u=n.readiness==="ready",p=Zn(),m=Ur().filter(b=>!b.archived_at).length,f=Ur().filter(b=>b.archived_at).length,g=Array.isArray(_.lastCoordinatorAdminJoinRequests)?_.lastCoordinatorAdminJoinRequests.length:0,h=Array.isArray(_.lastCoordinatorAdminDevices)?_.lastCoordinatorAdminDevices.length:0,v=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"),Ue(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,`${m} active${f?` · ${f} archived`:""}`)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Selected Team activity"),y("strong",null,`${g} join requests · ${h} devices`))),v?y("div",{class:"peer-meta coordinator-admin-inline-warning"},v):null,r?y("div",{class:"section-meta coordinator-admin-inline-meta"},`Coordinator: ${r}`):null),y("div",{class:"card coordinator-admin-sections"},y(Wf,{ariaLabel:"Teams sections",listClassName:"coordinator-admin-tabs-list",onValueChange:b=>{O.activeSection=b||"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:O.activeSection},VP({summary:n,createGroup:()=>{XP()},runGroup:(b,w,S)=>{QP(b,w,S)},renderShell:rr,reloadData:()=>{Ml()}}),WP({summary:n,createInvite:()=>{ZP()},renderShell:rr}),zP({summary:n,reviewJoinRequest:(b,w)=>{eE(b,w)}}),LN({summary:n,runDevice:(b,w,S,T)=>{tE(b,w,S,T)}})),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 nE(){rr()}async function Ml(){try{_.lastCoordinatorAdminStatus=await No()}catch{_.lastCoordinatorAdminStatus=null,_.lastCoordinatorAdminJoinRequests=[],_.lastCoordinatorAdminDevices=[],O.deviceRenameDrafts.clear(),O.deviceRenameServerNames.clear(),rr();return}const e=String(_.lastCoordinatorAdminStatus?.active_group||"").trim();if(Qh(),_.lastCoordinatorAdminStatus?.readiness==="ready"){try{const n=await Wu();_.lastShareOperations=Array.isArray(n.items)?n.items:[]}catch{}try{const n=await Du(O.showArchivedGroups);_.lastCoordinatorAdminGroups=Array.isArray(n?.items)?n.items:[],mx(),Qh()}catch{_.lastCoordinatorAdminGroups=[],O.groupRenameDrafts.clear()}const t=Zn();try{const n=await O_(t||e);_.lastCoordinatorAdminJoinRequests=Array.isArray(n?.items)?n.items:[]}catch{_.lastCoordinatorAdminJoinRequests=[]}try{const n=await Lu(t||e,!0);_.lastCoordinatorAdminDevices=Array.isArray(n?.items)?n.items:[],hx()}catch{_.lastCoordinatorAdminDevices=[]}try{O.availableProjects=await ko()}catch{O.availableProjects=[]}}else _.lastCoordinatorAdminGroups=[],O.groupRenameDrafts.clear(),_.lastCoordinatorAdminJoinRequests=[],_.lastCoordinatorAdminDevices=[],O.deviceRenameDrafts.clear(),O.deviceRenameServerNames.clear();rr()}var Ol=new WeakMap,Ug={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},rE={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},iE={available:"Available",offline:"Offline",unknown:"Availability unknown"};function jl(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function oE(e,t){return t.get(e)??rE}function aE(e){return e.reduce((t,n)=>!t||Ug[n.state]>Ug[t.state]?n:t,null)}function sE(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 cE(e,t,n,r){const i=new Map(e.identities.filter(d=>d.status==="active"&&d.mergedIntoIdentityId===null).map(d=>[d.identityId,d.displayName])),o=new Map(e.teams.filter(d=>d.status==="active").map(d=>[d.teamId,d.displayName])),s=new Map(n.map(d=>[d.canonicalProjectIdentity,d.displayName])),c=new Map(r.map(d=>[d.deviceId,d.state])),l=new Map(t.items.map(d=>[d.canonicalProjectIdentity,d]));return{devices:e.identityDevices.filter(d=>d.status==="active"&&i.has(d.identityId)).map(d=>{const u=new Set(e.teamMemberships.filter(S=>S.status==="active"&&S.identityId===d.identityId&&o.has(S.teamId)).map(S=>S.teamId)),p=jl(e.projectRecipients.filter(S=>S.status==="active"&&S.recipientKind==="identity"&&S.identityId===d.identityId).map(S=>S.canonicalProjectIdentity)),m=new Map;for(const S of e.projectRecipients){if(S.status!=="active"||S.recipientKind!=="team"||!u.has(S.teamId))continue;const T=m.get(S.canonicalProjectIdentity)??new Set;T.add(S.teamId),m.set(S.canonicalProjectIdentity,T)}const f=(S,T=[])=>{const N=s.get(S);if(!N)return null;const P=oE(S,l);return{displayName:N,teamNames:jl([...T].flatMap(A=>{const M=o.get(A);return M?[M]:[]})),state:P.state,statusLabel:P.label,statusCopy:P.explanation,deliveredCopiesMayRemain:P.deliveredCopiesMayRemain}},g=p.flatMap(S=>{const T=f(S);return T?[T]:[]}),h=jl(m.keys()).flatMap(S=>{const T=f(S,m.get(S));return T?[T]:[]}),v=[...g,...h],b=aE(v),w=c.get(d.deviceId)??"unknown";return{deviceId:d.deviceId,displayName:d.displayName,identityName:i.get(d.identityId)??"Identity unavailable",availability:w,availabilityLabel:iE[w],directProjects:g,inheritedProjects:h,unavailableProjectCount:p.length+m.size-v.length,statusState:b?.state??"no_projects",statusLabel:b?.statusLabel??"No shared Projects",statusCopy:b?.statusCopy??"This device has no current Project access.",deliveredCopiesMayRemain:v.some(S=>S.deliveredCopiesMayRemain),action:sE(w,b?.state??"no_projects")}}).sort((d,u)=>d.displayName.localeCompare(u.displayName)||d.identityName.localeCompare(u.identityName)),revokedDeviceCount:e.identityDevices.filter(d=>d.status==="revoked"&&i.has(d.identityId)).length}}function Gg({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}),n.teamNames.length?` through ${n.teamNames.join(", ")}`:"",a("span",{className:"small",children:[" ","— ",n.statusLabel,". ",n.statusCopy]})]},`${n.displayName}:${n.teamNames.join(":")}`))})}function lE({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})]}),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(Gg,{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(Gg,{empty:"No Projects are inherited through Teams.",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&&Ol.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 Ga(e,t,n,r,i,o={}){const s=document.activeElement,c=s instanceof HTMLElement&&e.contains(s)?Ol.get(s):void 0,l=cE(t,n,r,i);Ue(a("section",{"aria-labelledby":"devices-heading",className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[a("div",{className:"recipient-policy-sharing-header",children:[a("h2",{id:"devices-heading",children:"Devices"}),a("p",{className:"small",children:"See where Codemem runs and which Projects each active device receives."})]}),a(lE,{options:o,projection:l})]}),e),c&&([...e.querySelectorAll("button")].find(d=>{const u=Ol.get(d);return u?.deviceId===c.deviceId&&u.target===c.target})??document.getElementById("tabBtn-devices"))?.focus()}function dE(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 uE(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 qr(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 xn(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 Hg(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function pE(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 Fl(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 Ui(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 mE(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 Ha(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 Kg(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function fE(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function hE(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 qg(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function gE(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function vE(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 Ka(e){if(!e||typeof e!="object")return{};const t=e,n=t.import_metadata;return n&&typeof n=="object"?{...n,...t}:t}function yE(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 bE(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 Vg(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 Wg(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()}:${Wg(e)}`}function _E(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function wE(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function SE(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===_.lastStatsPayload?.identity?.actor_id?"You":n||t||"Unknown author"}function zg(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 CE(e,t){const n=new Set(t.map(ft));return zg(e.filter(r=>!n.has(ft(r))),t)}var VO=560;function TE(){const e=document.documentElement,t=Math.max(e.scrollHeight,document.body.scrollHeight);return window.innerHeight+window.scrollY>=t-560}function qa(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 NE(e,t){const n=new Set(t.map(ft));return e.filter(r=>!n.has(ft(r))).length}var[Wa,WO]=st("Tooltip",[Sn]),za=Sn(),Jg="TooltipProvider",kE=700,Bl="tooltip.open",[xE,Ul]=Wa(Jg),Yg=e=>{const{__scopeTooltip:t,delayDuration:n=kE,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:o}=e,s=B(!0),c=B(!1),l=B(0);return K(()=>{const d=l.current;return()=>window.clearTimeout(d)},[]),a(xE,{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})};Yg.displayName=Jg;var Gi="Tooltip",[PE,Hi]=Wa(Gi),Xg=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:o,disableHoverableContent:s,delayDuration:c}=e,l=Ul(Gi,e.__scopeTooltip),d=za(t),[u,p]=I(null),m=ct(),f=B(0),g=s??l.disableHoverableContent,h=c??l.delayDuration,v=B(!1),[b,w]=wt({prop:r,defaultProp:i??!1,onChange:A=>{A?(l.onOpen(),document.dispatchEvent(new CustomEvent(Bl))):l.onClose(),o?.(A)},caller:Gi}),S=xe(()=>b?v.current?"delayed-open":"instant-open":"closed",[b]),T=re(()=>{window.clearTimeout(f.current),f.current=0,v.current=!1,w(!0)},[w]),N=re(()=>{window.clearTimeout(f.current),f.current=0,w(!1)},[w]),P=re(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{v.current=!0,w(!0),f.current=0},h)},[h,w]);return K(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),a(Oi,{...d,children:a(PE,{scope:t,contentId:m,open:b,stateAttribute:S,trigger:u,onTriggerChange:p,onTriggerEnter:re(()=>{l.isOpenDelayedRef.current?P():T()},[l.isOpenDelayedRef,P,T]),onTriggerLeave:re(()=>{g?N():(window.clearTimeout(f.current),f.current=0)},[N,g]),onOpen:T,onClose:N,disableHoverableContent:g,children:n})})};Xg.displayName=Gi;var Gl="TooltipTrigger",Qg=F((e,t)=>{const{__scopeTooltip:n,...r}=e,i=Hi(Gl,n),o=Ul(Gl,n),s=za(n),c=we(t,B(null),i.onTriggerChange),l=B(!1),d=B(!1),u=re(()=>l.current=!1,[]);return K(()=>()=>document.removeEventListener("pointerup",u),[u]),a(ji,{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)})})});Qg.displayName=Gl;var Hl="TooltipPortal",[EE,AE]=Wa(Hl,{forceMount:void 0}),Zg=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,o=Hi(Hl,t);return a(EE,{scope:t,forceMount:n,children:a(rt,{present:n||o.open,children:a(qn,{asChild:!0,container:i,children:r})})})};Zg.displayName=Hl;var Vr="TooltipContent",ev=F((e,t)=>{const n=AE(Vr,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...o}=e,s=Hi(Vr,e.__scopeTooltip);return a(rt,{present:r||s.open,children:s.disableHoverableContent?a(tv,{side:i,...o,ref:t}):a(IE,{side:i,...o,ref:t})})}),IE=F((e,t)=>{const n=Hi(Vr,e.__scopeTooltip),r=Ul(Vr,e.__scopeTooltip),i=B(null),o=we(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((g,h)=>{const v=g.currentTarget,b={x:g.clientX,y:g.clientY},w=ME(b,$E(b,v.getBoundingClientRect())),S=OE(h.getBoundingClientRect());c(FE([...w,...S])),p(!0)},[p]);return K(()=>()=>m(),[m]),K(()=>{if(l&&u){const g=v=>f(v,u),h=v=>f(v,l);return l.addEventListener("pointerleave",g),u.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",g),u.removeEventListener("pointerleave",h)}}},[l,u,f,m]),K(()=>{if(s){const g=h=>{const v=h.target,b={x:h.clientX,y:h.clientY},w=l?.contains(v)||u?.contains(v),S=!jE(b,s);w?m():S&&(m(),d())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,u,s,d,m]),a(tv,{...e,ref:o})}),[RE,DE]=Wa(Gi,{isInside:!1}),LE=rS("TooltipContent"),tv=F((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:s,...c}=e,l=Hi(Vr,n),d=za(n),{onClose:u}=l;return K(()=>(document.addEventListener(Bl,u),()=>document.removeEventListener(Bl,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(Kn,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:u,children:a(Ea,{"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(LE,{children:r}),a(RE,{scope:n,isInside:!0,children:a(bT,{id:l.contentId,role:"tooltip",children:i||r})})]})})});ev.displayName=Vr;var nv="TooltipArrow",rv=F((e,t)=>{const{__scopeTooltip:n,...r}=e,i=za(n);return DE(nv,n).isInside?null:a(Aa,{...i,...r,ref:t})});rv.displayName=nv;function $E(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 ME(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 OE(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 jE(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 FE(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),BE(t)}function BE(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 UE=Yg,GE=Xg,HE=Qg,KE=Zg,qE=ev,VE=rv;function Kl({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return a(UE,{delayDuration:t,skipDelayDuration:n,children:e})}function Ja({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(GE,{children:[a(HE,{asChild:o,children:e}),a(KE,{children:a(qE,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,a(VE,{className:"tooltip-arrow"})]})})]})}function WE(e){e.dataset.feedRenderRoot="preact"}function zE(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function JE(e,t){WE(e),Ue(y(Kl,null,t),e)}function YE(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function XE(e){return e.split(/\n|,/).map(t=>t.trim()).filter(Boolean)}function ql(e){return JSON.stringify([e.project,e.query.trim(),e.workingSetFiles])}function QE(e){const t=Ka(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=Ha(e?.facts||t?.facts||[]),l=c.length?c:yE(r||n),d=l.length?l:bE(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function ZE(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 eA(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function tA(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function nA(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function rA(e,t){const n=_.feedTypeFilter==="observations"?" · observations":_.feedTypeFilter==="summaries"?" · session summaries":"",r=_E(_.feedScopeFilter),i=!_.feedQuery.trim()&&_.lastFeedFilteredCount?` · ${_.lastFeedFilteredCount} observations filtered`:"";return`${e} items${n}${r}${_.feedQuery.trim()?` · matching "${_.feedQuery.trim()}"`:""}${i}${t?" · scroll for more":""}`}function Ya({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 iA({open:e}){const[t,n]=I(()=>String(_.feedQuery||"")),[r,i]=I(!1),[o,s]=I(!1),[c,l]=I(""),[d,u]=I(!1),[p,m]=I(""),[f,g]=I(""),[h,v]=I(null),b=B(0),w=String(_.feedQuery||""),S=String(t||"").trim(),T=_.currentProject||null,N=XE(c),P=ql({project:T,query:S,workingSetFiles:N}),A=h&&ql({project:h.inputs.project,query:h.inputs.query,workingSetFiles:h.inputs.working_set_files})===P?h:null,M=p&&f===P?p:"";K(()=>{b.current+=1,u(!1),m(""),g(""),v(L=>!L||L.inputs.query!==S||L.inputs.project!==T?null:L)},[P]),K(()=>{e&&!r&&(n(YE({feedQuery:w,hasInspectorOverride:o,inspectorQuery:t})),i(!0))},[w,o,r,t,e]);const U=async()=>{const L=S,J=T,H=N,k=ql({project:J,query:L,workingSetFiles:H}),R=b.current+1;if(b.current=R,!L){m("Enter a query to inspect."),g(k),v(null);return}u(!0),m(""),g("");try{const j=await V_({context:L,project:J,working_set_files:H});if(R!==b.current)return;v(j)}catch(j){if(R!==b.current)return;m(j instanceof Error?j.message:String(j)),g(k),v(null)}finally{R===b.current&&u(!1)}},x=A?.retrieval.candidates.filter(L=>L.disposition==="selected")||[],G=A?.retrieval.candidates.filter(L=>L.disposition==="dropped")||[],E=A?.retrieval.candidates.filter(L=>L.disposition==="deduped")||[],$=A?.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),v(null),m(""),g("")},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:()=>{U()},type:"button"},d?"Tracing…":"Run trace"),A?y("span",{className:"section-meta"},`mode=${A.mode.selected} · candidates=${A.retrieval.candidate_count} · tokens=${A.output.estimated_tokens}`):null),h&&!A?y("div",{className:"section-meta",style:"margin-top:8px;"},"Trace inputs changed. Run trace again for the current query, project, and working set."):null,M?y("div",{className:"section-meta",style:"margin-top:8px; color:#d96c6c;"},M):null]),A?y(te,null,[y(Ya,{label:"Selected",candidates:x}),y(Ya,{label:"Dropped",candidates:G}),y(Ya,{label:"Deduped",candidates:E}),y(Ya,{label:"Trimmed",candidates:$}),y("div",{className:"feed-card-body"},[A.assembly.collapsed_groups.length?y("div",{className:"section-meta"},`Collapsed duplicates: ${A.assembly.collapsed_groups.map(L=>`kept #${L.kept} from [${L.dropped.join(", ")}]`).join(" · ")}`):null,A.assembly.trim_reasons.length?y("div",{className:"section-meta"},`Trim reasons: ${A.assembly.trim_reasons.join(", ")}`):null,y("div",{className:"section-meta"},"Final pack"),y("pre",{style:"white-space:pre-wrap; overflow:auto;"},A.output.pack_text)])]):null])):null}var oA={kind:"kind-chip",provenance:"provenance-chip",tag:"tag-chip",badge:"badge",scope:"peer-scope-chip"};function Vl({variant:e,tone:t,title:n,children:r}){const i=oA[e];return a("span",{className:t?`${i} ${t}`:i,title:n,children:r})}function iv(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 aA(e){if(Array.isArray(e))return e}function sA(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 cA(){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 lA(e,t){return aA(e)||sA(e,t)||dA(e,t)||cA()}function dA(e,t){if(e){if(typeof e=="string")return iv(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)?iv(e,t):void 0}}var ov=Object.entries,av=Object.setPrototypeOf,uA=Object.isFrozen,pA=Object.getPrototypeOf,mA=Object.getOwnPropertyDescriptor,Ye=Object.freeze,Xe=Object.seal,Wr=Object.create,sv=typeof Reflect<"u"&&Reflect,Wl=sv.apply,zl=sv.construct;Ye||(Ye=function(t){return t}),Xe||(Xe=function(t){return t}),Wl||(Wl=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)}),zl||(zl=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 Ki=He(Array.prototype.forEach),fA=He(Array.prototype.lastIndexOf),cv=He(Array.prototype.pop),zr=He(Array.prototype.push),hA=He(Array.prototype.splice),Pn=Array.isArray,qi=He(String.prototype.toLowerCase),Jl=He(String.prototype.toString),lv=He(String.prototype.match),Vi=He(String.prototype.replace),dv=He(String.prototype.indexOf),gA=He(String.prototype.trim),vA=He(Number.prototype.toString),yA=He(Boolean.prototype.toString),uv=typeof BigInt>"u"?null:He(BigInt.prototype.toString),pv=typeof Symbol>"u"?null:He(Symbol.prototype.toString),We=He(Object.prototype.hasOwnProperty),Wi=He(Object.prototype.toString),Qe=He(RegExp.prototype.test),or=bA(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 Wl(e,t,r)}}function bA(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return zl(e,n)}}function Te(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:qi;if(av&&av(e,null),!Pn(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i=="string"){const o=n(i);o!==i&&(uA(t)||(t[r]=o),i=o)}e[i]=!0}return e}function _A(e){for(let t=0;t<e.length;t++)We(e,t)||(e[t]=null);return e}function ut(e){const t=Wr(null);for(const r of ov(e)){var n=lA(r,2);const i=n[0],o=n[1];We(e,i)&&(Pn(o)?t[i]=_A(o):o&&typeof o=="object"&&o.constructor===Object?t[i]=ut(o):t[i]=o)}return t}function wA(e){switch(typeof e){case"string":return e;case"number":return vA(e);case"boolean":return yA(e);case"bigint":return uv?uv(e):"0";case"symbol":return pv?pv(e):"Symbol()";case"undefined":return Wi(e);case"function":case"object":{if(e===null)return Wi(e);const t=e,n=qt(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:Wi(r)}return Wi(e)}default:return Wi(e)}}function qt(e,t){for(;e!==null;){const r=mA(e,t);if(r){if(r.get)return He(r.get);if(typeof r.value=="function")return He(r.value)}e=pA(e)}function n(){return null}return n}function SA(e){try{return Qe(e,""),!0}catch{return!1}}var mv=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"]),Yl=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"]),Xl=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"]),CA=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"]),Ql=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"]),TA=Ye(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),fv=Ye(["#text"]),hv=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"]),Zl=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"]),gv=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"]),Xa=Ye(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),NA=Xe(/{{[\w\W]*|^[\w\W]*}}/g),kA=Xe(/<%[\w\W]*|^[\w\W]*%>/g),xA=Xe(/\${[\w\W]*/g),PA=Xe(/^data-[\-\w.\u00B7-\uFFFF]+$/),EA=Xe(/^aria-[\-\w]+$/),vv=Xe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),AA=Xe(/^(?:\w+script|data):/i),IA=Xe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),RA=Xe(/^html$/i),DA=Xe(/^[a-z][.\w]*(-[.\w]+)+$/i),yv=Xe(/<[/\w!]/g),LA=Xe(/<[/\w]/g),$A=Xe(/<\/no(script|embed|frames)/i),MA=Xe(/\/>/i),Vt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},OA=function(){return typeof window>"u"?null:window},jA=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}},bv=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},En=function(t,n,r,i){return We(t,n)&&Pn(t[n])?Te(i.base?ut(i.base):{},t[n],i.transform):r};function _v(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:OA();const t=ee=>_v(ee);if(t.version="3.4.11",t.removed=[],!e||!e.document||e.document.nodeType!==Vt.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=qt(p,"cloneNode"),f=qt(p,"remove"),g=qt(p,"nextSibling"),h=qt(p,"childNodes"),v=qt(p,"parentNode"),b=qt(p,"shadowRoot"),w=qt(p,"attributes"),S=s&&s.prototype?qt(s.prototype,"nodeType"):null,T=s&&s.prototype?qt(s.prototype,"nodeName"):null;if(typeof o=="function"){const ee=n.createElement("template");ee.content&&ee.content.ownerDocument&&(n=ee.content.ownerDocument)}let N,P="",A,M=!1,U=0;const x=function(){if(U>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){x(),U++;try{return N.createHTML(C)}finally{U--}},E=function(C){x(),U++;try{return N.createScriptURL(C)}finally{U--}},$=function(){return M||(A=jA(u,i),M=!0),A},L=n,J=L.implementation,H=L.createNodeIterator,k=L.createDocumentFragment,R=L.getElementsByTagName,j=r.importNode;let V=bv();t.isSupported=typeof ov=="function"&&typeof v=="function"&&J&&J.createHTMLDocument!==void 0;const ge=NA,le=kA,ce=xA,be=PA,Y=EA,fe=AA,X=IA,_e=DA;let he=vv,Q=null;const $e=Te({},[...mv,...Yl,...Xl,...Ql,...fv]);let ue=null;const q=Te({},[...hv,...Zl,...gv,...Xa]);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}})),qe=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 pn=!0,Lt=!0,Nt=!1,$t=!0,nt=!1,Mt=!0,pe=!1,ae=!1,Ge=null,On=null,So=!1,mn=!1,br=!1,jn=!1,ht=!0,Fn=!1;const c_="user-content-";let vu=!0,yu=!1,si={},Yt=null;const bu=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 l_=null;const d_=Te({},["audio","video","img","source","image","track"]);let _u=null;const u_=Te({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ls="http://www.w3.org/1998/Math/MathML",$s="http://www.w3.org/2000/svg",Xt="http://www.w3.org/1999/xhtml";let ci=Xt,wu=!1,Su=null;const gO=Te({},[Ls,$s,Xt],Jl),p_=Ye(["mi","mo","mn","ms","mtext"]);let Cu=Te({},p_);const m_=Ye(["annotation-xml"]);let Tu=Te({},m_);const vO=Te({},["title","style","font","a","script"]);let Co=null;const yO=["application/xhtml+xml","text/html"],bO="text/html";let Be=null,li=null;const _O=n.createElement("form"),f_=function(C){return C instanceof RegExp||C instanceof Function},Nu=function(){let C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(li&&li===C)return;(!C||typeof C!="object")&&(C={}),C=ut(C),Co=yO.indexOf(C.PARSER_MEDIA_TYPE)===-1?bO:C.PARSER_MEDIA_TYPE,Be=Co==="application/xhtml+xml"?Jl:qi,Q=En(C,"ALLOWED_TAGS",$e,{transform:Be}),ue=En(C,"ALLOWED_ATTR",q,{transform:Be}),Su=En(C,"ALLOWED_NAMESPACES",gO,{transform:Jl}),_u=En(C,"ADD_URI_SAFE_ATTR",u_,{transform:Be,base:u_}),l_=En(C,"ADD_DATA_URI_TAGS",d_,{transform:Be,base:d_}),Yt=En(C,"FORBID_CONTENTS",bu,{transform:Be}),qe=En(C,"FORBID_TAGS",ut({}),{transform:Be}),Me=En(C,"FORBID_ATTR",ut({}),{transform:Be}),si=We(C,"USE_PROFILES")?C.USE_PROFILES&&typeof C.USE_PROFILES=="object"?ut(C.USE_PROFILES):C.USE_PROFILES:!1,pn=C.ALLOW_ARIA_ATTR!==!1,Lt=C.ALLOW_DATA_ATTR!==!1,Nt=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,pe=C.WHOLE_DOCUMENT||!1,mn=C.RETURN_DOM||!1,br=C.RETURN_DOM_FRAGMENT||!1,jn=C.RETURN_TRUSTED_TYPE||!1,So=C.FORCE_BODY||!1,ht=C.SANITIZE_DOM!==!1,Fn=C.SANITIZE_NAMED_PROPS||!1,vu=C.KEEP_CONTENT!==!1,yu=C.IN_PLACE||!1,he=SA(C.ALLOWED_URI_REGEXP)?C.ALLOWED_URI_REGEXP:vv,ci=typeof C.NAMESPACE=="string"?C.NAMESPACE:Xt,Cu=We(C,"MATHML_TEXT_INTEGRATION_POINTS")&&C.MATHML_TEXT_INTEGRATION_POINTS&&typeof C.MATHML_TEXT_INTEGRATION_POINTS=="object"?ut(C.MATHML_TEXT_INTEGRATION_POINTS):Te({},p_),Tu=We(C,"HTML_INTEGRATION_POINTS")&&C.HTML_INTEGRATION_POINTS&&typeof C.HTML_INTEGRATION_POINTS=="object"?ut(C.HTML_INTEGRATION_POINTS):Te({},m_);const D=We(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),We(D,"tagNameCheck")&&f_(D.tagNameCheck)&&(oe.tagNameCheck=D.tagNameCheck),We(D,"attributeNameCheck")&&f_(D.attributeNameCheck)&&(oe.attributeNameCheck=D.attributeNameCheck),We(D,"allowCustomizedBuiltInElements")&&typeof D.allowCustomizedBuiltInElements=="boolean"&&(oe.allowCustomizedBuiltInElements=D.allowCustomizedBuiltInElements),Xe(oe),nt&&(Lt=!1),br&&(mn=!0),si&&(Q=Te({},fv),ue=Wr(null),si.html===!0&&(Te(Q,mv),Te(ue,hv)),si.svg===!0&&(Te(Q,Yl),Te(ue,Zl),Te(ue,Xa)),si.svgFilters===!0&&(Te(Q,Xl),Te(ue,Zl),Te(ue,Xa)),si.mathMl===!0&&(Te(Q,Ql),Te(ue,gv),Te(ue,Xa))),tt.tagCheck=null,tt.attributeCheck=null,We(C,"ADD_TAGS")&&(typeof C.ADD_TAGS=="function"?tt.tagCheck=C.ADD_TAGS:Pn(C.ADD_TAGS)&&(Q===$e&&(Q=ut(Q)),Te(Q,C.ADD_TAGS,Be))),We(C,"ADD_ATTR")&&(typeof C.ADD_ATTR=="function"?tt.attributeCheck=C.ADD_ATTR:Pn(C.ADD_ATTR)&&(ue===q&&(ue=ut(ue)),Te(ue,C.ADD_ATTR,Be))),We(C,"ADD_URI_SAFE_ATTR")&&Pn(C.ADD_URI_SAFE_ATTR)&&Te(_u,C.ADD_URI_SAFE_ATTR,Be),We(C,"FORBID_CONTENTS")&&Pn(C.FORBID_CONTENTS)&&(Yt===bu&&(Yt=ut(Yt)),Te(Yt,C.FORBID_CONTENTS,Be)),We(C,"ADD_FORBID_CONTENTS")&&Pn(C.ADD_FORBID_CONTENTS)&&(Yt===bu&&(Yt=ut(Yt)),Te(Yt,C.ADD_FORBID_CONTENTS,Be)),vu&&(Q["#text"]=!0),pe&&Te(Q,["html","head","body"]),Q.table&&(Te(Q,["tbody"]),delete qe.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 Z=N;N=C.TRUSTED_TYPES_POLICY;try{P=G("")}catch(ie){throw N=Z,ie}}else C.TRUSTED_TYPES_POLICY===null?(N=void 0,P=""):(N===void 0&&(N=$()),N&&typeof P=="string"&&(P=G("")));Ye&&Ye(C),li=C},h_=Te({},[...Yl,...Xl,...CA]),g_=Te({},[...Ql,...TA]),wO=function(C,D,Z){return D.namespaceURI===Xt?C==="svg":D.namespaceURI===Ls?C==="svg"&&(Z==="annotation-xml"||Cu[Z]):!!h_[C]},SO=function(C,D,Z){return D.namespaceURI===Xt?C==="math":D.namespaceURI===$s?C==="math"&&Tu[Z]:!!g_[C]},CO=function(C,D,Z){return D.namespaceURI===$s&&!Tu[Z]||D.namespaceURI===Ls&&!Cu[Z]?!1:!g_[C]&&(vO[C]||!h_[C])},TO=function(C){let D=v(C);(!D||!D.tagName)&&(D={namespaceURI:ci,tagName:"template"});const Z=qi(C.tagName),ie=qi(D.tagName);return Su[C.namespaceURI]?C.namespaceURI===$s?wO(Z,D,ie):C.namespaceURI===Ls?SO(Z,D,ie):C.namespaceURI===Xt?CO(Z,D,ie):!!(Co==="application/xhtml+xml"&&Su[C.namespaceURI]):!1},Bn=function(C){zr(t.removed,{element:C});try{v(C).removeChild(C)}catch{if(f(C),!v(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")}},v_=function(C){const D=h(C);if(D){const ie=[];Ki(D,Ce=>{zr(ie,Ce)}),Ki(ie,Ce=>{try{f(Ce)}catch{}})}const Z=w(C);if(Z)for(let ie=Z.length-1;ie>=0;--ie){const Ce=Z[ie],Ae=Ce&&Ce.name;if(typeof Ae=="string")try{C.removeAttribute(Ae)}catch{}}},_r=function(C,D){try{zr(t.removed,{attribute:D.getAttributeNode(C),from:D})}catch{zr(t.removed,{attribute:null,from:D})}if(D.removeAttribute(C),C==="is")if(mn||br)try{Bn(D)}catch{}else try{D.setAttribute(C,"")}catch{}},NO=function(C){const D=w(C);if(D)for(let Z=D.length-1;Z>=0;--Z){const ie=D[Z],Ce=ie&&ie.name;if(!(typeof Ce!="string"||ue[Be(Ce)]))try{C.removeAttribute(Ce)}catch{}}},kO=function(C){const D=[C];for(;D.length>0;){const Z=D.pop();(S?S(Z):Z.nodeType)===Vt.element&&NO(Z);const ie=h(Z);if(ie)for(let Ce=ie.length-1;Ce>=0;--Ce)D.push(ie[Ce])}},y_=function(C){let D=null,Z=null;if(So)C="<remove></remove>"+C;else{const Ae=lv(C,/^[\r\n\t ]+/);Z=Ae&&Ae[0]}Co==="application/xhtml+xml"&&ci===Xt&&(C='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+C+"</body></html>");const ie=N?G(C):C;if(ci===Xt)try{D=new d().parseFromString(ie,Co)}catch{}if(!D||!D.documentElement){D=J.createDocument(ci,"template",null);try{D.documentElement.innerHTML=wu?P:ie}catch{}}const Ce=D.body||D.documentElement;return C&&Z&&Ce.insertBefore(n.createTextNode(Z),Ce.childNodes[0]||null),ci===Xt?R.call(D,pe?"html":"body")[0]:pe?D.documentElement:Ce},b_=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)},Ms=function(C){return C=Vi(C,ge," "),C=Vi(C,le," "),C=Vi(C,ce," "),C},ku=function(C){var D;C.normalize();const Z=H.call(C.ownerDocument||C,C,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let ie=Z.nextNode();for(;ie;)ie.data=Ms(ie.data),ie=Z.nextNode();const Ce=(D=C.querySelectorAll)===null||D===void 0?void 0:D.call(C,"template");Ce&&Ki(Ce,Ae=>{di(Ae.content)&&ku(Ae.content)})},Os=function(C){const D=T?T(C):null;return typeof D!="string"||Be(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)},di=function(C){if(!S||typeof C!="object"||C===null)return!1;try{return S(C)===Vt.documentFragment}catch{return!1}},To=function(C){if(!S||typeof C!="object"||C===null)return!1;try{return typeof S(C)=="number"}catch{return!1}};function fn(ee,C,D){ee.length!==0&&Ki(ee,Z=>{Z.call(t,C,D,li)})}const xO=function(C,D){return!!(Mt&&C.hasChildNodes()&&!To(C.firstElementChild)&&Qe(yv,C.textContent)&&Qe(yv,C.innerHTML)||Mt&&C.namespaceURI===Xt&&D==="style"&&To(C.firstElementChild)||C.nodeType===Vt.processingInstruction||Mt&&C.nodeType===Vt.comment&&Qe(LA,C.data))},PO=function(C,D){if(!qe[D]&&S_(D)&&(oe.tagNameCheck instanceof RegExp&&Qe(oe.tagNameCheck,D)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(D)))return!1;if(vu&&!Yt[D]){const Z=v(C),ie=h(C);if(ie&&Z){const Ce=ie.length;for(let Ae=Ce-1;Ae>=0;--Ae){const Oe=yu?ie[Ae]:m(ie[Ae],!0);Z.insertBefore(Oe,g(C))}}}return Bn(C),!0},__=function(C){if(fn(V.beforeSanitizeElements,C,null),Os(C))return Bn(C),!0;const D=Be(T?T(C):C.nodeName);if(fn(V.uponSanitizeElement,C,{tagName:D,allowedTags:Q}),xO(C,D))return Bn(C),!0;if(qe[D]||!(tt.tagCheck instanceof Function&&tt.tagCheck(D))&&!Q[D])return PO(C,D);if((S?S(C):C.nodeType)===Vt.element&&!TO(C)||(D==="noscript"||D==="noembed"||D==="noframes")&&Qe($A,C.innerHTML))return Bn(C),!0;if(nt&&C.nodeType===Vt.text){const Z=Ms(C.textContent);C.textContent!==Z&&(zr(t.removed,{element:C.cloneNode()}),C.textContent=Z)}return fn(V.afterSanitizeElements,C,null),!1},w_=function(C,D,Z){if(Me[D]||ht&&(D==="id"||D==="name")&&(Z in n||Z in _O))return!1;const ie=ue[D]||tt.attributeCheck instanceof Function&&tt.attributeCheck(D,C);if(!(Lt&&Qe(be,D))){if(!(pn&&Qe(Y,D))){if(ie){if(!_u[D]){if(!Qe(he,Vi(Z,X,""))){if(!((D==="src"||D==="xlink:href"||D==="href")&&C!=="script"&&dv(Z,"data:")===0&&l_[C])){if(!(Nt&&!Qe(fe,Vi(Z,X,"")))){if(Z)return!1}}}}}else if(!(S_(C)&&(oe.tagNameCheck instanceof RegExp&&Qe(oe.tagNameCheck,C)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(C))&&(oe.attributeNameCheck instanceof RegExp&&Qe(oe.attributeNameCheck,D)||oe.attributeNameCheck instanceof Function&&oe.attributeNameCheck(D,C))||D==="is"&&oe.allowCustomizedBuiltInElements&&(oe.tagNameCheck instanceof RegExp&&Qe(oe.tagNameCheck,Z)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(Z))))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"]),S_=function(C){return!EO[qi(C)]&&Qe(_e,C)},AO=function(C,D,Z,ie){if(N&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!Z)switch(u.getAttributeType(C,D)){case"TrustedHTML":return G(ie);case"TrustedScriptURL":return E(ie)}return ie},IO=function(C,D,Z,ie){try{Z?C.setAttributeNS(Z,D,ie):C.setAttribute(D,ie),Os(C)?Bn(C):cv(t.removed)}catch{_r(D,C)}},C_=function(C){fn(V.beforeSanitizeAttributes,C,null);const D=C.attributes;if(!D||Os(C))return;const Z={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ue,forceKeepAttr:void 0};let ie=D.length;const Ce=Be(C.nodeName);for(;ie--;){const Ae=D[ie],Oe=Ae.name,kt=Ae.namespaceURI,hn=Ae.value,Ot=Be(Oe),Pu=hn;let mt=Oe==="value"?Pu:gA(Pu);if(Z.attrName=Ot,Z.attrValue=mt,Z.keepAttr=!0,Z.forceKeepAttr=void 0,fn(V.uponSanitizeAttribute,C,Z),mt=Z.attrValue,Fn&&(Ot==="id"||Ot==="name")&&dv(mt,c_)!==0&&(_r(Oe,C),mt=c_+mt),Mt&&Qe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,mt)){_r(Oe,C);continue}if(Ot==="attributename"&&lv(mt,"href")){_r(Oe,C);continue}if(!Z.forceKeepAttr){if(!Z.keepAttr){_r(Oe,C);continue}if(!$t&&Qe(MA,mt)){_r(Oe,C);continue}if(nt&&(mt=Ms(mt)),!w_(Ce,Ot,mt)){_r(Oe,C);continue}mt=AO(Ce,Ot,kt,mt),mt!==Pu&&IO(C,Oe,kt,mt)}}fn(V.afterSanitizeAttributes,C,null)},js=function(C){let D=null;const Z=b_(C);for(fn(V.beforeSanitizeShadowDOM,C,null);D=Z.nextNode();)if(fn(V.uponSanitizeShadowNode,D,null),__(D),C_(D),di(D.content)&&js(D.content),(S?S(D):D.nodeType)===Vt.element){const ie=b(D);di(ie)&&(xu(ie),js(ie))}fn(V.afterSanitizeShadowDOM,C,null)},xu=function(C){const D=[{node:C,shadow:null}];for(;D.length>0;){const Z=D.pop();if(Z.shadow){js(Z.shadow);continue}const ie=Z.node,Ce=(S?S(ie):ie.nodeType)===Vt.element,Ae=h(ie);if(Ae)for(let Oe=Ae.length-1;Oe>=0;--Oe)D.push({node:Ae[Oe],shadow:null});if(Ce){const Oe=T?T(ie):null;if(typeof Oe=="string"&&Be(Oe)==="template"){const kt=ie.content;di(kt)&&D.push({node:kt,shadow:null})}}if(Ce){const Oe=b(ie);di(Oe)&&D.push({node:null,shadow:Oe},{node:Oe,shadow:null})}}};return t.sanitize=function(ee){let C=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},D=null,Z=null,ie=null,Ce=null;if(wu=!ee,wu&&(ee="<!-->"),typeof ee!="string"&&!To(ee)&&(ee=wA(ee),typeof ee!="string"))throw or("dirty is not a string, aborting");if(!t.isSupported)return ee;ae?(Q=Ge,ue=On):Nu(C),(V.uponSanitizeElement.length>0||V.uponSanitizeAttribute.length>0)&&(Q=ut(Q)),V.uponSanitizeAttribute.length>0&&(ue=ut(ue)),t.removed=[];const Ae=yu&&typeof ee!="string"&&To(ee);if(Ae){const hn=T?T(ee):ee.nodeName;if(typeof hn=="string"){const Ot=Be(hn);if(!Q[Ot]||qe[Ot])throw or("root node is forbidden and cannot be sanitized in-place")}if(Os(ee))throw or("root node is clobbered and cannot be sanitized in-place");try{xu(ee)}catch(Ot){throw v_(ee),Ot}}else if(To(ee))D=y_("<!---->"),Z=D.ownerDocument.importNode(ee,!0),Z.nodeType===Vt.element&&Z.nodeName==="BODY"||Z.nodeName==="HTML"?D=Z:D.appendChild(Z),xu(Z);else{if(!mn&&!nt&&!pe&&ee.indexOf("<")===-1)return N&&jn?G(ee):ee;if(D=y_(ee),!D)return mn?null:jn?P:""}D&&So&&Bn(D.firstChild);const Oe=b_(Ae?ee:D);try{for(;ie=Oe.nextNode();)__(ie),C_(ie),di(ie.content)&&js(ie.content)}catch(hn){throw Ae&&v_(ee),hn}if(Ae)return Ki(t.removed,hn=>{hn.element&&kO(hn.element)}),nt&&ku(ee),ee;if(mn){if(nt&&ku(D),br)for(Ce=k.call(D.ownerDocument);D.firstChild;)Ce.appendChild(D.firstChild);else Ce=D;return(ue.shadowroot||ue.shadowrootmode)&&(Ce=j.call(r,Ce,!0)),Ce}let kt=pe?D.outerHTML:D.innerHTML;return pe&&Q["!doctype"]&&D.ownerDocument&&D.ownerDocument.doctype&&D.ownerDocument.doctype.name&&Qe(RA,D.ownerDocument.doctype.name)&&(kt="<!DOCTYPE "+D.ownerDocument.doctype.name+`>
|
|
48
|
+
`+kt),nt&&(kt=Ms(kt)),N&&jn?G(kt):kt},t.setConfig=function(){Nu(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),ae=!0,Ge=Q,On=ue},t.clearConfig=function(){li=null,ae=!1,Ge=null,On=null,N=A,P=""},t.isValidAttribute=function(ee,C,D){return li||Nu({}),w_(Be(ee),Be(C),D)},t.addHook=function(ee,C){typeof C=="function"&&We(V,ee)&&zr(V[ee],C)},t.removeHook=function(ee,C){if(We(V,ee)){if(C!==void 0){const D=fA(V[ee],C);return D===-1?void 0:hA(V[ee],D,1)[0]}return cv(V[ee])}},t.removeHooks=function(ee){We(V,ee)&&(V[ee]=[])},t.removeAllHooks=function(){V=bv()},t}var wv=_v();function ed(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ar=ed();function Sv(e){ar=e}var sr={exec:()=>null};function Jr(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(ot.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,t)};return r}var FA=((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:Jr(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Jr(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Jr(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Jr(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Jr(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Jr(e=>new RegExp(`^ {0,${e}}>`))},BA=/^(?:[ \t]*(?:\n|$))+/,UA=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,GA=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,zi=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,HA=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,td=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Cv=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Tv=Ne(Cv).replace(/bull/g,td).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(),KA=Ne(Cv).replace(/bull/g,td).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(),nd=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,qA=/^[^\n]+/,rd=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,VA=Ne(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",rd).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),WA=Ne(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,td).getRegex(),Qa="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",id=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,zA=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",id).replace("tag",Qa).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Nv=Ne(nd).replace("hr",zi).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",Qa).getRegex(),od={blockquote:Ne(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Nv).getRegex(),code:UA,def:VA,fences:GA,heading:HA,hr:zi,html:zA,lheading:Tv,list:WA,newline:BA,paragraph:Nv,table:sr,text:qA},kv=Ne("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",zi).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",Qa).getRegex(),JA={...od,lheading:KA,table:kv,paragraph:Ne(nd).replace("hr",zi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",kv).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",Qa).getRegex()},YA={...od,html:Ne(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",id).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(nd).replace("hr",zi).replace("heading",` *#{1,6} *[^
|
|
49
|
+
]`).replace("lheading",Tv).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},XA=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,QA=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,xv=/^( {2,}|\\)\n(?!\s*$)/,ZA=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Yr=/[\p{P}\p{S}]/u,Za=/[\s\p{P}\p{S}]/u,ad=/[^\s\p{P}\p{S}]/u,eI=Ne(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Za).getRegex(),Pv=/(?!~)[\p{P}\p{S}]/u,tI=/(?!~)[\s\p{P}\p{S}]/u,nI=/(?:[^\s\p{P}\p{S}]|~)/u,rI=Ne(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",FA?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ev=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,iI=Ne(Ev,"u").replace(/punct/g,Yr).getRegex(),oI=Ne(Ev,"u").replace(/punct/g,Pv).getRegex(),Av="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",aI=Ne(Av,"gu").replace(/notPunctSpace/g,ad).replace(/punctSpace/g,Za).replace(/punct/g,Yr).getRegex(),sI=Ne(Av,"gu").replace(/notPunctSpace/g,nI).replace(/punctSpace/g,tI).replace(/punct/g,Pv).getRegex(),cI=Ne("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ad).replace(/punctSpace/g,Za).replace(/punct/g,Yr).getRegex(),lI=Ne(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Yr).getRegex(),dI=Ne("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,ad).replace(/punctSpace/g,Za).replace(/punct/g,Yr).getRegex(),uI=Ne(/\\(punct)/,"gu").replace(/punct/g,Yr).getRegex(),pI=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(),mI=Ne(id).replace("(?:-->|$)","-->").getRegex(),fI=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",mI).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),es=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,hI=Ne(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",es).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Iv=Ne(/^!?\[(label)\]\[(ref)\]/).replace("label",es).replace("ref",rd).getRegex(),Rv=Ne(/^!?\[(ref)\](?:\[\])?/).replace("ref",rd).getRegex(),gI=Ne("reflink|nolink(?!\\()","g").replace("reflink",Iv).replace("nolink",Rv).getRegex(),Dv=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,sd={_backpedal:sr,anyPunctuation:uI,autolink:pI,blockSkip:rI,br:xv,code:QA,del:sr,delLDelim:sr,delRDelim:sr,emStrongLDelim:iI,emStrongRDelimAst:aI,emStrongRDelimUnd:cI,escape:XA,link:hI,nolink:Rv,punctuation:eI,reflink:Iv,reflinkSearch:gI,tag:fI,text:ZA,url:sr},vI={...sd,link:Ne(/^!?\[(label)\]\((.*?)\)/).replace("label",es).getRegex(),reflink:Ne(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",es).getRegex()},cd={...sd,emStrongRDelimAst:sI,emStrongLDelim:oI,delLDelim:lI,delRDelim:dI,url:Ne(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Dv).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",Dv).getRegex()},yI={...cd,br:Ne(xv).replace("{2,}","*").getRegex(),text:Ne(cd.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ts={normal:od,gfm:JA,pedantic:YA},Ji={normal:sd,gfm:cd,breaks:yI,pedantic:vI},bI={"&":"&","<":"<",">":">",'"':""","'":"'"},Lv=e=>bI[e];function Wt(e,t){if(t){if(ot.escapeTest.test(e))return e.replace(ot.escapeReplace,Lv)}else if(ot.escapeTestNoEncode.test(e))return e.replace(ot.escapeReplaceNoEncode,Lv);return e}function $v(e){try{e=encodeURI(e).replace(ot.percentDecode,"%")}catch{return null}return e}function Mv(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 An(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 Ov(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
51
|
`)}function _I(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 wI(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 jv(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 SI(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
53
|
`)}var ns=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]:Ov(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=SI(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=An(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:An(t[0],`
|
|
@@ -75,8 +75,8 @@ ${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
75
75
|
`):[],o={type:"table",raw:An(t[0],`
|
|
76
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(Mv(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:An(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=An(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=_I(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)),jv(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 jv(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 Eu{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 ns,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:
|
|
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(
|
|
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=An(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=_I(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)),jv(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 jv(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 Eu{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 ns,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:ts.normal,inline:Ji.normal};this.options.pedantic?(n.block=ts.pedantic,n.inline=Ji.pedantic):this.options.gfm&&(n.block=ts.gfm,this.options.breaks?n.inline=Ji.breaks:n.inline=Ji.gfm),this.tokenizer.rules=n}static get rules(){return{block:ts,inline:Ji}}static lex(t,n){return new Eu(n).lex(t)}static lexInline(t,n){return new Eu(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+=`
|
|
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(g=>{f=g.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)}},rs=class{options;parser;constructor(e){this.options=e||ar}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(
|
|
93
|
-
`;return r?'<pre><code class="language-'+
|
|
94
|
-
`:"<pre><code>"+(n?i:
|
|
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(g=>{f=g.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)}},rs=class{options;parser;constructor(e){this.options=e||ar}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-'+Wt(r)+'">'+(n?i:Wt(i,!0))+`</code></pre>
|
|
94
|
+
`:"<pre><code>"+(n?i:Wt(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>${
|
|
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 CI;function Pe(e,t){return cr.parse(e,t)}Pe.options=Pe.setOptions=function(e){return cr.setOptions(e),Pe.defaults=cr.defaults,Sv(Pe.defaults),Pe},Pe.getDefaults=ed,Pe.defaults=ar,Pe.use=function(...e){return cr.use(...e),Pe.defaults=cr.defaults,Sv(Pe.defaults),Pe},Pe.walkTokens=function(e,t){return cr.walkTokens(e,t)},Pe.parseInline=cr.parseInline,Pe.Parser=Dt,Pe.parser=Dt.parse,Pe.Renderer=rs,Pe.TextRenderer=ld,Pe.Lexer=Rt,Pe.lexer=Rt.lex,Pe.Tokenizer=ns,Pe.Hooks=Yi,Pe.parse=Pe;var zO=Pe.options,JO=Pe.setOptions,YO=Pe.use,XO=Pe.walkTokens,QO=Pe.parseInline,ZO=Pe,ej=Dt.parse,tj=Rt.lex,TI={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 NI(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:")}wv.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(NI(e.getAttribute("href")||"")?(e.setAttribute("rel","noopener noreferrer"),e.setAttribute("target","_blank")):e.removeAttribute("href"))});function dd(e){const t=Pe.parse(String(e||""),{async:!1});return wv.sanitize(t,TI)}function kI(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"},fE(r)),y("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:dd(i)}})):null}).filter(Boolean)}function xI(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:dd(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 Fv(e,t="feed-body"){const n=String(e||"").trim();return n?y("div",{className:t,dangerouslySetInnerHTML:{__html:dd(n)}}):null}function PI(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 is(e,t){return String(e?.kind||"").toLowerCase()==="session_summary"||t?.is_summary===!0?!0:String(t?.source||"").trim().toLowerCase()==="observer_summary"}function EI(e,t){const n=String(e?.kind||"").trim().toLowerCase();return is(e,t)?"session_summary":n||"change"}var ud=["Enter"," "],AI=["ArrowDown","PageUp","Home"],Bv=["ArrowUp","PageDown","End"],II=[...AI,...Bv],RI={ltr:[...ud,"ArrowRight"],rtl:[...ud,"ArrowLeft"]},DI={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Xi="Menu",[Qi,LI,$I]=da(Xi),[lr,Uv]=st(Xi,[$I,Sn,Lr]),Zi=Sn(),Gv=Lr(),[Hv,In]=lr(Xi),[MI,eo]=lr(Xi),Kv=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:o,modal:s=!0}=e,c=Zi(t),[l,d]=I(null),u=B(!1),p=lt(o),m=Di(i);return K(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),a(Oi,{...c,children:a(Hv,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:a(MI,{scope:t,onClose:re(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:m,modal:s,children:r})})})};Kv.displayName=Xi;var OI="MenuAnchor",pd=F((e,t)=>{const{__scopeMenu:n,...r}=e,i=Zi(n);return a(ji,{...i,...r,ref:t})});pd.displayName=OI;var md="MenuPortal",[jI,qv]=lr(md,{forceMount:void 0}),Wv=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,o=In(md,t);return a(jI,{scope:t,forceMount:n,children:a(nt,{present:n||o.open,children:a(qn,{asChild:!0,container:i,children:r})})})};Wv.displayName=md;var St="MenuContent",[FI,fd]=lr(St),Vv=F((e,t)=>{const n=qv(St,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,o=In(St,e.__scopeMenu),s=eo(St,e.__scopeMenu);return a(Qi.Provider,{scope:e.__scopeMenu,children:a(nt,{present:r||o.open,children:a(Qi.Slot,{scope:e.__scopeMenu,children:s.modal?a(BI,{...i,ref:t}):a(UI,{...i,ref:t})})})})}),BI=F((e,t)=>{const n=In(St,e.__scopeMenu),r=B(null),i=we(t,r);return K(()=>{const o=r.current;if(o)return Jo(o)},[]),a(hd,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:z(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),UI=F((e,t)=>{const n=In(St,e.__scopeMenu);return a(hd,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),GI=Hn("MenuContent.ScrollLock"),hd=F((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:g,...h}=e,v=In(St,n),b=eo(St,n),w=Zi(n),S=Gv(n),T=LI(n),[N,P]=I(null),A=B(null),M=we(t,A,v.onContentChange),U=B(0),x=B(""),G=B(0),E=B(null),$=B("right"),L=B(0),J=g?_i:te,H=g?{as:GI,allowPinchZoom:!0}:void 0,k=j=>{const W=x.current+j,ge=T().filter(fe=>!fe.disabled),le=document.activeElement,ce=ge.find(fe=>fe.ref.current===le)?.textValue,be=tR(ge.map(fe=>fe.textValue),W,ce),Y=ge.find(fe=>fe.textValue===be)?.ref.current;(function fe(X){x.current=X,window.clearTimeout(U.current),X!==""&&(U.current=window.setTimeout(()=>fe(""),1e3))})(W),Y&&setTimeout(()=>Y.focus())};K(()=>()=>window.clearTimeout(U.current),[]),Uo();const R=re(j=>$.current===E.current?.side&&rR(j,E.current?.area),[]);return a(FI,{scope:n,searchRef:x,onItemEnter:re(j=>{R(j)&&j.preventDefault()},[R]),onItemLeave:re(j=>{R(j)||(A.current?.focus(),P(null))},[R]),onTriggerLeave:re(j=>{R(j)&&j.preventDefault()},[R]),pointerGraceTimerRef:G,onPointerGraceIntentChange:re(j=>{E.current=j},[]),children:a(J,{...H,children:a(yi,{asChild:!0,trapped:i,onMountAutoFocus:z(o,j=>{j.preventDefault(),A.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:a(Kn,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:m,onDismiss:f,children:a(Jc,{asChild:!0,...S,dir:b.dir,orientation:"vertical",loop:r,currentTabStopId:N,onCurrentTabStopIdChange:P,onEntryFocus:z(l,j=>{b.isUsingKeyboardRef.current||j.preventDefault()}),preventScrollOnEntryFocus:!0,children:a(Ea,{role:"menu","aria-orientation":"vertical","data-state":dy(v.open),"data-radix-menu-content":"",dir:b.dir,...w,...h,ref:M,style:{outline:"none",...h.style},onKeyDown:z(h.onKeyDown,j=>{const W=j.target.closest("[data-radix-menu-content]")===j.currentTarget,ge=j.ctrlKey||j.altKey||j.metaKey,le=j.key.length===1;W&&(j.key==="Tab"&&j.preventDefault(),!ge&&le&&k(j.key));const ce=A.current;if(j.target!==ce||!II.includes(j.key))return;j.preventDefault();const be=T().filter(Y=>!Y.disabled).map(Y=>Y.ref.current);Bv.includes(j.key)&&be.reverse(),ZI(be)}),onBlur:z(e.onBlur,j=>{j.currentTarget.contains(j.target)||(window.clearTimeout(U.current),x.current="")}),onPointerMove:z(e.onPointerMove,no(j=>{const W=j.target,ge=L.current!==j.clientX;j.currentTarget.contains(W)&&ge&&($.current=j.clientX>L.current?"right":"left",L.current=j.clientX)}))})})})})})})});Vv.displayName=St;var HI="MenuGroup",gd=F((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{role:"group",...r,ref:t})});gd.displayName=HI;var KI="MenuLabel",zv=F((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{...r,ref:t})});zv.displayName=KI;var os="MenuItem",Jv="menu.itemSelect",as=F((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,o=B(null),s=eo(os,e.__scopeMenu),c=fd(os,e.__scopeMenu),l=we(t,o),d=B(!1),u=()=>{const p=o.current;if(!n&&p){const m=new CustomEvent(Jv,{bubbles:!0,cancelable:!0});p.addEventListener(Jv,f=>r?.(f),{once:!0}),uc(p,m),m.defaultPrevented?d.current=!1:s.onClose()}};return a(Yv,{...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===" "||ud.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});as.displayName=os;var Yv=F((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...o}=e,s=fd(os,n),c=Gv(n),l=B(null),d=we(t,l),[u,p]=I(!1),[m,f]=I("");return K(()=>{const g=l.current;g&&f((g.textContent??"").trim())},[o.children]),a(Qi.ItemSlot,{scope:n,disabled:r,textValue:i??m,children:a(Yc,{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,no(g=>{r?s.onItemLeave(g):(s.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:z(e.onPointerLeave,no(g=>s.onItemLeave(g))),onFocus:z(e.onFocus,()=>p(!0)),onBlur:z(e.onBlur,()=>p(!1))})})})}),qI="MenuCheckboxItem",Xv=F((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return a(ny,{scope:e.__scopeMenu,checked:n,children:a(as,{role:"menuitemcheckbox","aria-checked":ss(n)?"mixed":n,...i,ref:t,"data-state":bd(n),onSelect:z(i.onSelect,()=>r?.(ss(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Xv.displayName=qI;var Qv="MenuRadioGroup",[WI,VI]=lr(Qv,{value:void 0,onValueChange:()=>{}}),Zv=F((e,t)=>{const{value:n,onValueChange:r,...i}=e,o=lt(r);return a(WI,{scope:e.__scopeMenu,value:n,onValueChange:o,children:a(gd,{...i,ref:t})})});Zv.displayName=Qv;var ey="MenuRadioItem",ty=F((e,t)=>{const{value:n,...r}=e,i=VI(ey,e.__scopeMenu),o=n===i.value;return a(ny,{scope:e.__scopeMenu,checked:o,children:a(as,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":bd(o),onSelect:z(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});ty.displayName=ey;var vd="MenuItemIndicator",[ny,zI]=lr(vd,{checked:!1}),ry=F((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,o=zI(vd,n);return a(nt,{present:r||ss(o.checked)||o.checked===!0,children:a(se.span,{...i,ref:t,"data-state":bd(o.checked)})})});ry.displayName=vd;var JI="MenuSeparator",iy=F((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});iy.displayName=JI;var YI="MenuArrow",oy=F((e,t)=>{const{__scopeMenu:n,...r}=e,i=Zi(n);return a(Aa,{...i,...r,ref:t})});oy.displayName=YI;var yd="MenuSub",[XI,ay]=lr(yd),QI=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:i}=e,o=In(yd,t),s=Zi(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(Oi,{...s,children:a(Hv,{scope:t,open:r,onOpenChange:p,content:d,onContentChange:u,children:a(XI,{scope:t,contentId:ct(),triggerId:ct(),trigger:c,onTriggerChange:l,children:n})})})};QI.displayName=yd;var to="MenuSubTrigger",sy=F((e,t)=>{const n=In(to,e.__scopeMenu),r=eo(to,e.__scopeMenu),i=ay(to,e.__scopeMenu),o=fd(to,e.__scopeMenu),s=B(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(pd,{asChild:!0,...d,children:a(Yv,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":dy(n.open),...e,ref:Fo(t,i.onTriggerChange),onClick:p=>{e.onClick?.(p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:z(e.onPointerMove,no(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,no(p=>{u();const m=n.content?.getBoundingClientRect();if(m){const f=n.content?.dataset.side,g=f==="right",h=g?-5:5,v=m[g?"left":"right"],b=m[g?"right":"left"];o.onPointerGraceIntentChange({area:[{x:p.clientX+h,y:p.clientY},{x:v,y:m.top},{x:b,y:m.top},{x:b,y:m.bottom},{x:v,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===" "||RI[r.dir].includes(p.key)&&(n.onOpenChange(!0),n.content?.focus(),p.preventDefault())})})})});sy.displayName=to;var cy="MenuSubContent",ly=F((e,t)=>{const n=qv(St,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,o=In(St,e.__scopeMenu),s=eo(St,e.__scopeMenu),c=ay(cy,e.__scopeMenu),l=B(null),d=we(t,l);return a(Qi.Provider,{scope:e.__scopeMenu,children:a(nt,{present:r||o.open,children:a(Qi.Slot,{scope:e.__scopeMenu,children:a(hd,{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=DI[s.dir].includes(u.key);p&&m&&(o.onOpenChange(!1),c.trigger?.focus(),u.preventDefault())})})})})})});ly.displayName=cy;function dy(e){return e?"open":"closed"}function ss(e){return e==="indeterminate"}function bd(e){return ss(e)?"indeterminate":e?"checked":"unchecked"}function ZI(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function eR(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function tR(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=eR(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 nR(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 rR(e,t){return t?nR({x:e.clientX,y:e.clientY},t):!1}function no(e){return t=>t.pointerType==="mouse"?e(t):void 0}var iR=Kv,oR=pd,aR=Wv,sR=Vv,cR=gd,lR=zv,dR=as,uR=Xv,pR=Zv,mR=ty,fR=ry,hR=iy,gR=oy,vR=sy,yR=ly,cs="DropdownMenu",[bR,nj]=st(cs,[Uv]),pt=Uv(),[_R,uy]=bR(cs),py=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:o,onOpenChange:s,modal:c=!0}=e,l=pt(t),d=B(null),[u,p]=wt({prop:i,defaultProp:o??!1,onChange:s,caller:cs});return a(_R,{scope:t,triggerId:ct(),triggerRef:d,contentId:ct(),open:u,onOpenChange:p,onOpenToggle:re(()=>p(m=>!m),[p]),modal:c,children:a(iR,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})};py.displayName=cs;var my="DropdownMenuTrigger",fy=F((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,o=uy(my,n),s=pt(n);return a(oR,{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:Fo(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())})})})});fy.displayName=my;var wR="DropdownMenuPortal",hy=e=>{const{__scopeDropdownMenu:t,...n}=e,r=pt(t);return a(aR,{...r,...n})};hy.displayName=wR;var gy="DropdownMenuContent",vy=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=uy(gy,n),o=pt(n),s=B(!1);return a(sR,{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)"}})});vy.displayName=gy;var SR="DropdownMenuGroup",CR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(cR,{...i,...r,ref:t})});CR.displayName=SR;var TR="DropdownMenuLabel",NR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(lR,{...i,...r,ref:t})});NR.displayName=TR;var kR="DropdownMenuItem",yy=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(dR,{...i,...r,ref:t})});yy.displayName=kR;var xR="DropdownMenuCheckboxItem",PR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(uR,{...i,...r,ref:t})});PR.displayName=xR;var ER="DropdownMenuRadioGroup",AR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(pR,{...i,...r,ref:t})});AR.displayName=ER;var IR="DropdownMenuRadioItem",RR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(mR,{...i,...r,ref:t})});RR.displayName=IR;var DR="DropdownMenuItemIndicator",LR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(fR,{...i,...r,ref:t})});LR.displayName=DR;var $R="DropdownMenuSeparator",MR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(hR,{...i,...r,ref:t})});MR.displayName=$R;var OR="DropdownMenuArrow",jR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(gR,{...i,...r,ref:t})});jR.displayName=OR;var FR="DropdownMenuSubTrigger",BR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(vR,{...i,...r,ref:t})});BR.displayName=FR;var UR="DropdownMenuSubContent",GR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(yR,{...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)"}})});GR.displayName=UR;var HR=py,KR=fy,qR=hy,WR=vy,by=yy;function VR({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return y(HR,null,y(KR,{asChild:!0},y("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),y(qR,null,y(WR,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},y(by,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),y(by,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function zR({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 _d({label:e,variant:t=""}){return y(Wl,{variant:"provenance",tone:t||void 0},e)}function JR({tag:e}){const t=qg(e);return t?y(Wl,{variant:"tag",title:String(e)},t):null}function YR({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const o=Ka(e?.metadata_json),s=is(e,o),c=EI(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=uE(p),f=Ha(e.tags||[]),g=Ha(e.files||[]),h=e.project||"",v=SE(e),b=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(),N=String(e.trust_state||o?.trust_state||"").trim(),P=f.length?` · ${f.map(pe=>qg(pe)).join(", ")}`:"",A=g.length?` · ${hE(g)}`:"",M=Number(e.id||0),U=M>0?`ID ${M}`:"",[x,G]=I(_.newItemKeys.has(l)),E=s?PI({...e,metadata_json:o}):null,$=s?null:QE({...e,metadata_json:o}),L=$?ZE($):[],J=$?eA($):"summary",H=_.itemViewState.get(l),[k,R]=I($&&H&&L.some(pe=>pe.id===H)?H:J),j=`${l}:${k}`,[W,ge]=I(_.itemExpandState.get(j)===!0),[le,ce]=I(b==="shared"?"shared":"private"),[be,Y]=I(!1),[fe,X]=I(!1),[_e,he]=I(!1),Q=E?kI(E):[];K(()=>{$&&(L.some(pe=>pe.id===k)||R(J))},[k,J,L,$]),K(()=>{_.itemViewState.set(l,k)},[k,l]),K(()=>{const pe=`${l}:${k}`;ge(_.itemExpandState.get(pe)===!0)},[k,l]),K(()=>{ce(b==="shared"?"shared":"private")},[b]),K(()=>{if(!x)return;const pe=window.setTimeout(()=>{_.newItemKeys.delete(l),G(!1)},700);return()=>window.clearTimeout(pe)},[x,l]);const $e=le,ue=$e==="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.",q=[h?`Project ${h}`:"No project",m].filter(Boolean).join(" · "),oe=[w&&w!==b?`Workspace ${w}`:"",S?`From ${S}`:"",T&&v!=="You"?`Device ${T}`:"",N&&N!=="trusted"?wE(N):""].filter(Boolean).join(" · "),qe=[`${P}${A}`.trim(),oe].filter(Boolean).join(" · "),Me=!!$&&tA(k,$),et=[k==="facts"?"feed-body facts":"feed-body",Me&&!W?nA(k).join(" "):""].filter(Boolean).join(" "),pn=s?Q.length?y("div",{className:"feed-body facts"},Q):Fv(String(e.body_text||""))||y("div",{className:"feed-body"}):$?k==="facts"?xI($.facts)||y("div",{className:et}):Fv(k==="narrative"?$.narrative:$.summary,et)||y("div",{className:et}):y("div",{className:"feed-body"});async function Lt(pe){const ae=$e;ce(pe),Y(!0);try{const Ge=await H_(M,pe);Ge?.item&&(t(Ge.item),r()),ne(pe==="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 Nt(){const pe=String(e.project||"").trim(),ae=pe,Ge=String(u||"this memory").trim(),On=Ge.length>80?`${Ge.slice(0,79).trimEnd()}…`:Ge,So=pe?`Move "${On}" from "${pe}" 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 "${On}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`;let mn=[];try{mn=(await ko()).filter(ht=>ht&&ht!==pe)}catch{}const br=await Rl({title:"Assign to project",description:So,initialValue:ae,placeholder:"Pick one or type a new project name",suggestions:mn,confirmLabel:"Move",cancelLabel:"Cancel",validate:ht=>{const Fn=ht.trim();return Fn?Fn===pe?"Already assigned to this project.":null:"Enter a project name."}});if(br==null)return;const jn=br.trim();if(!(!jn||jn===pe)){he(!0);try{const ht=await K_(M,jn),Fn=Number(ht.moved_memory_count||1);ne(Fn>1?`Moved ${Fn} 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{he(!1)}}}async function $t(){const pe=String(u||"this memory").trim();if(await Kt({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${pe.length>80?`${pe.slice(0,79).trimEnd()}…`:pe}". 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"})){X(!0);try{await q_(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{X(!1)}}}const tt=c.replace(/_/g," "),Mt=g.length?y("div",{className:"feed-files"},g.map((pe,ae)=>y("span",{className:"feed-file",key:`${String(pe)}-${ae}`},String(pe)))):null;return y("article",{className:`feed-item ${c}${x?" new-item":""}`.trim(),"data-key":l},y("div",{className:"feed-kind-banner"},y(Wl,{variant:"kind",tone:c},tt)),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:YT(u,_.feedQuery)}}),y("div",{className:"feed-card-subtitle small"},q)),y("div",{className:"feed-actions"},$?y(zR,{active:k,modes:L,onSelect:pe=>R(pe)}):null,y(Ja,{label:dE(p),side:"left"},y("div",{className:"small feed-age"},m)),e.owned_by_self&&M>0?y(VR,{assignProjectDisabled:_e,disabled:fe,onAssignProject:()=>{Nt()},onForget:()=>{$t()},title:String(u||"memory")}):null)),y("div",{className:"feed-provenance"},y(_d,{label:v,variant:v==="You"?"mine":"author"}),y(_d,{label:b||"private",variant:b||"private"}),U?y(Ja,{label:`Memory database id ${M}`,side:"top"},y(_d,{label:U,variant:"memory-id"})):null),y("div",{className:"feed-meta"},qe||"No tags, files, or provenance details attached."),pn,y("div",{className:"feed-footer"},y("div",{className:"feed-footer-left"},f.length?y("div",{className:"feed-tags"},f.map((pe,ae)=>y(JR,{key:`${String(pe)}-${ae}`,tag:pe}))):null,e.owned_by_self&&M>0?y("div",{className:"feed-visibility-controls"},y("select",{"aria-label":`Visibility for ${String(e.title||"memory")}`,className:"feed-visibility-select",disabled:be,onChange:pe=>{Lt(String(pe.currentTarget.value)==="shared"?"shared":"private")},value:$e},y("option",{value:"private"},"Only me"),y("option",{value:"shared"},"Share with peers")),y("div",{className:"feed-visibility-note"},ue)):null),y("div",{className:"feed-footer-right"},Me?y("button",{className:"feed-expand",onClick:()=>{const pe=!W;_.itemExpandState.set(j,pe),ge(pe)},type:"button"},W?"Collapse":"Expand"):null)),Mt))}function XR({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 QR({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(XR,{index:r,key:`skeleton-${r}`})));if(!e.length){const r=!!_.feedQuery.trim()||_.feedTypeFilter!=="all"||_.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(te,null,e.map(r=>y(YR,{item:r,key:ft(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function _y({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 ZR({items:e,loadingText:t,ops:n}){const[r,i]=I(!1);return y(te,null,y("div",{className:"feed-controls"},y("div",{className:"section-meta",id:"feedMeta"},t||rA(e.length,n.hasMorePages())),y("div",{className:"feed-controls-right"},y("input",{className:"feed-search",id:"feedSearch",onInput:o=>{_.feedQuery=String(o.currentTarget.value||""),n.updateFeedView()},placeholder:"Search title, body, tags…",value:_.feedQuery}),y(_y,{active:_.feedScopeFilter,id:"feedScopeToggle",onSelect:o=>{o!==_.feedScopeFilter&&(Pf(o),n.loadFeedData())},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),y(_y,{active:_.feedTypeFilter,id:"feedTypeToggle",onSelect:o=>{o!==_.feedTypeFilter&&(lN(o),n.updateFeedView())},options:[{value:"all",label:"All"},{value:"observations",label:"Observations"},{value:"summaries",label:"Summaries"}]}),y("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"))),y(iA,{open:r}),y("div",{className:"feed-list",id:"feedList"},y(QR,{items:e,loadingText:t,ops:n})))}function e0(e){return _.feedTypeFilter==="observations"?e.filter(t=>!is(t,Ka(t?.metadata_json))):_.feedTypeFilter==="summaries"?e.filter(t=>is(t,Ka(t?.metadata_json))):e}function t0(e){const t=It(_.feedQuery);return t?e.filter(n=>[It(n?.title),It(n?.body_text),It(n?.kind),Ha(n?.tags||[]).map(r=>It(r)).join(" "),It(n?.project)].join(" ").trim().includes(t)):e}function n0(e){const t=e.map(n=>`${Vg(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}`);return`${_.feedTypeFilter}|${_.feedScopeFilter}|${_.currentProject}|${It(_.feedQuery)}|${t.join("|")}`}var wy="",ro=0,io=0,oo=!0,ao=!0,wd=!1,Sy=!1,so=0,Sd="all";function r0(e){wy=e,Sd=_.feedScopeFilter,so+=1,ro=0,io=0,oo=!0,ao=!0,_.lastFeedItems=[],_.pendingFeedItems=null,_.lastFeedFilteredCount=0,_.lastFeedSignature="",_.newItemKeys.clear(),_.itemViewState.clear(),_.itemExpandState.clear()}function Cd(){return oo||ao}function i0(e){const t=ft(e);_.lastFeedItems=_.lastFeedItems.map(n=>ft(n)===t?e:n)}function o0(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(ft(r)),i};_.lastFeedItems=_.lastFeedItems.filter(n),Array.isArray(_.pendingFeedItems)&&(_.pendingFeedItems=_.pendingFeedItems.filter(n));for(const r of t){_.newItemKeys.delete(r),_.itemViewState.delete(r);for(const i of Array.from(_.itemExpandState.keys()))i.startsWith(`${r}:`)&&_.itemExpandState.delete(i)}}async function a0(){if(wd||!Cd())return;const e=_.currentProject||"",t=so,n=ro,r=io;wd=!0;try{const[i,o]=await Promise.all([oo?Mu(e,{limit:20,offset:n,scope:_.feedScopeFilter}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:n}}),ao?Ou(e,{limit:50,offset:r,scope:_.feedScopeFilter}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}})]);if(t!==so||e!==(_.currentProject||""))return;const s=o.items||[],c=i.items||[],l=c.filter(u=>!Wg(u));_.lastFeedFilteredCount+=c.length-l.length,ao=qa(o,s.length,50),oo=qa(i,c.length,20),io=Wa(o,r+s.length),ro=Wa(i,n+c.length);const d=[...s,...l];_.lastFeedItems=zg(_.lastFeedItems,d),co()}finally{wd=!1}}function Cy(){_.activeTab==="feed"&&Cd()&&TE()&&a0()}var s0={replaceFeedItem:i0,removeFeedItem:o0,updateFeedView:e=>co(e),loadFeedData:()=>Ty(),hasMorePages:Cd};function Td(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;JE(n,y(ZR,{items:e,loadingText:t?.loadingText,ops:s0}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function c0(){Td([],{loadingText:"Loading selected project..."})}function l0(){zE(),Td(_.lastFeedItems,_.lastFeedItems.length||_.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),Sy||(window.addEventListener("scroll",()=>{Cy()},{passive:!0}),Sy=!0)}function co(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=t0(e0(_.lastFeedItems)),r=n0(n),i=e||r!==_.lastFeedSignature;_.lastFeedSignature=r,i&&Td(n),window.scrollTo({top:t}),Cy()}async function Ty(){const e=_.currentProject||"",t=_.feedScopeFilter!==Sd;(e!==wy||t)&&(r0(e),c0());const n=so,r=20,i=50,[o,s]=await Promise.all([Mu(e,{limit:r,offset:0,scope:_.feedScopeFilter}),Ou(e,{limit:i,offset:0,scope:_.feedScopeFilter})]);if(n!==so||e!==(_.currentProject||""))return;const c=s.items||[],l=o.items||[],d=l.filter(g=>!Wg(g)),u=l.length-d.length,p=[...c,...d].sort((g,h)=>new Date(h.created_at||0).getTime()-new Date(g.created_at||0).getTime()),m=CE(_.lastFeedItems,p),f=_.lastFeedItems;if(NE(m,f)&&f.length>0){const g=new Set(f.map(ft));m.forEach(h=>{g.has(ft(h))||_.newItemKeys.add(ft(h))})}_.pendingFeedItems=null,_.lastFeedItems=m,_.lastFeedFilteredCount=Math.max(_.lastFeedFilteredCount,u),ao=qa(s,c.length,i),oo=qa(o,l.length,r),io=Math.max(io,Wa(s,c.length)),ro=Math.max(ro,Wa(o,l.length)),Sd=_.feedScopeFilter,co()}function rj(e){return e}function d0({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(Ja,{label:o},s):s}function u0({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||Ai(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 p0(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function m0({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"},p0(t)),y("div",{class:"label"},e)));return r?y(Ja,{label:r},i):i}function Ny(e,t){e&&Ue(y(Kl,null,t.map(n=>y(m0,{...n,key:`${n.label}-${n.icon}`}))),e)}function ky(e,t){e&&Ue(y(te,null,t),e)}function Nd(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function f0(e,t){e&&Ue(y(Kl,null,t.map(n=>y(d0,{...n,key:n.key??n.label}))),e)}function h0(e,t){if(e){if(!t.length){e.hidden=!0,Ue(null,e);return}e.hidden=!1,Ue(y(te,null,t.slice(0,3).map((n,r)=>y(u0,{item:n,key:`${n.label}-${r}`}))),e)}}var xy="scope_id_backfill";function Py(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthMeta"),n=document.getElementById("healthActions"),r=document.getElementById("healthDot");if(!e||!t)return;const i=_.lastStatsPayload||{},o=_.lastUsagePayload||{},s=_.lastRawEventsPayload&&typeof _.lastRawEventsPayload=="object"?_.lastRawEventsPayload:{},c=_.lastSyncStatus||{},l=Array.isArray(i.maintenance_jobs)?i.maintenance_jobs:[],d=l.find(oe=>oe.kind===xy),u=i.reliability||{},p=u.counts||{},m=u.rates||{},f=i.database||{},g=o.totals_filtered||o.totals||o.totals_global||i.usage?.totals||{},h=Array.isArray(o.recent_packs)?o.recent_packs:[],v=h.length?h[0]?.created_at:null,b=h.length?h[0]?.metadata_json||{}:{},w=Number(b?.exact_duplicates_collapsed||0),S=Number(s.pending||0),T=Number(p.errored_batches||0),N=Number(m.flush_success_rate??1),P=Number(m.dropped_event_rate||0),A=Fl(g.tokens_saved,g.tokens_read),M=mE(A),U=Number(f.tags_coverage||0),x=String(c.daemon_state||"unknown"),G=x==="offline-peers"?"Offline peers":x==="needs_attention"?"Needs attention":x==="rebootstrapping"?"Rebootstrapping":Kg(x),E=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers.length:0,$=x==="disabled"||c.enabled===!1,L=x==="offline-peers",J=!$&&E===0;let H=$?"Disabled":J?"No peers":G;const k=qr(c.last_sync_at||c.last_sync_at_utc||null),R=qr(v),j=k!==null&&k>7200,W=k!==null&&k<=300,ge=S>=200;let le=0;const ce=[];S>=1e3?(le+=40,ce.push("high raw-event backlog")):S>=200&&(le+=24,ce.push("growing raw-event backlog")),T>0&&S>=200&&(le+=T>=5?10:6,ce.push("batch errors during backlog pressure")),N<.95&&(le+=20,ce.push("lower flush success")),P>.02?(le+=24,ce.push("high dropped-event rate")):P>.005&&(le+=10,ce.push("non-trivial dropped-event rate")),!$&&!J&&(x==="error"?(le+=36,ce.push("sync daemon reports errors")):x==="needs_attention"?(le+=40,ce.push("sync needs manual attention")):x==="stopped"?(le+=22,ce.push("sync daemon stopped")):x==="degraded"&&!W&&(le+=20,ce.push("sync daemon degraded")),L?(le+=4,ce.push("all peers currently offline"),j&&(le+=4,ce.push("offline peers and sync not recent"))):j?(le+=26,ce.push("sync looks stale")):k!==null&&k>1800&&(le+=12,ce.push("sync not recent"))),M!==null&&M<10&&(le+=8,ce.push("low retrieval reduction")),R!==null&&R>86400&&(le+=12,ce.push("memory pack activity is old"));let be="Healthy",Y="status-healthy";le>=60?(be="Attention",Y="status-attention"):le>=25&&(be="Degraded",Y="status-degraded");const fe=Y==="status-healthy";r&&(r.className=`health-dot ${Y}`,r.title=be);const X=`${Number(g.tokens_saved||0).toLocaleString()} saved tokens · ${w.toLocaleString()} deduped in latest pack`,_e=S>0?"Queue is actively draining":"Queue is clear",he=$?"Sync disabled":J?"No peers configured":L?`${E} peers offline · last sync ${xn(k)} ago`:`${E} peers · last sync ${xn(k)} ago`;fe&&!$&&!J&&(L?H="Peers offline":x==="degraded"&&W&&(H="Syncing"));const Q=`last pack ${xn(R)} ago`,$e=l.map(oe=>{const qe=Number(oe.progress?.current||0),Me=typeof oe.progress?.total=="number"?oe.progress.total:null,et=String(oe.progress?.unit||"items"),pn=Me&&Me>0?` (${Math.round(100*qe/Me)}%)`:"",Lt=Me&&Me>0?`${qe.toLocaleString()}/${Me.toLocaleString()} ${et}${pn}`:`${qe.toLocaleString()} ${et}`,Nt=oe.status==="failed",$t=oe.status==="completed",tt=oe.kind===xy,Mt=Nt?"Failed":$t?"Complete":Lt,pe=Nt?String(oe.error||"unknown error").trim():$t?tt?`${Lt} · one-time Sharing-domain upgrade finished`:Lt:tt?"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:pe,icon:Nt?"alert-triangle":$t?"check-circle":"loader",className:Nt?"status-attention":void 0,title:Nt?`Error: ${oe.error||"unknown"}`:$t?`${String(oe.title||"Maintenance")} finished`:tt?`${String(oe.title||"Maintenance")} in progress; inspect with codemem maintenance status`:`${String(oe.title||"Maintenance")} in progress`}});f0(e,[{key:"overall-health",label:"Overall health",value:be,detail:`Weighted score ${le}`,icon:"heart-pulse",className:`health-primary ${Y}`,title:ce.length?`Main signals: ${ce.join(", ")}`:"No major risk signals detected"},...$e,{key:"pipeline-health",label:"Pipeline health",value:`${S.toLocaleString()} pending`,detail:_e,icon:"workflow",title:"Raw-event queue pressure and flush reliability"},{key:"retrieval-impact",label:"Retrieval impact",value:A,detail:X,icon:"sparkles",title:"Reduction from memory reuse across recent usage"},{key:"sync-health",label:"Sync health",value:H,detail:he,icon:"refresh-cw",title:"Daemon state and sync recency"},{key:"data-freshness",label:"Data freshness",value:xn(R),detail:Q,icon:"clock-3",title:"Recency of last memory pack activity"}]);const ue=async()=>{await Hs()},q=[];ge?(q.push({label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status"}),q.push({label:"Then retry failed batches for impacted sessions.",command:"codemem db raw-events-retry <opencode_session_id>"})):x==="stopped"?q.push({label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}):!$&&!J&&!fe&&(x==="error"||x==="degraded")?(q.push({label:"Sync is unhealthy. Restart and run one immediate pass.",command:"codemem serve restart",action:ue,actionLabel:"Sync now"}),q.push({label:"Then run doctor to see root cause details.",command:"codemem sync doctor"})):!$&&!J&&j&&q.push({label:"Sync is stale. Run one immediate sync pass.",command:"codemem sync once",action:ue,actionLabel:"Sync now"}),U>0&&U<.7&&q.length<2&&q.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db backfill-tags --dry-run"}),d&&d.status!=="completed"&&q.length<3&&q.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),h0(n,q),t.textContent=ce.length?`Why this status: ${ce.join(", ")}.`:"Healthy right now. Diagnostics stay available if you want details.",Nd()}function g0(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=_.lastUsagePayload||{},r=_.currentProject;n?.totals_global||n?.totals;const i=n?.totals_filtered||null,o=!!(r&&i),s=(Array.isArray(n?.events)?n.events:[]).find(N=>N.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),g=Number(d?.exact_duplicates_collapsed||0),h=!!d?.exact_dedupe_enabled,v=Fl(f,m),b=p?`${p} packs`:"No packs yet",w=u?`Last pack: ${ir(u)}`:"",S=o?"Project":"All projects",T=[{label:"Last pack savings",value:l?`${Ui(f)} (${v})`:"n/a",tooltip:l?`Exact: ${f.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:l?Ui(m):"n/a",tooltip:l?`Exact: ${m.toLocaleString()} injected`:void 0,icon:"package"},{label:"Last pack deduped",value:l?g.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"}];ky(t,[S,b,w].filter(Boolean).join(" · ")),Ny(e,T),Nd()}function v0(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=_.lastStatsPayload||{},r=_.lastUsagePayload||{},i=_.lastRawEventsPayload&&typeof _.lastRawEventsPayload=="object"?_.lastRawEventsPayload:{},o=n.database||{},s=_.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?`
|
|
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>${Wt(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=$v(e);if(i===null)return r;e=i;let o='<a href="'+e+'"';return t&&(o+=' title="'+Wt(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=$v(e);if(i===null)return Wt(n);e=i;let o=`<img src="${e}" alt="${Wt(n)}"`;return t&&(o+=` title="${Wt(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Wt(e.text)}},ld=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 Au{options;renderer;textRenderer;constructor(t){this.options=t||ar,this.options.renderer=this.options.renderer||new rs,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new ld}static parse(t,n){return new Au(n).parse(t)}static parseInline(t,n){return new Au(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}},Yi=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?Rt.lex:Rt.lexInline}provideParser(e=this.block){return e?Dt.parse:Dt.parseInline}},CI=class{defaults=ed();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Dt;Renderer=rs;TextRenderer=ld;Lexer=Rt;Tokenizer=ns;Hooks=Yi;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 rs(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 ns(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 Yi;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];Yi.passThroughHooks.has(o)?i[s]=d=>{if(this.defaults.async&&Yi.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>"+Wt(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},cr=new CI;function Pe(e,t){return cr.parse(e,t)}Pe.options=Pe.setOptions=function(e){return cr.setOptions(e),Pe.defaults=cr.defaults,Sv(Pe.defaults),Pe},Pe.getDefaults=ed,Pe.defaults=ar,Pe.use=function(...e){return cr.use(...e),Pe.defaults=cr.defaults,Sv(Pe.defaults),Pe},Pe.walkTokens=function(e,t){return cr.walkTokens(e,t)},Pe.parseInline=cr.parseInline,Pe.Parser=Dt,Pe.parser=Dt.parse,Pe.Renderer=rs,Pe.TextRenderer=ld,Pe.Lexer=Rt,Pe.lexer=Rt.lex,Pe.Tokenizer=ns,Pe.Hooks=Yi,Pe.parse=Pe;var zO=Pe.options,JO=Pe.setOptions,YO=Pe.use,XO=Pe.walkTokens,QO=Pe.parseInline,ZO=Pe,ej=Dt.parse,tj=Rt.lex,TI={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 NI(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:")}wv.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(NI(e.getAttribute("href")||"")?(e.setAttribute("rel","noopener noreferrer"),e.setAttribute("target","_blank")):e.removeAttribute("href"))});function dd(e){const t=Pe.parse(String(e||""),{async:!1});return wv.sanitize(t,TI)}function kI(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"},fE(r)),y("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:dd(i)}})):null}).filter(Boolean)}function xI(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:dd(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 Fv(e,t="feed-body"){const n=String(e||"").trim();return n?y("div",{className:t,dangerouslySetInnerHTML:{__html:dd(n)}}):null}function PI(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 is(e,t){return String(e?.kind||"").toLowerCase()==="session_summary"||t?.is_summary===!0?!0:String(t?.source||"").trim().toLowerCase()==="observer_summary"}function EI(e,t){const n=String(e?.kind||"").trim().toLowerCase();return is(e,t)?"session_summary":n||"change"}var ud=["Enter"," "],AI=["ArrowDown","PageUp","Home"],Bv=["ArrowUp","PageDown","End"],II=[...AI,...Bv],RI={ltr:[...ud,"ArrowRight"],rtl:[...ud,"ArrowLeft"]},DI={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Xi="Menu",[Qi,LI,$I]=da(Xi),[lr,Uv]=st(Xi,[$I,Sn,Lr]),Zi=Sn(),Gv=Lr(),[Hv,In]=lr(Xi),[MI,eo]=lr(Xi),Kv=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:o,modal:s=!0}=e,c=Zi(t),[l,d]=I(null),u=B(!1),p=lt(o),m=Di(i);return K(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),a(Oi,{...c,children:a(Hv,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:a(MI,{scope:t,onClose:re(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:m,modal:s,children:r})})})};Kv.displayName=Xi;var OI="MenuAnchor",pd=F((e,t)=>{const{__scopeMenu:n,...r}=e,i=Zi(n);return a(ji,{...i,...r,ref:t})});pd.displayName=OI;var md="MenuPortal",[jI,qv]=lr(md,{forceMount:void 0}),Vv=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,o=In(md,t);return a(jI,{scope:t,forceMount:n,children:a(rt,{present:n||o.open,children:a(qn,{asChild:!0,container:i,children:r})})})};Vv.displayName=md;var St="MenuContent",[FI,fd]=lr(St),Wv=F((e,t)=>{const n=qv(St,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,o=In(St,e.__scopeMenu),s=eo(St,e.__scopeMenu);return a(Qi.Provider,{scope:e.__scopeMenu,children:a(rt,{present:r||o.open,children:a(Qi.Slot,{scope:e.__scopeMenu,children:s.modal?a(BI,{...i,ref:t}):a(UI,{...i,ref:t})})})})}),BI=F((e,t)=>{const n=In(St,e.__scopeMenu),r=B(null),i=we(t,r);return K(()=>{const o=r.current;if(o)return Jo(o)},[]),a(hd,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:z(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),UI=F((e,t)=>{const n=In(St,e.__scopeMenu);return a(hd,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),GI=Hn("MenuContent.ScrollLock"),hd=F((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:g,...h}=e,v=In(St,n),b=eo(St,n),w=Zi(n),S=Gv(n),T=LI(n),[N,P]=I(null),A=B(null),M=we(t,A,v.onContentChange),U=B(0),x=B(""),G=B(0),E=B(null),$=B("right"),L=B(0),J=g?_i:te,H=g?{as:GI,allowPinchZoom:!0}:void 0,k=j=>{const V=x.current+j,ge=T().filter(fe=>!fe.disabled),le=document.activeElement,ce=ge.find(fe=>fe.ref.current===le)?.textValue,be=tR(ge.map(fe=>fe.textValue),V,ce),Y=ge.find(fe=>fe.textValue===be)?.ref.current;(function fe(X){x.current=X,window.clearTimeout(U.current),X!==""&&(U.current=window.setTimeout(()=>fe(""),1e3))})(V),Y&&setTimeout(()=>Y.focus())};K(()=>()=>window.clearTimeout(U.current),[]),Uo();const R=re(j=>$.current===E.current?.side&&rR(j,E.current?.area),[]);return a(FI,{scope:n,searchRef:x,onItemEnter:re(j=>{R(j)&&j.preventDefault()},[R]),onItemLeave:re(j=>{R(j)||(A.current?.focus(),P(null))},[R]),onTriggerLeave:re(j=>{R(j)&&j.preventDefault()},[R]),pointerGraceTimerRef:G,onPointerGraceIntentChange:re(j=>{E.current=j},[]),children:a(J,{...H,children:a(yi,{asChild:!0,trapped:i,onMountAutoFocus:z(o,j=>{j.preventDefault(),A.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:a(Kn,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:m,onDismiss:f,children:a(Jc,{asChild:!0,...S,dir:b.dir,orientation:"vertical",loop:r,currentTabStopId:N,onCurrentTabStopIdChange:P,onEntryFocus:z(l,j=>{b.isUsingKeyboardRef.current||j.preventDefault()}),preventScrollOnEntryFocus:!0,children:a(Ea,{role:"menu","aria-orientation":"vertical","data-state":dy(v.open),"data-radix-menu-content":"",dir:b.dir,...w,...h,ref:M,style:{outline:"none",...h.style},onKeyDown:z(h.onKeyDown,j=>{const V=j.target.closest("[data-radix-menu-content]")===j.currentTarget,ge=j.ctrlKey||j.altKey||j.metaKey,le=j.key.length===1;V&&(j.key==="Tab"&&j.preventDefault(),!ge&&le&&k(j.key));const ce=A.current;if(j.target!==ce||!II.includes(j.key))return;j.preventDefault();const be=T().filter(Y=>!Y.disabled).map(Y=>Y.ref.current);Bv.includes(j.key)&&be.reverse(),ZI(be)}),onBlur:z(e.onBlur,j=>{j.currentTarget.contains(j.target)||(window.clearTimeout(U.current),x.current="")}),onPointerMove:z(e.onPointerMove,no(j=>{const V=j.target,ge=L.current!==j.clientX;j.currentTarget.contains(V)&&ge&&($.current=j.clientX>L.current?"right":"left",L.current=j.clientX)}))})})})})})})});Wv.displayName=St;var HI="MenuGroup",gd=F((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{role:"group",...r,ref:t})});gd.displayName=HI;var KI="MenuLabel",zv=F((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{...r,ref:t})});zv.displayName=KI;var os="MenuItem",Jv="menu.itemSelect",as=F((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,o=B(null),s=eo(os,e.__scopeMenu),c=fd(os,e.__scopeMenu),l=we(t,o),d=B(!1),u=()=>{const p=o.current;if(!n&&p){const m=new CustomEvent(Jv,{bubbles:!0,cancelable:!0});p.addEventListener(Jv,f=>r?.(f),{once:!0}),uc(p,m),m.defaultPrevented?d.current=!1:s.onClose()}};return a(Yv,{...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===" "||ud.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});as.displayName=os;var Yv=F((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...o}=e,s=fd(os,n),c=Gv(n),l=B(null),d=we(t,l),[u,p]=I(!1),[m,f]=I("");return K(()=>{const g=l.current;g&&f((g.textContent??"").trim())},[o.children]),a(Qi.ItemSlot,{scope:n,disabled:r,textValue:i??m,children:a(Yc,{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,no(g=>{r?s.onItemLeave(g):(s.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:z(e.onPointerLeave,no(g=>s.onItemLeave(g))),onFocus:z(e.onFocus,()=>p(!0)),onBlur:z(e.onBlur,()=>p(!1))})})})}),qI="MenuCheckboxItem",Xv=F((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return a(ny,{scope:e.__scopeMenu,checked:n,children:a(as,{role:"menuitemcheckbox","aria-checked":ss(n)?"mixed":n,...i,ref:t,"data-state":bd(n),onSelect:z(i.onSelect,()=>r?.(ss(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Xv.displayName=qI;var Qv="MenuRadioGroup",[VI,WI]=lr(Qv,{value:void 0,onValueChange:()=>{}}),Zv=F((e,t)=>{const{value:n,onValueChange:r,...i}=e,o=lt(r);return a(VI,{scope:e.__scopeMenu,value:n,onValueChange:o,children:a(gd,{...i,ref:t})})});Zv.displayName=Qv;var ey="MenuRadioItem",ty=F((e,t)=>{const{value:n,...r}=e,i=WI(ey,e.__scopeMenu),o=n===i.value;return a(ny,{scope:e.__scopeMenu,checked:o,children:a(as,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":bd(o),onSelect:z(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});ty.displayName=ey;var vd="MenuItemIndicator",[ny,zI]=lr(vd,{checked:!1}),ry=F((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,o=zI(vd,n);return a(rt,{present:r||ss(o.checked)||o.checked===!0,children:a(se.span,{...i,ref:t,"data-state":bd(o.checked)})})});ry.displayName=vd;var JI="MenuSeparator",iy=F((e,t)=>{const{__scopeMenu:n,...r}=e;return a(se.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});iy.displayName=JI;var YI="MenuArrow",oy=F((e,t)=>{const{__scopeMenu:n,...r}=e,i=Zi(n);return a(Aa,{...i,...r,ref:t})});oy.displayName=YI;var yd="MenuSub",[XI,ay]=lr(yd),QI=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:i}=e,o=In(yd,t),s=Zi(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(Oi,{...s,children:a(Hv,{scope:t,open:r,onOpenChange:p,content:d,onContentChange:u,children:a(XI,{scope:t,contentId:ct(),triggerId:ct(),trigger:c,onTriggerChange:l,children:n})})})};QI.displayName=yd;var to="MenuSubTrigger",sy=F((e,t)=>{const n=In(to,e.__scopeMenu),r=eo(to,e.__scopeMenu),i=ay(to,e.__scopeMenu),o=fd(to,e.__scopeMenu),s=B(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(pd,{asChild:!0,...d,children:a(Yv,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":dy(n.open),...e,ref:Fo(t,i.onTriggerChange),onClick:p=>{e.onClick?.(p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:z(e.onPointerMove,no(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,no(p=>{u();const m=n.content?.getBoundingClientRect();if(m){const f=n.content?.dataset.side,g=f==="right",h=g?-5:5,v=m[g?"left":"right"],b=m[g?"right":"left"];o.onPointerGraceIntentChange({area:[{x:p.clientX+h,y:p.clientY},{x:v,y:m.top},{x:b,y:m.top},{x:b,y:m.bottom},{x:v,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===" "||RI[r.dir].includes(p.key)&&(n.onOpenChange(!0),n.content?.focus(),p.preventDefault())})})})});sy.displayName=to;var cy="MenuSubContent",ly=F((e,t)=>{const n=qv(St,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,o=In(St,e.__scopeMenu),s=eo(St,e.__scopeMenu),c=ay(cy,e.__scopeMenu),l=B(null),d=we(t,l);return a(Qi.Provider,{scope:e.__scopeMenu,children:a(rt,{present:r||o.open,children:a(Qi.Slot,{scope:e.__scopeMenu,children:a(hd,{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=DI[s.dir].includes(u.key);p&&m&&(o.onOpenChange(!1),c.trigger?.focus(),u.preventDefault())})})})})})});ly.displayName=cy;function dy(e){return e?"open":"closed"}function ss(e){return e==="indeterminate"}function bd(e){return ss(e)?"indeterminate":e?"checked":"unchecked"}function ZI(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function eR(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function tR(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=eR(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 nR(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 rR(e,t){return t?nR({x:e.clientX,y:e.clientY},t):!1}function no(e){return t=>t.pointerType==="mouse"?e(t):void 0}var iR=Kv,oR=pd,aR=Vv,sR=Wv,cR=gd,lR=zv,dR=as,uR=Xv,pR=Zv,mR=ty,fR=ry,hR=iy,gR=oy,vR=sy,yR=ly,cs="DropdownMenu",[bR,nj]=st(cs,[Uv]),pt=Uv(),[_R,uy]=bR(cs),py=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:o,onOpenChange:s,modal:c=!0}=e,l=pt(t),d=B(null),[u,p]=wt({prop:i,defaultProp:o??!1,onChange:s,caller:cs});return a(_R,{scope:t,triggerId:ct(),triggerRef:d,contentId:ct(),open:u,onOpenChange:p,onOpenToggle:re(()=>p(m=>!m),[p]),modal:c,children:a(iR,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})};py.displayName=cs;var my="DropdownMenuTrigger",fy=F((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,o=uy(my,n),s=pt(n);return a(oR,{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:Fo(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())})})})});fy.displayName=my;var wR="DropdownMenuPortal",hy=e=>{const{__scopeDropdownMenu:t,...n}=e,r=pt(t);return a(aR,{...r,...n})};hy.displayName=wR;var gy="DropdownMenuContent",vy=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=uy(gy,n),o=pt(n),s=B(!1);return a(sR,{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)"}})});vy.displayName=gy;var SR="DropdownMenuGroup",CR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(cR,{...i,...r,ref:t})});CR.displayName=SR;var TR="DropdownMenuLabel",NR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(lR,{...i,...r,ref:t})});NR.displayName=TR;var kR="DropdownMenuItem",yy=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(dR,{...i,...r,ref:t})});yy.displayName=kR;var xR="DropdownMenuCheckboxItem",PR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(uR,{...i,...r,ref:t})});PR.displayName=xR;var ER="DropdownMenuRadioGroup",AR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(pR,{...i,...r,ref:t})});AR.displayName=ER;var IR="DropdownMenuRadioItem",RR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(mR,{...i,...r,ref:t})});RR.displayName=IR;var DR="DropdownMenuItemIndicator",LR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(fR,{...i,...r,ref:t})});LR.displayName=DR;var $R="DropdownMenuSeparator",MR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(hR,{...i,...r,ref:t})});MR.displayName=$R;var OR="DropdownMenuArrow",jR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(gR,{...i,...r,ref:t})});jR.displayName=OR;var FR="DropdownMenuSubTrigger",BR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(vR,{...i,...r,ref:t})});BR.displayName=FR;var UR="DropdownMenuSubContent",GR=F((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return a(yR,{...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)"}})});GR.displayName=UR;var HR=py,KR=fy,qR=hy,VR=vy,by=yy;function WR({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return y(HR,null,y(KR,{asChild:!0},y("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),y(qR,null,y(VR,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},y(by,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),y(by,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function zR({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 _d({label:e,variant:t=""}){return y(Vl,{variant:"provenance",tone:t||void 0},e)}function JR({tag:e}){const t=qg(e);return t?y(Vl,{variant:"tag",title:String(e)},t):null}function YR({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const o=Ka(e?.metadata_json),s=is(e,o),c=EI(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=uE(p),f=Ha(e.tags||[]),g=Ha(e.files||[]),h=e.project||"",v=SE(e),b=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(),N=String(e.trust_state||o?.trust_state||"").trim(),P=f.length?` · ${f.map(pe=>qg(pe)).join(", ")}`:"",A=g.length?` · ${hE(g)}`:"",M=Number(e.id||0),U=M>0?`ID ${M}`:"",[x,G]=I(_.newItemKeys.has(l)),E=s?PI({...e,metadata_json:o}):null,$=s?null:QE({...e,metadata_json:o}),L=$?ZE($):[],J=$?eA($):"summary",H=_.itemViewState.get(l),[k,R]=I($&&H&&L.some(pe=>pe.id===H)?H:J),j=`${l}:${k}`,[V,ge]=I(_.itemExpandState.get(j)===!0),[le,ce]=I(b==="shared"?"shared":"private"),[be,Y]=I(!1),[fe,X]=I(!1),[_e,he]=I(!1),Q=E?kI(E):[];K(()=>{$&&(L.some(pe=>pe.id===k)||R(J))},[k,J,L,$]),K(()=>{_.itemViewState.set(l,k)},[k,l]),K(()=>{const pe=`${l}:${k}`;ge(_.itemExpandState.get(pe)===!0)},[k,l]),K(()=>{ce(b==="shared"?"shared":"private")},[b]),K(()=>{if(!x)return;const pe=window.setTimeout(()=>{_.newItemKeys.delete(l),G(!1)},700);return()=>window.clearTimeout(pe)},[x,l]);const $e=le,ue=$e==="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.",q=[h?`Project ${h}`:"No project",m].filter(Boolean).join(" · "),oe=[w&&w!==b?`Workspace ${w}`:"",S?`From ${S}`:"",T&&v!=="You"?`Device ${T}`:"",N&&N!=="trusted"?wE(N):""].filter(Boolean).join(" · "),qe=[`${P}${A}`.trim(),oe].filter(Boolean).join(" · "),Me=!!$&&tA(k,$),tt=[k==="facts"?"feed-body facts":"feed-body",Me&&!V?nA(k).join(" "):""].filter(Boolean).join(" "),pn=s?Q.length?y("div",{className:"feed-body facts"},Q):Fv(String(e.body_text||""))||y("div",{className:"feed-body"}):$?k==="facts"?xI($.facts)||y("div",{className:tt}):Fv(k==="narrative"?$.narrative:$.summary,tt)||y("div",{className:tt}):y("div",{className:"feed-body"});async function Lt(pe){const ae=$e;ce(pe),Y(!0);try{const Ge=await H_(M,pe);Ge?.item&&(t(Ge.item),r()),ne(pe==="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 Nt(){const pe=String(e.project||"").trim(),ae=pe,Ge=String(u||"this memory").trim(),On=Ge.length>80?`${Ge.slice(0,79).trimEnd()}…`:Ge,So=pe?`Move "${On}" from "${pe}" 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 "${On}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`;let mn=[];try{mn=(await ko()).filter(ht=>ht&&ht!==pe)}catch{}const br=await Rl({title:"Assign to project",description:So,initialValue:ae,placeholder:"Pick one or type a new project name",suggestions:mn,confirmLabel:"Move",cancelLabel:"Cancel",validate:ht=>{const Fn=ht.trim();return Fn?Fn===pe?"Already assigned to this project.":null:"Enter a project name."}});if(br==null)return;const jn=br.trim();if(!(!jn||jn===pe)){he(!0);try{const ht=await K_(M,jn),Fn=Number(ht.moved_memory_count||1);ne(Fn>1?`Moved ${Fn} 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{he(!1)}}}async function $t(){const pe=String(u||"this memory").trim();if(await Kt({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${pe.length>80?`${pe.slice(0,79).trimEnd()}…`:pe}". 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"})){X(!0);try{await q_(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{X(!1)}}}const nt=c.replace(/_/g," "),Mt=g.length?y("div",{className:"feed-files"},g.map((pe,ae)=>y("span",{className:"feed-file",key:`${String(pe)}-${ae}`},String(pe)))):null;return y("article",{className:`feed-item ${c}${x?" new-item":""}`.trim(),"data-key":l},y("div",{className:"feed-kind-banner"},y(Vl,{variant:"kind",tone:c},nt)),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:YT(u,_.feedQuery)}}),y("div",{className:"feed-card-subtitle small"},q)),y("div",{className:"feed-actions"},$?y(zR,{active:k,modes:L,onSelect:pe=>R(pe)}):null,y(Ja,{label:dE(p),side:"left"},y("div",{className:"small feed-age"},m)),e.owned_by_self&&M>0?y(WR,{assignProjectDisabled:_e,disabled:fe,onAssignProject:()=>{Nt()},onForget:()=>{$t()},title:String(u||"memory")}):null)),y("div",{className:"feed-provenance"},y(_d,{label:v,variant:v==="You"?"mine":"author"}),y(_d,{label:b||"private",variant:b||"private"}),U?y(Ja,{label:`Memory database id ${M}`,side:"top"},y(_d,{label:U,variant:"memory-id"})):null),y("div",{className:"feed-meta"},qe||"No tags, files, or provenance details attached."),pn,y("div",{className:"feed-footer"},y("div",{className:"feed-footer-left"},f.length?y("div",{className:"feed-tags"},f.map((pe,ae)=>y(JR,{key:`${String(pe)}-${ae}`,tag:pe}))):null,e.owned_by_self&&M>0?y("div",{className:"feed-visibility-controls"},y("select",{"aria-label":`Visibility for ${String(e.title||"memory")}`,className:"feed-visibility-select",disabled:be,onChange:pe=>{Lt(String(pe.currentTarget.value)==="shared"?"shared":"private")},value:$e},y("option",{value:"private"},"Only me"),y("option",{value:"shared"},"Share with peers")),y("div",{className:"feed-visibility-note"},ue)):null),y("div",{className:"feed-footer-right"},Me?y("button",{className:"feed-expand",onClick:()=>{const pe=!V;_.itemExpandState.set(j,pe),ge(pe)},type:"button"},V?"Collapse":"Expand"):null)),Mt))}function XR({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 QR({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(XR,{index:r,key:`skeleton-${r}`})));if(!e.length){const r=!!_.feedQuery.trim()||_.feedTypeFilter!=="all"||_.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(te,null,e.map(r=>y(YR,{item:r,key:ft(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function _y({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 ZR({items:e,loadingText:t,ops:n}){const[r,i]=I(!1);return y(te,null,y("div",{className:"feed-controls"},y("div",{className:"section-meta",id:"feedMeta"},t||rA(e.length,n.hasMorePages())),y("div",{className:"feed-controls-right"},y("input",{className:"feed-search",id:"feedSearch",onInput:o=>{_.feedQuery=String(o.currentTarget.value||""),n.updateFeedView()},placeholder:"Search title, body, tags…",value:_.feedQuery}),y(_y,{active:_.feedScopeFilter,id:"feedScopeToggle",onSelect:o=>{o!==_.feedScopeFilter&&(Pf(o),n.loadFeedData())},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),y(_y,{active:_.feedTypeFilter,id:"feedTypeToggle",onSelect:o=>{o!==_.feedTypeFilter&&(lN(o),n.updateFeedView())},options:[{value:"all",label:"All"},{value:"observations",label:"Observations"},{value:"summaries",label:"Summaries"}]}),y("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"))),y(iA,{open:r}),y("div",{className:"feed-list",id:"feedList"},y(QR,{items:e,loadingText:t,ops:n})))}function e0(e){return _.feedTypeFilter==="observations"?e.filter(t=>!is(t,Ka(t?.metadata_json))):_.feedTypeFilter==="summaries"?e.filter(t=>is(t,Ka(t?.metadata_json))):e}function t0(e){const t=It(_.feedQuery);return t?e.filter(n=>[It(n?.title),It(n?.body_text),It(n?.kind),Ha(n?.tags||[]).map(r=>It(r)).join(" "),It(n?.project)].join(" ").trim().includes(t)):e}function n0(e){const t=e.map(n=>`${Wg(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}`);return`${_.feedTypeFilter}|${_.feedScopeFilter}|${_.currentProject}|${It(_.feedQuery)}|${t.join("|")}`}var wy="",ro=0,io=0,oo=!0,ao=!0,wd=!1,Sy=!1,so=0,Sd="all";function r0(e){wy=e,Sd=_.feedScopeFilter,so+=1,ro=0,io=0,oo=!0,ao=!0,_.lastFeedItems=[],_.pendingFeedItems=null,_.lastFeedFilteredCount=0,_.lastFeedSignature="",_.newItemKeys.clear(),_.itemViewState.clear(),_.itemExpandState.clear()}function Cd(){return oo||ao}function i0(e){const t=ft(e);_.lastFeedItems=_.lastFeedItems.map(n=>ft(n)===t?e:n)}function o0(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(ft(r)),i};_.lastFeedItems=_.lastFeedItems.filter(n),Array.isArray(_.pendingFeedItems)&&(_.pendingFeedItems=_.pendingFeedItems.filter(n));for(const r of t){_.newItemKeys.delete(r),_.itemViewState.delete(r);for(const i of Array.from(_.itemExpandState.keys()))i.startsWith(`${r}:`)&&_.itemExpandState.delete(i)}}async function a0(){if(wd||!Cd())return;const e=_.currentProject||"",t=so,n=ro,r=io;wd=!0;try{const[i,o]=await Promise.all([oo?Mu(e,{limit:20,offset:n,scope:_.feedScopeFilter}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:n}}),ao?Ou(e,{limit:50,offset:r,scope:_.feedScopeFilter}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}})]);if(t!==so||e!==(_.currentProject||""))return;const s=o.items||[],c=i.items||[],l=c.filter(u=>!Vg(u));_.lastFeedFilteredCount+=c.length-l.length,ao=qa(o,s.length,50),oo=qa(i,c.length,20),io=Va(o,r+s.length),ro=Va(i,n+c.length);const d=[...s,...l];_.lastFeedItems=zg(_.lastFeedItems,d),co()}finally{wd=!1}}function Cy(){_.activeTab==="feed"&&Cd()&&TE()&&a0()}var s0={replaceFeedItem:i0,removeFeedItem:o0,updateFeedView:e=>co(e),loadFeedData:()=>Ty(),hasMorePages:Cd};function Td(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;JE(n,y(ZR,{items:e,loadingText:t?.loadingText,ops:s0}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function c0(){Td([],{loadingText:"Loading selected project..."})}function l0(){zE(),Td(_.lastFeedItems,_.lastFeedItems.length||_.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),Sy||(window.addEventListener("scroll",()=>{Cy()},{passive:!0}),Sy=!0)}function co(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=t0(e0(_.lastFeedItems)),r=n0(n),i=e||r!==_.lastFeedSignature;_.lastFeedSignature=r,i&&Td(n),window.scrollTo({top:t}),Cy()}async function Ty(){const e=_.currentProject||"",t=_.feedScopeFilter!==Sd;(e!==wy||t)&&(r0(e),c0());const n=so,r=20,i=50,[o,s]=await Promise.all([Mu(e,{limit:r,offset:0,scope:_.feedScopeFilter}),Ou(e,{limit:i,offset:0,scope:_.feedScopeFilter})]);if(n!==so||e!==(_.currentProject||""))return;const c=s.items||[],l=o.items||[],d=l.filter(g=>!Vg(g)),u=l.length-d.length,p=[...c,...d].sort((g,h)=>new Date(h.created_at||0).getTime()-new Date(g.created_at||0).getTime()),m=CE(_.lastFeedItems,p),f=_.lastFeedItems;if(NE(m,f)&&f.length>0){const g=new Set(f.map(ft));m.forEach(h=>{g.has(ft(h))||_.newItemKeys.add(ft(h))})}_.pendingFeedItems=null,_.lastFeedItems=m,_.lastFeedFilteredCount=Math.max(_.lastFeedFilteredCount,u),ao=qa(s,c.length,i),oo=qa(o,l.length,r),io=Math.max(io,Va(s,c.length)),ro=Math.max(ro,Va(o,l.length)),Sd=_.feedScopeFilter,co()}function rj(e){return e}function d0({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(Ja,{label:o},s):s}function u0({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||Ai(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 p0(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function m0({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"},p0(t)),y("div",{class:"label"},e)));return r?y(Ja,{label:r},i):i}function Ny(e,t){e&&Ue(y(Kl,null,t.map(n=>y(m0,{...n,key:`${n.label}-${n.icon}`}))),e)}function ky(e,t){e&&Ue(y(te,null,t),e)}function Nd(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function f0(e,t){e&&Ue(y(Kl,null,t.map(n=>y(d0,{...n,key:n.key??n.label}))),e)}function h0(e,t){if(e){if(!t.length){e.hidden=!0,Ue(null,e);return}e.hidden=!1,Ue(y(te,null,t.slice(0,3).map((n,r)=>y(u0,{item:n,key:`${n.label}-${r}`}))),e)}}var xy="scope_id_backfill";function Py(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthMeta"),n=document.getElementById("healthActions"),r=document.getElementById("healthDot");if(!e||!t)return;const i=_.lastStatsPayload||{},o=_.lastUsagePayload||{},s=_.lastRawEventsPayload&&typeof _.lastRawEventsPayload=="object"?_.lastRawEventsPayload:{},c=_.lastSyncStatus||{},l=Array.isArray(i.maintenance_jobs)?i.maintenance_jobs:[],d=l.find(oe=>oe.kind===xy),u=i.reliability||{},p=u.counts||{},m=u.rates||{},f=i.database||{},g=o.totals_filtered||o.totals||o.totals_global||i.usage?.totals||{},h=Array.isArray(o.recent_packs)?o.recent_packs:[],v=h.length?h[0]?.created_at:null,b=h.length?h[0]?.metadata_json||{}:{},w=Number(b?.exact_duplicates_collapsed||0),S=Number(s.pending||0),T=Number(p.errored_batches||0),N=Number(m.flush_success_rate??1),P=Number(m.dropped_event_rate||0),A=Fl(g.tokens_saved,g.tokens_read),M=mE(A),U=Number(f.tags_coverage||0),x=String(c.daemon_state||"unknown"),G=x==="offline-peers"?"Offline peers":x==="needs_attention"?"Needs attention":x==="rebootstrapping"?"Rebootstrapping":Kg(x),E=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers.length:0,$=x==="disabled"||c.enabled===!1,L=x==="offline-peers",J=!$&&E===0;let H=$?"Disabled":J?"No peers":G;const k=qr(c.last_sync_at||c.last_sync_at_utc||null),R=qr(v),j=k!==null&&k>7200,V=k!==null&&k<=300,ge=S>=200;let le=0;const ce=[];S>=1e3?(le+=40,ce.push("high raw-event backlog")):S>=200&&(le+=24,ce.push("growing raw-event backlog")),T>0&&S>=200&&(le+=T>=5?10:6,ce.push("batch errors during backlog pressure")),N<.95&&(le+=20,ce.push("lower flush success")),P>.02?(le+=24,ce.push("high dropped-event rate")):P>.005&&(le+=10,ce.push("non-trivial dropped-event rate")),!$&&!J&&(x==="error"?(le+=36,ce.push("sync daemon reports errors")):x==="needs_attention"?(le+=40,ce.push("sync needs manual attention")):x==="stopped"?(le+=22,ce.push("sync daemon stopped")):x==="degraded"&&!V&&(le+=20,ce.push("sync daemon degraded")),L?(le+=4,ce.push("all peers currently offline"),j&&(le+=4,ce.push("offline peers and sync not recent"))):j?(le+=26,ce.push("sync looks stale")):k!==null&&k>1800&&(le+=12,ce.push("sync not recent"))),M!==null&&M<10&&(le+=8,ce.push("low retrieval reduction")),R!==null&&R>86400&&(le+=12,ce.push("memory pack activity is old"));let be="Healthy",Y="status-healthy";le>=60?(be="Attention",Y="status-attention"):le>=25&&(be="Degraded",Y="status-degraded");const fe=Y==="status-healthy";r&&(r.className=`health-dot ${Y}`,r.title=be);const X=`${Number(g.tokens_saved||0).toLocaleString()} saved tokens · ${w.toLocaleString()} deduped in latest pack`,_e=S>0?"Queue is actively draining":"Queue is clear",he=$?"Sync disabled":J?"No peers configured":L?`${E} peers offline · last sync ${xn(k)} ago`:`${E} peers · last sync ${xn(k)} ago`;fe&&!$&&!J&&(L?H="Peers offline":x==="degraded"&&V&&(H="Syncing"));const Q=`last pack ${xn(R)} ago`,$e=l.map(oe=>{const qe=Number(oe.progress?.current||0),Me=typeof oe.progress?.total=="number"?oe.progress.total:null,tt=String(oe.progress?.unit||"items"),pn=Me&&Me>0?` (${Math.round(100*qe/Me)}%)`:"",Lt=Me&&Me>0?`${qe.toLocaleString()}/${Me.toLocaleString()} ${tt}${pn}`:`${qe.toLocaleString()} ${tt}`,Nt=oe.status==="failed",$t=oe.status==="completed",nt=oe.kind===xy,Mt=Nt?"Failed":$t?"Complete":Lt,pe=Nt?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:pe,icon:Nt?"alert-triangle":$t?"check-circle":"loader",className:Nt?"status-attention":void 0,title:Nt?`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`}});f0(e,[{key:"overall-health",label:"Overall health",value:be,detail:`Weighted score ${le}`,icon:"heart-pulse",className:`health-primary ${Y}`,title:ce.length?`Main signals: ${ce.join(", ")}`:"No major risk signals detected"},...$e,{key:"pipeline-health",label:"Pipeline health",value:`${S.toLocaleString()} pending`,detail:_e,icon:"workflow",title:"Raw-event queue pressure and flush reliability"},{key:"retrieval-impact",label:"Retrieval impact",value:A,detail:X,icon:"sparkles",title:"Reduction from memory reuse across recent usage"},{key:"sync-health",label:"Sync health",value:H,detail:he,icon:"refresh-cw",title:"Daemon state and sync recency"},{key:"data-freshness",label:"Data freshness",value:xn(R),detail:Q,icon:"clock-3",title:"Recency of last memory pack activity"}]);const ue=async()=>{await Hs()},q=[];ge?(q.push({label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status"}),q.push({label:"Then retry failed batches for impacted sessions.",command:"codemem db raw-events-retry <opencode_session_id>"})):x==="stopped"?q.push({label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}):!$&&!J&&!fe&&(x==="error"||x==="degraded")?(q.push({label:"Sync is unhealthy. Restart and run one immediate pass.",command:"codemem serve restart",action:ue,actionLabel:"Sync now"}),q.push({label:"Then run doctor to see root cause details.",command:"codemem sync doctor"})):!$&&!J&&j&&q.push({label:"Sync is stale. Run one immediate sync pass.",command:"codemem sync once",action:ue,actionLabel:"Sync now"}),U>0&&U<.7&&q.length<2&&q.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db backfill-tags --dry-run"}),d&&d.status!=="completed"&&q.length<3&&q.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),h0(n,q),t.textContent=ce.length?`Why this status: ${ce.join(", ")}.`:"Healthy right now. Diagnostics stay available if you want details.",Nd()}function g0(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=_.lastUsagePayload||{},r=_.currentProject;n?.totals_global||n?.totals;const i=n?.totals_filtered||null,o=!!(r&&i),s=(Array.isArray(n?.events)?n.events:[]).find(N=>N.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),g=Number(d?.exact_duplicates_collapsed||0),h=!!d?.exact_dedupe_enabled,v=Fl(f,m),b=p?`${p} packs`:"No packs yet",w=u?`Last pack: ${ir(u)}`:"",S=o?"Project":"All projects",T=[{label:"Last pack savings",value:l?`${Ui(f)} (${v})`:"n/a",tooltip:l?`Exact: ${f.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:l?Ui(m):"n/a",tooltip:l?`Exact: ${m.toLocaleString()} injected`:void 0,icon:"package"},{label:"Last pack deduped",value:l?g.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"}];ky(t,[S,b,w].filter(Boolean).join(" · ")),Ny(e,T),Nd()}function v0(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=_.lastStatsPayload||{},r=_.lastUsagePayload||{},i=_.lastRawEventsPayload&&typeof _.lastRawEventsPayload=="object"?_.lastRawEventsPayload:{},o=n.database||{},s=_.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
112
|
Global: ${Number(c.work_investment_tokens||0).toLocaleString()} invested`:"",g=d?`
|
|
113
113
|
Global: ${Number(c.tokens_read||0).toLocaleString()} read`:"",h=d?`
|
|
114
|
-
Global: ${Number(c.tokens_saved||0).toLocaleString()} saved`:"",v=[{label:d?"Savings (project)":"Savings",value:Ui(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:Ui(u.tokens_read||0),tooltip:`Tokens injected into context (pack size). Exact: ${Number(u.tokens_read||0).toLocaleString()} injected${g}`,icon:"book-open"},{label:d?"Reduction (project)":"Reduction",value:Fl(u.tokens_saved,u.tokens_read),tooltip:`Percent reduction from reuse. Factor: ${pE(u.tokens_saved,u.tokens_read)}.`+g+h,icon:"percent"},{label:d?"Work investment (project)":"Work investment",value:Ui(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:Hg(o.vector_coverage),tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:Hg(o.tags_coverage),tooltip:"Share of active memories with tags",icon:"tag"}];if(m>0?v.push({label:"Raw events pending",value:m,tooltip:"Pending raw events waiting to be flushed",icon:"activity"}):p>0&&v.push({label:"Raw sessions",value:p,tooltip:"Sessions with pending raw events",icon:"inbox"}),Ny(e,v),t){const b=s?` · project: ${s}`:"";ky(t,`DB: ${gE(o.path||"unknown")} · ${vE(o.size_bytes||0)}${b}`)}Nd()}async function y0(){const e=_.lastStatsPayload?.identity?.actor_id||null,[t,n,r,i]=await Promise.all([J_(),Y_(_.currentProject),X_(_.currentProject),Q_(_.currentProject)]);_.lastStatsPayload=t||{},_.lastUsagePayload=n||{},_.lastRawEventsPayload=i||{};const o=_.lastStatsPayload?.identity?.actor_id||null;v0(),g0(),Py(),_.activeTab==="feed"&&e!==o&&co(!0)}var dr=new Set,kd=new Set,Xr="";function ln(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function b0(e){return e.options.find(t=>t.decision===e.recommendedDecision)?.label??e.recommendedDecision.replaceAll("_"," ")}function Ey(e,t){const n=document.createElement("div");n.className="recipient-policy-preview-list";const r=document.createElement("strong");r.textContent=e;const i=document.createElement("ul");for(const o of t){const s=document.createElement("li");s.textContent=o,i.appendChild(s)}return n.append(r,i),n}function _0(e){const t=document.createElement("div");t.className="recipient-policy-preview settings-note";const n=document.createElement("strong");return n.textContent=`Exact preview: ${e.preview.affectedProjectCount.toLocaleString()} project${e.preview.affectedProjectCount===1?"":"s"} · ${e.preview.affectedMemoryCount.toLocaleString()} memor${e.preview.affectedMemoryCount===1?"y":"ies"} · ${e.preview.affectedDeviceCount.toLocaleString()} device${e.preview.affectedDeviceCount===1?"":"s"}`,t.appendChild(n),t.appendChild(Ey("Projects",e.preview.projects.map(r=>r.displayName))),t.appendChild(Ey("Devices",e.preview.effectiveDevices.map(r=>`${r.displayName} (${r.assignment})`))),t}function w0(e,t,n,r){const i=document.createElement("article");i.className="project-inventory-row recipient-policy-review-item";const o=document.createElement("h3");o.className="project-inventory-title",o.textContent=e.finding;const s=ln(e.reason,"project-inventory-meta"),c=ln(`Recommended: ${b0(e)}`,"settings-note"),l=document.createElement("div");l.className="project-inventory-actions";const d=`recipient-policy-decision-${t}`,u=document.createElement("label");u.htmlFor=d,u.textContent="Decision";const p=document.createElement("select");p.id=d,p.className="project-filter recipient-policy-review-select";for(const b of e.options){const w=document.createElement("option");w.value=b.decision,w.textContent=b.label,p.appendChild(w)}e.options.some(b=>b.decision===e.recommendedDecision)&&(p.value=e.recommendedDecision);const m=document.createElement("button");m.className="settings-button",m.type="button",m.textContent="Apply decision";const f=ln("","settings-note recipient-policy-deferred"),g=document.createElement("div");g.className="recipient-policy-preview-mount",g.setAttribute("aria-live","polite");const h=()=>e.options.find(b=>b.decision===p.value)??e.options[0],v=()=>{const b=h();b&&(g.replaceChildren(_0(b)),f.textContent=b.preview.requiresDecisionInput?"Recipient or device details are required for this decision. Complete it in a later review flow; no incomplete decision will be submitted.":"",f.hidden=!b.preview.requiresDecisionInput,m.disabled=b.preview.requiresDecisionInput||dr.has(e.reviewItemId))};return p.addEventListener("change",v),v(),kd.has(e.reviewItemId)&&i.appendChild(ln("Source state changed while this decision was being reviewed. Review the refreshed choices before trying again.","settings-note project-attention-note")),m.addEventListener("click",async()=>{const b=h();if(!(!b||b.preview.requiresDecisionInput||dr.has(e.reviewItemId))){dr.add(e.reviewItemId),p.disabled=!0,m.disabled=!0,m.textContent="Applying…",n.textContent=`Applying “${b.label}”…`;try{await lw({reviewItemId:e.reviewItemId,sourceFingerprint:e.sourceFingerprint,decision:b.decision}),kd.delete(e.reviewItemId),Xr="Decision applied. Review items refreshed.",dr.delete(e.reviewItemId),await r()}catch(w){if(w instanceof Hu){kd.add(e.reviewItemId),Xr="Source state changed. The review item is still open and its choices were refreshed.",n.textContent=Xr,dr.delete(e.reviewItemId),await r();return}Xr=w instanceof Error?w.message:"Unable to apply decision.",n.textContent=Xr,dr.delete(e.reviewItemId),p.disabled=!1,m.textContent="Apply decision",v()}finally{dr.delete(e.reviewItemId)}}}),l.append(u,p,m),i.prepend(o,s,c),i.append(l,f,g),i}function S0(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,ln(e.reason,"project-inventory-meta"),ln(`Owner: ${e.ownerLabel}`,"settings-note"),ln(`Repair: ${e.repairAction}`,"settings-note")),t}function C0(e,t,n){const r=t.reviewItems.filter(l=>l.options.length>0);if(r.length===0&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0;return}e.hidden=!1;const i=document.createElement("section");i.className="card recipient-policy-review",i.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const o=document.createElement("h2");o.id="recipientPolicyReviewTitle",o.textContent="Recipient migration review";const s=ln("Review how older project sharing should be represented. These decisions do not expose internal scope or transport details.","section-meta"),c=document.createElement("div");if(c.className="section-meta recipient-policy-review-status",c.setAttribute("role","status"),c.setAttribute("aria-live","polite"),c.textContent=Xr,i.append(o,s,c),r.length>0){const l=document.createElement("h3");l.textContent="Needs review";const d=document.createElement("div");d.className="project-inventory-list recipient-policy-review-list",r.forEach((u,p)=>{d.appendChild(w0(u,p,c,n))}),i.append(l,d)}if(t.blockedItems.length>0){const l=document.createElement("h3");l.className="recipient-policy-blocked-heading",l.textContent="Blocked";const d=document.createElement("div");d.className="project-inventory-list recipient-policy-review-list";for(const u of t.blockedItems)d.appendChild(S0(u));i.append(l,d)}e.replaceChildren(i)}function T0(e,t){e.hidden=!1;const n=document.createElement("section");n.className="card recipient-policy-review";const r=document.createElement("h2");r.textContent="Recipient migration review";const i=ln(t instanceof Error?t.message:"Unable to load recipient migration review.","settings-note project-attention-note");i.setAttribute("role","status"),n.append(r,i),e.replaceChildren(n)}var Ay=[["","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"]],ot=null,lo=0,xd=250,Pd=[],Ed=new Set,Ad=new Set,ls=new Map,ds=new Map,ur=new Map,uo=new Map,us=!1,po=!1,Rn=!1,ps=0,Ct=new Set,Iy=new WeakMap,ms={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Qr=ms,Dn=!1;function Ke(e){return document.getElementById(e)}function N0(e){return Ay.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function k0(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 Zr(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Id(e){return e.identity_source!=="unmapped"&&!Zr(e)}function Rd(e){return Zr(e)?"Received from peers":fs(e.resolved_scope_id)}function x0(e){return Zr(e)?"source-owned project":k0(e.resolution_reason)}function P0(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`Waiting for ${t}'s device`;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 Ry(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Dy(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function pr(){const e=Ct.size,t=Ke("projectsShareSelected");t&&(t.textContent=e===0?"Share selected":`Share selected (${e})`,t.disabled=e===0||!Rn||!Dn,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=Iy.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=!Rn||!Dn}function E0(e){const t=e.every(n=>Ct.has(n));for(const n of e)t?Ct.delete(n):Ct.add(n);pr()}function Ly(e,t){const n=Dy(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),Iy.set(i,n),i.addEventListener("change",()=>E0(n));const o=document.createElement("span");return o.className="sr-only",o.textContent=t,r.append(i,o),r}function A0(e){if(!Dn)return[];const t=new Set(e),n=new Map(Qr.teams.filter(o=>o.status==="active").map(o=>[o.teamId,o.displayName])),r=new Map(Qr.identities.filter(o=>o.status==="active"||o.status==="pending").map(o=>[o.identityId,o.displayName])),i=new Map;for(const o of Qr.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 $y(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=A0(e),r=document.createElement("div");if(r.className="project-recipient-status",r.textContent=Dn?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 My(e,t){const n=document.createElement("button");return n.className="settings-button project-recipient-action project-selection-target",n.type="button",n.disabled=!Rn||!Dn,e.length===1?(n.textContent="Manage recipients",n.setAttribute("aria-label",`Manage recipients for ${t}`),n.dataset.projectFocusKey=`manage:${e[0]}`,n.addEventListener("click",()=>{Ti({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);pr(),Ti({mode:"project-add",projectIds:[...e].sort()})})),n}function I0(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function Dd(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function Ld(e){return e.project||e.display_project||"Unnamed Project"}function Oy(e){const t=String(e||"").trim();return t?_.lastCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function R0(){return new Set(_.lastCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function D0(e){return!po||e.authority_type!=="coordinator"||!e.group_id?!1:!R0().has(String(e.group_id).trim())}function jy(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function Fy(){us&&(us=!1,ot?.())}async function L0(){try{const e=await No();_.lastCoordinatorAdminStatus=e&&typeof e=="object"?e:null}catch{_.lastCoordinatorAdminStatus=null,_.lastCoordinatorAdminGroups=[],po=!1;return}if(_.lastCoordinatorAdminStatus?.readiness!=="ready"||!_.lastCoordinatorAdminStatus.has_admin_secret){_.lastCoordinatorAdminGroups=[],po=!1;return}try{const e=await Du(!1);_.lastCoordinatorAdminGroups=Array.isArray(e?.items)?e.items:[],po=!0}catch{_.lastCoordinatorAdminGroups=[],po=!1}}function $0(e){return e.kind==="team_default"}function $d(e){const t=e.label||"Untitled Space";return $0(e)?`${t} (default)`:t}function M0(e,t){const n=$d(e);return t.some(r=>r.scope_id!==e.scope_id&&$d(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function O0(e){const t=Oy(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 j0(e){return e?Pd.find(t=>t.scope_id===e)??null:null}function fs(e){const t=j0(e);return e?t?`${$d(t)} · ${O0(t)}`:"Unknown Space":"—"}function Md(){return Pd.filter(e=>e.scope_id!=="legacy-shared-review"&&!D0(e))}function F0(e){return Md().some(t=>t.scope_id===e)}function By(...e){for(const t of e)if(t&&F0(t))return t;return e.find(t=>!!t)??""}function B0(e){const t=Oy(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function U0(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function G0(){const e=new Map;for(const t of Md()){const n=U0(t),r=B0(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function Uy(e){for(const t of G0()){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=M0(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function H0(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 Od(e,t,n=[]){try{await hw({...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}),ur.delete(e.workspace_identity),ls.delete(e.workspace_identity),ne("Project Space assignment updated. Device access grants are unchanged."),ot?.()}catch(r){if(r instanceof xo){ur.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),ot?.();return}ne(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function K0(e,t){const n=e.filter(Id);if(n.length!==0)try{await gw({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.`),ds.delete(Dd(n[0])),ot?.()}catch(r){ne(r instanceof xo?"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 q0(e){if(e.mapping_id!=null)try{await vw(e.mapping_id),ur.delete(e.workspace_identity),ls.delete(e.workspace_identity),ne("Project Space assignment removed. The next fallback now applies."),ot?.()}catch(t){ne(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function Gy(e,t=!1){try{const n=uo.get(e.workspace_identity),r=await bw({...t&&n?{confirmation_token:n.confirmationToken}:{},confirmed:t,workspace_identity:e.workspace_identity});uo.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.`),ot?.()}catch(n){if(n instanceof Uu){uo.set(e.workspace_identity,{confirmationToken:n.preview.confirmation_token,localOwnedMemoryCount:n.preview.local_owned_memory_count,peerOwnedMemoryCount:n.preview.peer_owned_memory_count}),ot?.();return}ne(n instanceof Error?n.message:"Unable to forget project memories.","warning")}}async function W0(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 Rl({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 yw({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"}.`),ot?.()}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",Id(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=!Rn,Rn||(f.title="The complete project list is unavailable."),f.addEventListener("click",()=>ta([e.workspace_identity])),t.appendChild(f)}if(Zr(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=Md().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=`${fs(e.resolved_scope_id)} — not assignable`,f.disabled=!0,i.appendChild(f)}Uy(i),i.value=By(ls.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",()=>{Od(e,i.value)}),i.addEventListener("change",()=>{ls.set(e.workspace_identity,i.value),ur.delete(e.workspace_identity),t.querySelector(".project-space-guardrail-confirmation")?.remove(),s.textContent="Save Space",s.disabled=!i.value,ot?.()}),i.addEventListener("blur",Fy);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{Od(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",()=>{q0(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",()=>{W0(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",()=>{Gy(e)}),t.append(n,i,s,c,l,d,u);const p=ur.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 g=document.createElement("strong");g.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 v=document.createElement("ul");for(const S of p.warnings){const T=document.createElement("li"),N=document.createElement("strong");N.textContent=`${H0(S)}: `;const P=document.createElement("span");P.textContent=S.message,T.append(N,P),v.appendChild(T)}const b=document.createElement("button");b.className="settings-button",b.type="button",b.textContent="I understand, save Space",b.addEventListener("click",()=>{const S=ur.get(e.workspace_identity);!S||S.scopeId!==i.value||Od(e,S.scopeId,S.requiredGuardrailTokens)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{ur.delete(e.workspace_identity),ot?.()}),f.append(g,h,v,b,w),t.appendChild(f)}const m=uo.get(e.workspace_identity);if(m){const f=document.createElement("div");f.className="settings-note project-guardrail-confirmation",f.setAttribute("role","alert");const g=document.createElement("strong");g.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 v=document.createElement("p");v.textContent="Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device.";const b=document.createElement("button");b.className="settings-button danger",b.type="button",b.textContent="I understand, forget local memories",b.addEventListener("click",()=>{Gy(e,!0)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{uo.delete(e.workspace_identity),ot?.()}),f.append(g,h,v,b,w),t.appendChild(f)}return t}function Hy(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(Ly([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(My([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 · ${Ry(e.latest_session_at)}`,t.appendChild(o),t.appendChild($y([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=Rd(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${x0(e)} · ${e.identity_source} · ${Ry(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 v=document.createElement("strong");v.textContent="Project sharing";const b=document.createElement("ul");b.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=P0(w);const N=document.createElement("span");N.textContent=` — ${w.lifecycle.label}. ${w.lifecycle.explanation}`,S.append(T,N),b.appendChild(S)}h.append(v,b),s.appendChild(h)}if(Zr(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=I0(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 ${fs(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(v=>v.message).join(" ")}`,s.appendChild(h)}if(e.statuses.length>0){const h=document.createElement("div");h.className="project-inventory-badges";for(const v of e.statuses){const b=document.createElement("span");b.className=`project-status-badge ${v}`,b.textContent=N0(v),h.appendChild(b)}s.appendChild(h)}const p=document.createElement("details");p.className="project-inventory-details",p.open=Ed.has(e.workspace_identity),p.addEventListener("toggle",()=>{p.open?Ed.add(e.workspace_identity):Ed.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 g=[["Workspace identity",e.workspace_identity],["Project",e.project],["CWD",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",Rd(e)],["Suggested Space",e.suggested_scope_id?fs(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,v]of g){const b=document.createElement("dt");b.textContent=h;const w=document.createElement("dd");w.textContent=v==null||v===""?"—":String(v),f.append(b,w)}return p.appendChild(f),p.appendChild(V0(e)),t.appendChild(p),t}function z0(e){const t=[...new Set(e.map(n=>Rd(n)))];return t.length===1?t[0]:"Mixed Spaces"}function J0(e){if(e.length===1)return Hy(e[0]);const t=Dd(e[0]),n=e.filter(Zo),r=Dy(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster";const o=Ld(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(Ly(n,`Select all identities for ${Ld(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(My(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=z0(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($y(r));const g=document.createElement("div");g.className="project-inventory-actions";const h=e.filter(Id);if(h.length===0){const S=document.createElement("div");S.className="settings-note",S.textContent=e.every(Zr)?"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.",g.appendChild(S),d.appendChild(g)}else{const S=h.map(x=>({project:x,warnings:(x.guardrail_warnings??[]).filter(G=>G.requires_confirmation)})),T=S.some(({warnings:x})=>x.length>0),N=new Set(h.map(x=>x.suggested_scope_id).filter(x=>!!x)),P=new Set(h.map(x=>x.resolved_scope_id)),A=document.createElement("select");A.className="project-domain-select",A.setAttribute("aria-label",`Space for ${Ld(e[0])} group`);const M=document.createElement("option");M.value="",M.textContent="Choose Space…",A.appendChild(M),Uy(A),A.value=By(ds.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=!A.value||T,U.addEventListener("click",()=>{K0(h,A.value)}),A.addEventListener("change",()=>{A.value?ds.set(t,A.value):ds.delete(t),U.disabled=!A.value||T}),A.addEventListener("blur",Fy),g.append(A,U),N.size>1||P.size>1||T){const x=document.createElement("div");if(x.className="settings-note project-attention-note",x.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:E,warnings:$}of S){if($.length===0)continue;const L=document.createElement("li"),J=document.createElement("strong");J.textContent=`Blocked identity: ${E.workspace_identity}`;const H=document.createElement("span");H.textContent=` — ${$.map(k=>k.message).join(" ")}`,L.append(J,H),G.appendChild(L)}x.appendChild(G)}g.appendChild(x)}d.appendChild(g)}const v=document.createElement("details");v.className="project-inventory-details",v.open=Ad.has(t),v.addEventListener("toggle",()=>{v.open?Ad.add(t):Ad.delete(t)});const b=document.createElement("summary"),w=e.reduce((S,T)=>S+(T.guardrail_warnings??[]).filter(N=>N.severity==="warning").length,0);b.textContent=w>0?`Advanced Project administration — ${w.toLocaleString()} item${w===1?"":"s"} need attention`:"Advanced Project administration",v.appendChild(b),v.appendChild(d);for(const S of e)v.appendChild(Hy(S));return i.appendChild(v),i}function Y0(e){const t=new Map;for(const n of e){const r=Dd(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function Ky(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 qy(){document.getElementById("projectsInventorySkeleton")?.remove()}function Wy(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(qy(),n.textContent="",e.projects.length===0)Ky("No projects match those filters.");else for(const s of Y0(e.projects))n.appendChild(J0(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),pr(),r&&[...n.querySelectorAll("[data-project-focus-key]")].find(s=>s.dataset.projectFocusKey===r)?.focus()}function X0(e,t){L0().then(()=>{t===ps&&(jy()||Wy(e))})}async function Q0(){const e=new Map;let t=0;for(;;){const n=await Po({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 Vy(e,t,n){const r=Ke("recipientPolicyManagementMount");r&&Fm(r,ea(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Ct.clear(),pr(),ot?.()}})}async function zy(){const e=Ke("projectsInventoryMeta"),t=Ke("projectsInventoryList");if(!e||!t)return;if(jy()){us=!0;return}us=!1;const n=++ps;Rn=!1,Dn=!1,pr(),e.textContent="Loading project inventory…";try{const[r,i,o,s,c]=await Promise.all([Po({limit:xd,offset:lo,q:Ke("projectsSearch")?.value.trim()||void 0,status:Ke("projectsStatusFilter")?.value||void 0}),dw(),Q0().then(u=>({ok:!0,projects:u})).catch(()=>({ok:!1,projects:[]})),cw().then(u=>({ok:!0,review:u})).catch(u=>({ok:!1,error:u})),Gs().then(u=>({ok:!0,intent:u})).catch(u=>({ok:!1,error:u}))]);if(n!==ps)return;if(Pd=i.scopes,Rn=o.ok,Dn=c.ok,Qr=c.ok?c.intent:ms,o.ok){const u=new Set(ea(o.projects).map(p=>p.canonicalProjectIdentity));for(const p of Ct)u.has(p)||Ct.delete(p)}const l=Ke("projectShareFlowMount");l&&Gm(l,o.projects,{inventoryError:!o.ok});const d=Ke("recipientPolicyReviewMount");d&&("review"in s?C0(d,s.review,zy):T0(d,s.error)),Vy(o.projects,Qr,!o.ok||!c.ok),Wy(r),X0(r,n)}catch(r){if(n!==ps)return;Rn=!1,Dn=!1,Qr=ms;const i=Ke("projectShareFlowMount");i&&Gm(i,[],{inventoryError:!0}),Vy([],ms,!0),pr(),qy(),e.textContent="Project inventory failed to load.",Ky(r instanceof Error?r.message:"Unable to load project inventory.")}}function Z0(e){ot=e,Ct.clear();const t=Ke("projectsStatusFilter");if(t&&t.options.length===0)for(const[i,o]of Ay){const s=document.createElement("option");s.value=i,s.textContent=o,t.appendChild(s)}const n=()=>{lo=0,ot?.()};Ke("projectsSearch")?.addEventListener("input",n),t?.addEventListener("change",n),Ke("projectsPrevPage")?.addEventListener("click",()=>{lo=Math.max(0,lo-xd),ot?.()}),Ke("projectsNextPage")?.addEventListener("click",()=>{lo+=xd,ot?.()});const r=Ke("projectsShareSelected");r&&r.dataset.recipientPolicyBound!=="true"&&(r.dataset.recipientPolicyBound="true",r.addEventListener("click",()=>{Ct.size!==0&&Ti({mode:"project-add",projectIds:[...Ct].sort()})})),pr()}function jd(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 eD(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 Jy="codemem-settings-advanced",Yy="gpt-5.1-codex-mini",Xy="claude-4.5-haiku",tD=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],nD={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",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"},rD=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),iD={claudeCommand:"",codexCommand:"",observerProvider:"",observerModel:"",observerTierRoutingEnabled:!1,observerSimpleModel:"",observerSimpleTemperature:"",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 oD(){try{return globalThis.localStorage?.getItem(Jy)==="1"}catch{return!1}}function aD(e){try{globalThis.localStorage?.setItem(Jy,e?"1":"0")}catch{}}function dn(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function xe(e,t,n){if(dn(t,n))return t[n];if(dn(e,n))return e[n]}function Ie(e){return e==null?"":String(e)}function hs(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 sD(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function cD(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function at(e){const t=e.trim();return t===""?"":t}function lD(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:Xy,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:Yy,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:Xy,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:Yy,source:"Recommended (direct API)"}}function dD(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_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 at(Ie(n[t]));case"observer_runtime":return at(Ie(n.observer_runtime));case"observer_auth_source":return at(Ie(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(!dn(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(!dn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!dn(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 hs(n[t]);default:return dn(n,t)?n[t]:""}}function uD(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{dn(r,i)&&(r[i]=dD(t,i))}),r}function pD(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=jd(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(T){if(!i||n.has("claude_command"))throw T;const N=r.claude_command;o=Array.isArray(N)?N.filter(P=>typeof P=="string").map(P=>P.trim()).filter(P=>P.length>0):[]}let s=[];try{s=jd(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(T){if(!i||n.has("codex_command"))throw T;const N=r.codex_command;s=Array.isArray(N)?N.filter(P=>typeof P=="string").map(P=>P.trim()).filter(P=>P.length>0):[]}let c=[];try{c=jd(t.observerAuthCommand,{label:"observer auth command"})}catch(T){if(!i||n.has("observer_auth_command"))throw T;const N=r.observer_auth_command;c=Array.isArray(N)?N.filter(P=>typeof P=="string"):[]}let l={};try{l=eD(t.observerHeaders)}catch(T){if(!i||n.has("observer_headers"))throw T;const N=r.observer_headers;N&&typeof N=="object"&&!Array.isArray(N)&&Object.entries(N).forEach(([P,A])=>{typeof P=="string"&&P.trim()&&typeof A=="string"&&(l[P]=A)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),p=t.observerRichTemperature.trim(),m=t.observerRichMaxOutputTokens.trim(),f=t.rawEventsSweeperIntervalS.trim(),g=d===""?"":Number(d),h=u===""?"":Number(u),v=p===""?"":Number(p),b=m===""?"":Number(m),w=Number(f),S=f===""?"":w;if(d!==""&&!Number.isFinite(g))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 v!="number"||!Number.isFinite(v)||v<0))throw new Error("rich tier temperature must be a non-negative number");if(m!==""&&(typeof b!="number"||!Number.isFinite(b)||b<=0||!Number.isInteger(b)))throw new Error("rich tier max output tokens must be a positive integer");if(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:at(t.observerProvider),observer_model:at(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:at(t.observerSimpleModel),observer_simple_temperature:h,observer_rich_model:at(t.observerRichModel),observer_rich_temperature:v,observer_rich_reasoning_effort:at(t.observerRichReasoningEffort),observer_rich_reasoning_summary:at(t.observerRichReasoningSummary),observer_rich_max_output_tokens:b,observer_runtime:at(t.observerRuntime||"api_http")||"api_http",observer_auth_source:at(t.observerAuthSource||"auto")||"auto",observer_auth_file:at(t.observerAuthFile),observer_auth_command:c,observer_auth_timeout_ms:Number(t.observerAuthTimeoutMs||0)||"",observer_auth_cache_ttl_s:g,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:at(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:at(t.syncCoordinatorUrl),sync_coordinator_group:at(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function mD(e){const t=e.config||{},n=e.effective||{},r=xe(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=xe(t,n,"claude_command"),s=Array.isArray(o)?o.filter(p=>typeof p=="string"):[],c=xe(t,n,"codex_command"),l=Array.isArray(c)?c.filter(p=>typeof p=="string"):[],d=xe(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:Ie(xe(t,n,"observer_provider")),observerModel:Ie(xe(t,n,"observer_model")),observerTierRoutingEnabled:hs(xe(t,n,"observer_tier_routing_enabled")),observerSimpleModel:Ie(xe(t,n,"observer_simple_model")),observerSimpleTemperature:Ie(xe(t,n,"observer_simple_temperature")),observerRichModel:Ie(xe(t,n,"observer_rich_model")),observerRichTemperature:Ie(xe(t,n,"observer_rich_temperature")),observerRichReasoningEffort:Ie(xe(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:Ie(xe(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:Ie(xe(t,n,"observer_rich_max_output_tokens")),observerRuntime:Ie(xe(t,n,"observer_runtime"))||"api_http",observerAuthSource:Ie(xe(t,n,"observer_auth_source"))||"auto",observerAuthFile:Ie(xe(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:Ie(xe(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:Ie(xe(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:Ie(xe(t,n,"observer_max_chars")),packObservationLimit:Ie(xe(t,n,"pack_observation_limit")),packSessionLimit:Ie(xe(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:Ie(xe(t,n,"raw_events_sweeper_interval_s")),syncEnabled:hs(xe(t,n,"sync_enabled")),syncHost:Ie(xe(t,n,"sync_host")),syncPort:Ie(xe(t,n,"sync_port")),syncInterval:Ie(xe(t,n,"sync_interval_s")),syncMdns:hs(xe(t,n,"sync_mdns")),syncCoordinatorUrl:Ie(xe(t,n,"sync_coordinator_url")),syncCoordinatorGroup:Ie(xe(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:Ie(xe(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:Ie(xe(t,n,"sync_coordinator_presence_ttl_s"))}}function fD(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=lD(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),at(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>dn(t,r))?"Env override":n.source}: ${n.model}`}function hD(e){return e.observerTierRoutingEnabled?"On: codemem routes simpler batches to a lighter model and richer batches to a higher-quality configuration. Rich-tier OpenAI requests default to the Responses transport, and 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 gD(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function vD(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 yD(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.1-codex-mini` for Direct API or Local Codex session; `claude-4.5-haiku` for Local Claude session."}function bD(e){return!e}function _D(e,t,n){return t.has(e)||n.has(e)}function wD(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var V={open:!1,previouslyFocused:null,activeTab:"observer",baseline:{},envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,showAdvanced:oD(),controller:null,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...iD}}};function SD(){V.controller?.hideTooltip()}function mr(e){if(V.controller){V.controller.setRenderState(e);return}V.renderState={...V.renderState,...e}}function CD(e){mr({values:{...V.renderState.values,...e}})}function TD(e){const t=["observer","queue","sync"].includes(e)?e:"observer";V.activeTab=t,V.controller?.setActiveTab(t)}function gs(e,t=!0){_.settingsDirty=e,t&&V.controller?.setDirty(e)}function ND(e){V.showAdvanced=e,V.controller?.setShowAdvanced(e)}function Qy(){return V.open}function kD(e){return _D(e,V.protectedKeys,rD)}function Zy(e={}){return pD({values:V.renderState.values,touchedKeys:V.touchedKeys,baseline:V.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function xD(e){mr({observerStatus:e&&typeof e=="object"?e:null})}function PD(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=mD(t);V.envOverrides=i,V.protectedKeys=new Set(o),_.configDefaults=n,_.configPath=t.path||"",mr({effectiveText:Object.keys(i).length>0?"Some fields are managed by environment settings.":"",overridesVisible:Object.keys(i).length>0,pathText:_.configPath?`Config path: ${_.configPath}`:"Config path: n/a",providers:sD(t.providers),statusText:"No unsaved changes",values:s}),V.touchedKeys=new Set;try{V.baseline=uD(Zy({allowUntouchedParseErrors:!0}),r,i)}catch{V.baseline={}}gs(!1)}async function ED(){if(!V.open)try{const[e,t]=await Promise.all([k_(),N_().catch(()=>null)]);PD(e),xD(t)}catch{}}function Fd(e){return String(e||"").replace(/_/g," ")}function Bd(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 ID(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 RD(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function DD({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),": ",ID(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 ${RD(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 eb(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 mo(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function LD(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 $D(){const e=Ae("settingsModal");(LD(e)[0]||e)?.focus()}function MD(){const[e,t]=I({anchor:null,content:"",visible:!1}),n=B(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=mo(u.target);p&&r(p)},s=u=>{const p=mo(u.target);if(!p)return;const m=u.relatedTarget;m instanceof Element&&p.contains(m)||i()},c=u=>{const p=mo(u.target);p&&r(p)},l=u=>{mo(u.target)&&i()},d=u=>{const p=mo(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&&eb(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&&eb(n.current,e.anchor)};return globalThis.addEventListener("resize",r),document.addEventListener("scroll",r,!0),()=>{globalThis.removeEventListener("resize",r),document.removeEventListener("scroll",r,!0)}},[e.anchor,e.visible]),{tooltipPortal:ke(()=>typeof document>"u"?null: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 OD({DialogContent:e,onClose:t}){const[n,r]=I(V.open),[i,o]=I(["observer","queue","sync"].includes(V.activeTab)?V.activeTab:"observer"),[s,c]=I(_.settingsDirty),[l,d]=I(V.renderState),[u,p]=I(V.showAdvanced),{tooltipPortal:m,setTooltip:f}=MD();V.open=n,V.activeTab=i,_.settingsDirty=s,V.renderState=l,V.showAdvanced=u,K(()=>(V.controller={hideTooltip:()=>{f({anchor:null,content:"",visible:!1})},setActiveTab:h=>{const v=["observer","queue","sync"].includes(h)?h:"observer";V.activeTab=v,o(v)},setDirty:h=>{_.settingsDirty=h,c(h)},setOpen:h=>{V.open=h,r(h)},setRenderState:h=>{const v={...V.renderState,...h};V.renderState=v,d(v)},setShowAdvanced:h=>{V.showAdvanced=h,aD(h),p(h)}},()=>{V.controller&&(V.controller=null)}),[]),K(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const g=re(()=>{V.startPolling&&V.refresh&&t(V.startPolling,V.refresh)},[t]);return a(te,{children:[a(wi,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:h=>{h.preventDefault()},onOpenAutoFocus:h=>{h.preventDefault(),$D()},onOpenChange:h=>{if(h){r(!0);return}g()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:a(e,{})}),m]})}function Fe({children:e,className:t="field",hidden:n=!1,id:r}){return a("div",{className:t,hidden:n,id:r,children:e})}function fo({children:e,hidden:t=!1}){return a("div",{className:"settings-note",hidden:t,children:e})}function Ud({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 jD({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(Ud,{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(Fe,{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(Fe,{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(Ce,{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(Fe,{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(Fe,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),a(Kr,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),a("div",{className:"small",children:m("codex_command")})]}),a(Fe,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),a(Kr,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),a("div",{className:"small",children:m("claude_command")})]}),a(Fe,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),a(Ce,{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(Fe,{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(Fe,{hidden:!r,id:"observerAuthFileField",children:[a("label",{htmlFor:"observerAuthFile",children:"Token file path"}),a(Ce,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),a("div",{className:"small",children:m("observer_auth_file")})]}),a(Fe,{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(Kr,{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(fo,{hidden:o(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),a(Fe,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),a(Ce,{id:"observerAuthTimeoutMs",min:"1",onInput:s("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),a(Fe,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),a(Ce,{id:"observerAuthCacheTtlS",min:"0",onInput:s("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),a(Fe,{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(Kr,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),a("div",{className:"small",children:m("observer_headers")})]})]})]})}function vs({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(Br,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"})]})}function FD({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:o}){return a(te,{children:[a(Ud,{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(Fe,{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(Ce,{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(vs,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),a("div",{className:"small",children:o()}),a(fo,{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(Fe,{hidden:!t,children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerSimpleModel",children:"Simple tier 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(Ce,{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(Fe,{hidden:!t,children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerRichModel",children:"Rich tier 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(Ce,{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(Fe,{className:"field settings-advanced",hidden:!t||n(),children:[a("label",{htmlFor:"observerSimpleTemperature",children:"Simple tier temperature"}),a(Ce,{id:"observerSimpleTemperature",min:"0",onInput:r("observerSimpleTemperature"),step:"0.1",type:"number",value:e.observerSimpleTemperature})]}),a(Fe,{className:"field settings-advanced",hidden:!t||n(),children:[a("label",{htmlFor:"observerRichTemperature",children:"Rich tier temperature"}),a(Ce,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),a(Fe,{className:"field settings-advanced",hidden:!t||n(),children:[a("label",{htmlFor:"observerRichReasoningEffort",children:"Rich tier reasoning effort"}),a(Ce,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"leave empty for default",value:e.observerRichReasoningEffort})]}),a(Fe,{className:"field settings-advanced",hidden:!t||n(),children:[a("label",{htmlFor:"observerRichReasoningSummary",children:"Rich tier reasoning summary"}),a(Ce,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"leave empty for default",value:e.observerRichReasoningSummary})]}),a(Fe,{className:"field settings-advanced",hidden:!t||n(),children:[a("label",{htmlFor:"observerRichMaxOutputTokens",children:"Rich tier max output tokens"}),a(Ce,{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(fo,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),a(Fe,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),a(Ce,{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(Fe,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),a(Ce,{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 BD({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(te,{children:[a(Ud,{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(vs,{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(Ce,{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(Ce,{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(Ce,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),a(vs,{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(Ce,{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(Ce,{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(fo,{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(Ce,{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(Ce,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function UD({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=>Dr(p,{onSubmit:s,disabled:u}),children:[a("div",{className:"modal-header",children:[a("h2",{id:"settingsTitle",children:"Settings"}),a(Mo,{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(vs,{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(fo,{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(Vf,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:tD,triggerClassName:"settings-tab",value:t,children:[a(Yn,{className:"settings-panel",forceMount:!0,value:"observer",children:a(jD,{...e,observerStatusBannerSlot:d})}),a(Yn,{className:"settings-panel",forceMount:!0,value:"queue",children:a(FD,{...e})}),a(Yn,{className:"settings-panel",forceMount:!0,value:"sync",children:a(BD,{...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 GD(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};return Object.entries(t).forEach(([c,l])=>{o(c)||dn(r,c)&&!i.has(c)||cD(l,n[c])||(s[c]=l)}),s}function HD(e){const t=s=>{const c=nD[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 KD(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=>Fd(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>Fd(String(p))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>Fd(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: ${Bd(r)}.`),i.length&&d.push(`Live settings updated: ${Bd(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 ${Bd(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 qD=()=>fD(V.renderState.values,V.envOverrides),WD=()=>hD(V.renderState.values),VD=()=>gD(V.renderState.values),zD=()=>vD(V.renderState.values),JD=()=>yD(V.renderState.values),YD=()=>bD(V.showAdvanced),{onTextInput:XD,onSelectValueChange:QD,onSwitchInput:ZD}=HD({getTouchedKeys:()=>V.touchedKeys,getValues:()=>V.renderState.values,updateFormState:CD,setDirty:e=>gs(e)});function eL(){const e=V.renderState.observerStatus;return a(DD,{status:e})}function tL(){const e=V.renderState.values,t=String(_.configDefaults?.observer_max_chars||""),n=e.observerAuthSource==="file",r=e.observerAuthSource==="command",i=e.observerTierRoutingEnabled;return a(UD,{panelProps:{values:e,observerMaxCharsDefault:t,providerOptions:Array.from(new Set(V.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:YD,onTextInput:XD,onSelectValueChange:QD,onSwitchInput:ZD,getObserverModelLabel:VD,getObserverModelTooltip:zD,getObserverModelDescription:JD,getObserverModelHint:qD,getTieredRoutingHelperText:WD,protectedConfigHelp:wD},activeTab:V.activeTab,showAdvanced:V.showAdvanced,renderState:V.renderState,settingsDirty:_.settingsDirty,onClose:()=>{V.startPolling&&V.refresh&&ys(V.startPolling,V.refresh)},onSave:()=>{V.startPolling&&V.refresh&&oL(V.startPolling,V.refresh)},onActiveTabChange:TD,onAdvancedToggle:ND,observerStatusBannerSlot:a(eL,{})})}function nL(){return a(OD,{DialogContent:tL,onClose:ys})}function rL(){const e=Ae("settingsDialogMount");e&&Ue(a(nL,{}),e)}function tb(){Ae("settingsDialogMount")&&(V.shellMounted||(rL(),V.shellMounted=!0))}function iL(e){V.shellMounted||tb(),V.open=!0,V.previouslyFocused=document.activeElement,e(),V.controller?.setOpen(!0)}function ys(e,t){if(_.settingsDirty&&!globalThis.confirm("Discard unsaved changes?")){V.controller?.setOpen(!0);return}V.open=!1,V.controller?.setOpen(!1),SD(),(V.previouslyFocused&&typeof V.previouslyFocused.focus=="function"?V.previouslyFocused:Bc("settingsButton"))?.focus(),V.previouslyFocused=null,V.touchedKeys=new Set,e(),t()}async function oL(e,t){if(!V.renderState.isSaving){mr({isSaving:!0,statusText:"Saving changes…"});try{const n=GD({current:Zy({allowUntouchedParseErrors:!0}),baseline:V.baseline,envOverrides:V.envOverrides,touchedKeys:V.touchedKeys,isProtected:kD});if(Object.keys(n).length===0){mr({isSaving:!1,statusText:"No unsaved changes"}),gs(!1),ys(e,t);return}const r=KD(await x_(n));mr({isSaving:!1,statusText:"Saved changes"}),gs(!1),ys(e,t),ne(r.message,r.type)}catch(n){mr({isSaving:!1,statusText:`Save failed: ${n instanceof Error?n.message:"unknown error"}`})}}}function aL(e,t,n){V.startPolling=t,V.refresh=n,tb(),Bc("settingsButton")?.addEventListener("click",()=>iL(e))}function sL(e){e.dataset.syncRenderRoot="preact"}function cL(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function Qe(e,t){sL(e),Ue(t,e)}function ei(e){e.dataset.syncRenderRoot==="preact"&&Ue(null,e)}function lL(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 dL(e){return typeof e=="object"&&e!==null}function uL(e,t){return _.pairingCommandRaw="",{payloadText:e,hintText:t}}function pL(e){if(!dL(e))return uL("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 _.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function mL(){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 fL(){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 hL(){const e=_.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 gL(){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 vL(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 yL({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 bL({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 nb({text:e}){return a(te,{children:e})}function _L({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function wL(e,t){if(!t.length){ei(e);return}Qe(e,a(yL,{items:t}))}function SL(e,t,n){if(!t.length){ei(e);return}Qe(e,a(bL,{attempts:t,note:n}))}function fr(e,t){Qe(e,a(_L,{...t}))}function rb(e,t,n){Qe(e,a(nb,{text:n.payloadText})),t&&Qe(t,a(nb,{text:n.hintText}))}function ib({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:o,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=B(null),p=B(null),m=B(!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(ya,{forceMount:!0,asChild:!0,children:a("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return a(va,{open:e,onOpenChange:t,children:[a(Qf,{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 CL({open:e,onOpenChange:t}){return a(ib,{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(Ce,{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(Ce,{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(Kr,{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 TL({contentHost:e,open:t,onOpenChange:n}){return a(ib,{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 NL(e,t){Qe(e,a(CL,{...t}))}function kL(e,t){Qe(e,a(TL,{...t}))}function de(e){return String(e??"").trim()}function xL(e){return de(e).replace(/\s+/g," ").toLowerCase()}function PL(e){const t=de(e);return t?t.slice(0,8):"Unnamed device"}function ob(e){return de(e?.last_error).toLowerCase()}function ab(e){return e.includes("401")&&e.includes("unauthorized")}function sb(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var EL={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function cb(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=cb(e);return!de(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function lb(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=LL(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=>db(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=>db(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 db(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 IL(n)?"trust":RL(n)?"scope":null}function IL(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function RL(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function DL(e){const t=de(e?.reason);return EL[t]??(t.replaceAll("_"," ")||"sync filters")}function LL(e){const t=new Map;for(const n of e){const r=DL(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 ub(e){const t=de(e.localName);if(t)return t;const n=de(e.coordinatorName);return n||PL(de(e.deviceId))}function $L(e){const t=de(e.localName),n=de(e.coordinatorName);return t||n?!1:!!de(e.deviceId)}function ML(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 ho(e){const t=de(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=ob(e);return ab(n)?"needs-repair":sb(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function ti(e){const t=e?.status||{},n=de(t.peer_state),r=ob(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}:ab(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}:sb(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 OL={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 jL(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:OL[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 pb(e){return Array.isArray(e)?e.map(t=>de(t)).filter(t=>!!t):[]}function mb(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 bs(e,t){return e?e.replaceAll("_"," "):t}function FL(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=[bs(de(r.kind),"user"),bs(de(r.authority_type),"local"),`${bs(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 fb(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=bs(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 BL=["personal","private","home","mine","me"],UL=["oss","open source","opensource","community","public"],GL=["work","client"],HL=["local","legacy","review"];function KL(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>de(t)??"").join(" ").toLowerCase()}function qL(e){return[e.scope_id,e.label,e.kind].map(t=>de(t)??"").join(" ").toLowerCase()}function hb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gd(e,t){const n=KL(e);return t.some(r=>{const i=hb(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function gb(e){return Gd(e,BL)||Gd(e,UL)}function WL(e){const t=qL(e);return HL.some(n=>{const r=hb(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function VL(e){return!gb(e)&&(!WL(e)||Gd(e,GL))}function zL(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(gb),r=t.some(VL);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 JL(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function YL(e){const t=pb(e?.effective_include),n=pb(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${mb(t,"all projects")}`,o=`Exclude filter: ${mb(n,"no exclusions")}`,s=JL(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 XL(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=de(n?.display_name),i=de(n?.actor_id),o=xL(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 vb(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 QL=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),ZL=new Set(["pending","verifying","waiting"]);function e$(e){return(Array.isArray(e?.groups)?e.groups.map(t=>de(t)).filter(Boolean):[]).join(", ")||"none"}function yb(e){return de(e?.projects?.[0]?.display_name)||"the shared Project"}function t$(e){const t=e?.items?.find(n=>n.state!=="active");return de(t?.canonicalProjectIdentity)||"the shared Project"}function n$(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=ti(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function r$(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&ti(n).state==="mutual-trust"&&!fb(n).rows.some(r=>r.status==="pending"))}function i$(e){return e.some(t=>de(t.status?.peer_state)==="online"&&ti(t).state==="mutual-trust")}function o$(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=ti(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function a$(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 bb(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=e$(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=yb(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&&QL.has(m)}),d=i.find(p=>{const m=p.state;return m!==void 0&&ZL.has(m)});if(l||d){const p=l?yb(l):t$(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(a$(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(n$(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."}:o$(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&&r$(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}:i$(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 s$(e){return e.discovered?.stale?e.peer?ho(e.peer)!=="connected":!0:!1}function _b(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 Hd(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 c$(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 l$(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 d$(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 u$(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=d$(n,r),o=e.duplicatePersonDecisions??{},s=XL(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=ub({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId}),u=l.peer?ho(l.peer):"waiting",p=l.peer?ti(l.peer):null,m=de(l.discovered?.fingerprint),f=de(l.peer?.fingerprint);if(l.peer&&m&&f&&m!==f){c.push(_b({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 g=p?.description||de(l.peer?.last_error)||"Sync needs review.";c.push(_b({id:l.deviceId,name:d,title:p?.state==="needs-repairing"?`${d} needs re-pairing`:`${d} needs review`,summary:g}))}l.peer&&p?.state==="trusted-by-you"&&c.push(Hd({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(Hd({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(Hd({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&&$L({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(c$({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:bb({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>ho(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>s$(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 Ln(e){const t=document.getElementById(e);t&&t.remove()}var Sb=!1;function p$(e){Sb=e}var Kd=!1;function m$(e){Kd=e}var qd=!1;function f$(e){qd=e}var h$=new Set,Wd=new Set,Vd=new Set,Cb="codemem-sync-duplicate-person-decisions";function g$(e){const t=String(e||"").trim();t&&(Wd.add(t),Vd.add(t),h$.add(t))}function zd(e){const t=String(e||"").trim();return!!t&&Wd.has(t)}function v$(e){const t=String(e||"").trim();t&&Wd.delete(t)}function y$(e){const t=String(e||"").trim();return!t||!Vd.has(t)?!1:(Vd.delete(t),!0)}function Jd(){try{const e=localStorage.getItem(Cb);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Tb(e){try{localStorage.setItem(Cb,JSON.stringify(e))}catch{}}function Nb(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function b$(){return Jd()}function _$(e,t){const n=Nb(e);if(!n)return;const r=Jd();r[n]=t,Tb(r)}function w$(e){const t=Nb(e);if(!t)return;const n=Jd();delete n[t],Tb(n)}function kb(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function xb(e){const t=String(e||"");return t?kb(t):""}function S$(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function C$(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function _s(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 ws(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":_s(e)}function T$(e){return(Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function Pb(){return vb({actors:_.lastSyncActors,peers:_.lastSyncPeers,duplicatePeople:_.lastSyncViewModel?.duplicatePeople}).visibleActors}function N$(e=""){const t=[{value:"",label:"No person assigned"}],n=Pb(),r=(Array.isArray(_.lastSyncActors)?_.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:ws(i)})}),t.filter((i,o,s)=>o===s.findIndex(c=>c.value===i.value))}function Eb(e){return Pb().filter(t=>String(t?.actor_id||"")!==e)}function k$(e,t){const n=Eb(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${ws(n)}. Assigned devices move now; existing memories keep their current provenance.`}function Yd(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=fa("div","sync-action"),i=fa("div","sync-action-text");i.textContent=n.label,i.appendChild(fa("span","sync-action-command",n.command));const o=fa("button","settings-button sync-action-copy","Copy");o.addEventListener("click",()=>Ai(n.command,o)),r.append(i,o),e.appendChild(r)})}}function Ab(e,t){return t&&e.error_redacted===!0}function Ib(){const e=document.getElementById("syncAttempts");if(!e)return;const t=_.lastSyncAttempts,n=String(_.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){fr(e,hL());return}const r=vL(n,t.slice(0,5).some(i=>i.status==="error"));SL(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(_.lastSyncPeers)?_.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=Ri();if(d&&i.error){const m=String(i.error);u.push(p?kb(m):m),Ab(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):"",...Ab(i,p)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}}),r)}function x$(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&fr(e,fL()),t&&fr(t,gL()),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."),Yd(r,[])}function ni(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function P$(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=ni(n.would_remove),o=ni(n.ambiguous),s=ni(r.applied),c=ni(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 Rb(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;Ln("syncDiagSkeleton");const r=_.lastSyncStatus;if(!r){fr(e,mL()),Yd(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||lL(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"),g=r.retention||{},h=r.cleanup_diagnostics,v=h?.stale_peer_rows??{},b=ni(v.would_remove),w=ni(v.ambiguous),S=g.enabled===!0,T=Number(g.last_deleted_ops||0),N=g.last_run_at||null,P=String(g.last_error||""),A=f==="offline-peers"?"Offline peers":f==="needs_attention"?"Needs attention":f==="rebootstrapping"?"Rebootstrapping":Kg(f),M=f==="disabled"||r.enabled===!1,U=Object.keys(i).length,x=!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"]:x?["Advanced sync is ready but idle","Use Show pairing command under People & devices to connect another device, then this panel will start showing live peer status and recent attempts"]:[`Advanced state: ${A}`,`Peers: ${U}`,c?`Last sync: ${xn(qr(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(N?`Retention last ran ${xn(qr(N))} ago (approx oldest-first)`:"Retention enabled"),b>0?$.push(`${b.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"}]:x?[{label:"State",value:"No peers"},{label:"Mode",value:"Ready to pair"},{label:"Pending events",value:p},{label:"Last sync",value:"Waiting for first peer"}]:[{label:"State",value:A},{label:"Pending events",value:p},{label:"Last sync",value:c?`${xn(qr(c))} ago`:"never"},{label:"Last peer ping",value:l?`${xn(qr(l))} ago`:"never"},{label:"Retention",value:S?N?`${T.toLocaleString()} ops last run (approx)`:"Enabled":"Disabled"}];!M&&!x&&(d||u)&&G.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!M&&!x&&s.seconds_since_last&&G.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!M&&!x&&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&&!x&&h&&G.push({label:"Cleanup",value:P$(h)}),wL(e,G);const E=[];x||f==="offline-peers"||(f==="stopped"?(E.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),E.push({label:"Run one sync pass now.",command:"codemem sync once"})):f==="needs_attention"?E.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):f==="rebootstrapping"?E.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||f==="error"?(E.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),E.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!M&&!x&&p>0&&E.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!M&&w>0?E.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!M&&b>0&&E.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),Yd(n,E)}var E$="syncRedactMount",A$="syncRedactLabel",Db=()=>{};function I$(e){Db=e}var Xd=()=>{};function Qd(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;kL(e,{contentHost:t,open:_.syncPairingOpen,onOpenChange:r=>{if(uN(r),Qd(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&rb(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}Xd()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=_.pairingCommandRaw;r&&await Ai(r,n)})}function Zd(){Qd();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;rb(e,t,pL(_.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!_.pairingCommandRaw)}function Lb(){const e=document.getElementById(E$);e&&Qe(e,y(Br,{"aria-labelledby":A$,checked:Ri(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{pN(t),Lb(),Xd(),Rb(),Db(),Ib(),Zd()},thumbClassName:"sync-redact-switch-thumb"}))}function R$(e){Xd=e,Qd(),Lb()}function D$(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function ri(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),D$(e),e.addEventListener("input",()=>go(e),{once:!0}),!1}function go(e){e.classList.remove("sync-field-error");const t=e.parentElement?.querySelector(".sync-field-hint");t&&t.remove()}function Ze(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 hr=new Map,eu=null,L$={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 $$(e){return L$[e instanceof Error?e.message:String(e)]??"Setup could not be retried. Review diagnostics for details."}function M$(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 O$(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function tu(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 j$({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[o,s]=I(!1),[c,l]=I(()=>hr.get(e.operation_id)??null),d=B(null),u=e.lifecycle.primary_action;K(()=>{eu!==e.operation_id||!d.current||(eu=null,d.current.focus())},[c?.message,e.operation_id]);async function p(h){s(!0);try{let v=h;if(!v&&n){const w=(await n(e.operation_id)).lifecycle.primary_action;w?.kind==="copy_invite"&&(v=w.invite_link)}if(!v)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(w=>navigator.clipboard.writeText(w)))(v);const b={message:"Invite copied.",tone:"success"};hr.set(e.operation_id,b),l(b)}catch(v){const b={message:v instanceof Error?v.message:"Invite could not be copied.",tone:"warning"};hr.set(e.operation_id,b),l(b)}finally{s(!1)}}async function m(){s(!0);try{const h=await t(e.operation_id),v=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"};hr.set(e.operation_id,v),eu=e.operation_id,l(v),await r()}catch(h){const v={message:$$(h),tone:"warning"};hr.set(e.operation_id,v),l(v),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function f(){const h=e.projects.map(v=>v.project_id?.trim()).filter(v=>!!v);if(h.length!==e.projects.length){const v={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};hr.set(e.operation_id,v),l(v);return}if(!ta(h,e.person.display_name)){const v={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};hr.set(e.operation_id,v),l(v)}}function g(){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":`${tu(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:tu(e.lifecycle.state)}),a("ul",{"aria-label":`${tu(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((h,v)=>a("li",{className:"peer-scope-chip",children:h.display_name},`${h.display_name}:${v}`))}),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:g,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 F$({operations:e,...t}){const n=e[0].person,r=O$(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(j$,{operation:i,...t},i.operation_id))]})}function B$(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:M$(e.operations).map(t=>a(F$,{...e,operations:t},t[0].person.actor_id))})}function U$(e,t){Qe(e,a(B$,{...t}))}function $b({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 G$(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 H$({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=_s(e),c=T$(o),l=Eb(o),d=l.map(E=>String(E.actor_id||"")).join("|"),[u,p]=I(s),[m,f]=I(!1),[g,h]=I("Rename"),[v,b]=I(!1),[w,S]=I("Merge into selected person"),[T,N]=I(""),[P,A]=I(!1);K(()=>{p(s),f(!1),h("Rename"),b(!1),S("Merge into selected person"),N(""),A(!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(E=>{const $=String(E.actor_id||"");return{label:E.is_local?ws(E):_s(E),value:$}})];async function x(){const E=u.trim();if(!E)return;f(!0),h("Saving…");let $=!1;try{await n(o,E),$=!0}catch{h("Retry rename")}finally{f(!1),$&&h("Rename")}}async function G(){if(!T)return;const E=l.find(L=>String(L.actor_id||"")===T);if(!E||!await Kt({title:`Merge ${s} into ${_s(E)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;b(!0),S("Merging…");let $=!1;try{await r(T,o),$=!0}catch{S("Retry merge")}finally{b(!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:ws(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?G$(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(Ce,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:m||v,type:"text",value:u,onInput:E=>p(E.currentTarget.value),onKeyDown:E=>Dr(E,{onSubmit:()=>{x()},disabled:m||v||!u.trim()})}),a("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:m||v,onClick:()=>{x()},children:g}),a("button",{type:"button",className:"settings-button danger",disabled:m||v,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||v,onClick:()=>A(E=>!E),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:v||l.length===0,itemClassName:"sync-radix-select-item",onValueChange:N,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:v||l.length===0||!T,onClick:()=>{G()},children:w})]}),a("div",{className:"peer-meta actor-merge-note",children:M})]}):null]})})]})}function K$({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(H$,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a($b,{detail:"Create a named person here, then assign devices below so team ownership stays readable.",title:"No people set up yet."})}function q$(e,t){Qe(e,a(K$,{...t}))}function W$(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function V$(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 z$({devices:e}){return a(te,{children:V$(e)})}function J$(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 Y$(e){const t=W$(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),ei(e.mount),ei(e.meta);return}const n=t.map(J$),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(z$,{devices:t}))}var X$={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function Q$({state:e,size:t=8,"aria-label":n}){return a("span",{"aria-label":n??X$[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 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 eM(e){switch(ho(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var Ss=null,Mb=0,nu=new Set;function Ob(e){if(Ss!==e){Ss=e,Mb+=1;for(const t of nu)t(Mb)}}function tM(){const[,e]=I(0);return K(()=>(nu.add(e),()=>{nu.delete(e)}),[]),Ss}var nM={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 rM(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 iM(){window.location.hash="coordinator-admin"}function ru(e=_.lastCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function oM({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=ti(e),d=nM[ML(e)],u=e.status||{},p=FL(e),m=zd(o),f=m&&p.total===0,g=zL(e),h=jL(e),v=fb(e),b=YL(e.project_scope||{}),w=S$(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),N=Number.isFinite(T)&&T>0?T:0,P=S.length?S.map(ae=>Ri()?xb(ae):ae).join(" · "):N>0?`${N} ${N===1?"address":"addresses"} hidden`:"No addresses",A=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||""),x=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=y$(o),E=B(null),[$,L]=I(s),[J,H]=I(()=>_.syncPeerFeedbackById.get(o)??null),[k,R]=I(!1),[j,W]=I("Save name"),[ge,le]=I(!1),[ce,be]=I(!1),[Y,fe]=I("Remove device"),[X,_e]=I(String(e.actor_id||"")),[he,Q]=I(!1),[$e,ue]=I("Save assignment"),q=ke(()=>{const ae=N$(X),Ge=ae.some(On=>On.value===X);return X&&!Ge&&ae.push({value:X,label:e.claimed_local_actor?"You":String(e.actor_display_name||"Current assignment")}),ae},[e.actor_display_name,e.claimed_local_actor,X,_.lastSyncActors,_.lastSyncPeers,_.lastSyncViewModel]);K(()=>{m&&p.total>0&&v$(o)},[p.total,o,m]),K(()=>{L(s),H(_.syncPeerFeedbackById.get(o)??null),R(!1),W("Save name"),le(!1),be(!1),fe("Remove device"),_e(String(e.actor_id||"")),Q(!1),ue("Save assignment")},[s,e.actor_id,o]),K(()=>{!G||!E.current||queueMicrotask(()=>E.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),_.syncPeerFeedbackById.set(o,Ge),document.querySelector(`[data-device-name-input="${CSS.escape(o)}"]`)?.focus();return}R(!0),W("Saving…");try{const Ge=await r(o,ae);H(Ge),_.syncPeerFeedbackById.set(o,Ge),W("Save name")}catch{W("Retry")}finally{R(!1)}}async function qe(){if(f){const ae=ru();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}le(!0);try{const ae=await i(e,w);H(ae),ae&&_.syncPeerFeedbackById.set(o,ae)}finally{le(!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),fe("Removing…");let ae=!1;try{await n(o,c),ae=!0}catch{fe("Retry remove")}finally{be(!1),ae&&fe("Remove device")}}async function et(){if(o){Q(!0),ue("Saving…");try{const ae=await t(o,X||null);H(ae),_.syncPeerFeedbackById.set(o,ae),ue("Save assignment")}catch{ue("Retry")}finally{Q(!1)}}}const pn=tM()===o&&o!=="",Lt=`device-drawer-${o||"unknown"}`,Nt=eM(e),$t=M?`Sync: ${ir(M)}`:"Sync: never",tt=ru(),Mt=`${pn?"Collapse":"Expand"} device ${s}`;return a(va,{asChild:!0,open:pn,onOpenChange:ae=>{ae?Ob(o):Ss===o&&Ob(null)},children:a("div",{ref:E,className:"peer-card","data-peer-device-id":o||void 0,children:[a(Qf,{asChild:!0,children:a("button",{"aria-label":Mt,className:"device-row-head device-row-head--trigger",type:"button",children:[a(Q$,{state:Nt}),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,g.badgeLabel?a("span",{className:"badge badge-offline",title:"Review whether explicit Space access matches this device's intended role.",children:g.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(ya,{"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:ge,onClick:()=>{qe()},title:w?void 0:"Address details are hidden; sync will target this device by ID.",children:ge?"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(Ce,{"aria-label":`Friendly name for ${s}`,className:"peer-scope-input","data-device-name-input":o||void 0,disabled:k,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:k,onClick:()=>{oe()},children:j}),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:tt?"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}),x?a("div",{className:"peer-meta",children:x}):null,a("div",{className:"peer-meta",children:[M?`Sync: ${ir(M)}`:"Sync: never",U?`Ping: ${ir(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,g.isVisible?a("div",{className:"settings-note",role:"status",children:[a("strong",{children:g.title}),a("div",{children:g.message}),a("div",{children:g.detail})]}):null,a("div",{className:"peer-meta",children:b.note}),a("div",{className:"peer-scope-summary",children:"Space sync progress"}),a("div",{className:"peer-meta",children:v.total>0?"Per-Space progress for this device. Open details to see technical identifiers.":v.emptyMessage}),v.rows.length>0?a("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:v.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 ",ir(h.lastAt)]}):null]}):null,a("div",{className:"peer-scope-summary",children:"Who this device belongs to"}),a("div",{className:"peer-meta",children:A}),e.claimed_local_actor?a("div",{className:"peer-meta",children:rM(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:he,itemClassName:"sync-radix-select-item",onValueChange:_e,options:q,placeholder:"No person assigned yet",triggerClassName:"sync-radix-select-trigger sync-actor-select",value:X,viewportClassName:"sync-radix-select-viewport"})}),a("button",{type:"button",className:"settings-button",disabled:he,onClick:()=>{et()},children:$e})]}),a("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),a("div",{className:"peer-meta",children:[b.statusLabel,". ",b.summary," ",b.note]}),tt?a("div",{className:"peer-actions",children:a("button",{type:"button",className:"settings-button",onClick:iM,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:J})]})]})]})})}function aM(e){const t=_.syncPeersSectionFeedback,n=_.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?a(te,{children:[a(gr,{feedback:t}),e.peers.map(i=>{const o=String(i.peer_device_id||i.name||"unknown-peer");return a(oM,{peer:i,...e},o)})]}):a(te,{children:[a(gr,{feedback:t}),a($b,{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 sM(e,t){Qe(e,a(aM,{...t}))}var un=async()=>{},Cs="";function iu(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function cM(e){un=e}function lM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;Ln("syncActorsSkeleton"),iu(!1);const n=vb({actors:_.lastSyncActors,peers:_.lastSyncPeers,duplicatePeople:_.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.`)),q$(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await Tw(i,o),await un()},onMerge:async(i,o)=>{try{await zu(i,o),ne("People combined. Assigned devices moved to the selected person."),await un()}catch(s){throw ne(Ze(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await Nw(i),ne("Person removed. Assigned devices have been unassigned."),await un()}catch(o){throw ne(Ze(o,"Failed to remove person."),"warning"),o}}})}function dM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");iu(!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&&fr(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function uM(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;U$(e,{operations:_.lastShareOperations,onAdvance:n=>fw(n),onLoadOperation:n=>mw(n),onReload:un});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=_.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":_.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function ou(){const e=document.getElementById("syncPeers");if(!e)return;Ln("syncPeersSkeleton");const t=_.lastSyncPeers,n=Array.isArray(t)?t:[];C$(_.syncPeersSectionFeedback,n)&&(_.syncPeersSectionFeedback=null),sM(e,{peers:n,onRename:async(r,i)=>{try{return await Bu(r,i),await un(),{message:"Device name saved.",tone:"success"}}catch(o){return{message:Ze(o,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const o=String(r?.peer_device_id||""),s=lb(await Hs({address:i,peerDeviceId:o||void 0}));let c;s.ok?o&&zd(o)?c={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${ru()?"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 un()}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:Ze(o,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await Fu(r);const o={message:`Removed peer ${i}.`,tone:"success"};return _.syncPeerFeedbackById.delete(r),_.syncPeersSectionFeedback={...o,relatedPeerDeviceId:r},await un(),o}catch(o){return{message:Ze(o,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}},onAssignActor:async(r,i)=>{try{return await tw(r,i),await un(),{message:i?"Device assignment updated.":"Device assignment cleared.",tone:"success"}}catch(o){return{message:Ze(o,"Failed to update device assignment. The current assignment is unchanged."),tone:"warning"}}}})}function pM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");iu(!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&&fr(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&&fr(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 jb(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");!e||!t||!n||Y$({devices:Array.isArray(_.lastSyncLegacyDevices)?_.lastSyncLegacyDevices:[],meta:n,mount:t,onValueChange:r=>{r!==Cs&&(Cs=r,jb())},panel:e,value:Cs})}function mM(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{Dr(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){ri(n,"Enter a name for the person.");return}go(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await Cw(i),ne("Person created."),n.value="",await e()}catch(o){ne(Ze(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(Cs||"").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 kw(i),ne("Old device history attached to you."),await e()}catch(s){ne(Ze(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=o,r.disabled=!1})}function fM(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function au(e=fM()){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 Fb=!1;function hM(){Fb||(Fb=!0,window.addEventListener("hashchange",()=>{au()}))}var zt={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function gM(e){zt.loadSyncData=e}var vM=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function yM(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=_.lastCoordinatorAdminStatus?.readiness,r=String(_.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 su(){const e=document.getElementById("syncAdminDisclosureMount");e&&NL(e,{open:Sb,onOpenChange:t=>{p$(t),su(),Ns(),cu()}})}function bM(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function cu(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(_.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(_.lastTeamInvite?.warnings)?_.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function Ts(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=_.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 Ns(){const e=document.getElementById("syncInvitePolicyMount");e&&Qe(e,y(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,Ns())},options:vM,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:zt.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function _M(e,t){su(),Ns();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"),g=document.getElementById("syncRecipientDeviceName");let h="",v=0;r?.addEventListener("click",()=>{ta()||ne("Project sharing is unavailable. Refresh Projects and try again.","warning")});const b=async(w,S)=>{if(!u||!f||!g)return"other";const T=await ju(w);if(S!==v||d?.value.trim()!==w)return"stale";if(T.kind!=="project_share_invite")return"other";const N=(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 ${N||"selected projects"}.`),f.value=T.recipient_name??"",g.value=T.device_name??"",u.hidden=!1,h=w,l&&(l.textContent="Accept and start syncing"),m?.focus(),"project"};d?.addEventListener("input",()=>{v+=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?go(o):T=ri(o,"Team name is required."),!S||S<1?T=ri(s,"Must be at least 1 hour."):go(s),!!T){i.disabled=!0,i.textContent="Creating…";try{const N=await $u({group_id:w,policy:zt.invitePolicy,ttl_hours:S||24});_.lastTeamInvite=N,cu(),c.value=String(N.encoded||""),c.hidden=!1,c.focus(),c.select();const P=Array.isArray(N.warnings)?N.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(N){ne(Ze(N,"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=>{Dr(w,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d)return;const w=d.value.trim();if(!w){ri(d,"Paste a team invite or pairing payload.");return}if(go(d),h!==w){const T=v;try{const N=await b(w,T);if(N==="project"||N==="stale")return}catch{}if(T!==v||d.value.trim()!==w)return;h=w,l.textContent="Accept invite";return}const S=u&&!u.hidden?{recipient_name:f?.value.trim()??"",device_name:g?.value.trim()??""}:void 0;if(S){const T=N=>!N||[...N].length>120||[...N].some(P=>/[\p{Cc}\p{Cf}]/u.test(P));if(T(S.recipient_name)){f&&ri(f,"Enter a valid name using 120 characters or fewer.");return}if(T(S.device_name)){g&&ri(g,"Enter a valid device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const T=await Bs(w,S);_.lastTeamJoin=T;const N=T,P=typeof N.type=="string"?N.type:"team_join";let A;if(P==="pair"){const M=String(T.peer_device_id??"").trim();A={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=N.restart_required===!0||N.setup_state==="pending_inviter"||T.status==="pending_setup",U=typeof N.detail=="string"?N.detail.trim():"";A=M?{message:U||(N.restart_required===!0?"Project invitation accepted. Restart codemem to finish setup.":N.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 A={message:T.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"};_.syncJoinFlowFeedback=A,Ts(),d.value="",h="",u&&(u.hidden=!0);try{await t()}catch(M){A={message:Ze(M,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},_.syncJoinFlowFeedback=A,Ts()}}catch(T){_.syncJoinFlowFeedback={message:Ze(T,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},Ts(),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=lb(await Hs());ne(w.message,w.warning?"warning":void 0)}catch(w){ne(Ze(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 lu({element:e,hidden:t=!1,restoreParent:n=null}){const r=B(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 wM({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(lu,{element:e,hidden:!t,restoreParent:n}):null]})}function SM(){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=>Ai("codemem sync pair --payload-only",e.currentTarget),children:"Copy pairing command"})]})}function CM({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(lu,{element:e,hidden:!t,restoreParent:n}):null]})}function TM({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(lu,{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(CM,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:o,onToggle:c}),a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:a(wM,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?a(SM,{}):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 xs({children:e}){return a("div",{className:"section-meta sync-section-note",children:e})}function NM({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(gr,{feedback:o})]})}function xM({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(gr,{feedback:s})]})}function PM(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(xs,{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(NM,{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 EM({children:e}){return e?a(te,{children:[a(ks,{label:"Add devices & teammates"}),a(xs,{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&&!_.syncDiscoveredFeedback?null:en(a(te,{children:[a(ks,{count:t.length||void 0,label:"Devices waiting for review"}),a(xs,{children:"Review team devices here when they still need trust, re-pairing, or approval on this machine."}),a(gr,{feedback:_.syncDiscoveredFeedback}),t.map(o=>a(xM,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},o.deviceId))]}),e)}function IM({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!_.syncJoinRequestsFeedback?null:en(a(te,{children:[a(ks,{count:t.length||void 0,label:"Join requests to review"}),a(xs,{children:"Approve or deny requests here before those devices become part of the team."}),a(gr,{feedback:_.syncJoinRequestsFeedback}),t.map(i=>a(kM,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function Bb(e){return a(te,{children:[a(PM,{...e}),a(EM,{children:e.children}),a(IM,{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 Ub(e){e&&(e.textContent="")}function Ps(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 RM(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function vo(){return RM()?"auto":"smooth"}var du="syncTeamActionsMount";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=du,e.appendChild(n),Qe(n,y(Bb,{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 Gb(e,t){const n=document.getElementById(du);n&&(ei(n),n.remove()),Ub(e),t.forEach(r=>{Ub(r)})}function Es(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;su(),Ns(),cu(),Ts(),yM();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");Ln("syncTeamSkeleton"),bM();const p=_.lastSyncCoordinator,m=_.lastSyncViewModel||{primaryStatus:bb({status:_.lastSyncStatus,coordinator:p,peers:_.lastSyncPeers,shareOperations:_.lastShareOperations,shareOperationsLoadError:_.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]},f=E=>{if(E.kind==="possible-duplicate-person"){const H=document.getElementById("syncActorsList");H instanceof HTMLElement&&(H.scrollIntoView({block:"center",behavior:vo()}),Ps(H));return}const $=String(E.deviceId||"").trim();if(!$)return;if(E.kind==="name-device"){const H=document.querySelector(`[data-device-name-input="${CSS.escape($)}"]`);if(H instanceof HTMLInputElement){H.scrollIntoView({block:"center",behavior:vo()}),H.focus(),H.select(),Ps(H);return}}const L=document.querySelector(`[data-peer-device-id="${CSS.escape($)}"]`);if(L instanceof HTMLElement){L.scrollIntoView({block:"center",behavior:vo()}),Ps(L);return}const J=document.querySelector(`[data-discovered-device-id="${CSS.escape($)}"]`);J instanceof HTMLElement&&(J.scrollIntoView({block:"center",behavior:vo()}),Ps(J))},g=async E=>{const $=Array.isArray(E.actorIds)?E.actorIds.map(R=>String(R||"").trim()).filter(Boolean):[],L=(Array.isArray(_.lastSyncActors)?_.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 xP({title:"Review possible duplicate people",summary:E.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"){_$($,"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),k=L.find(R=>String(R?.actor_id||"")===J.secondaryActorId);if(!H?.actor_id||!k?.actor_id){ne("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await zu(String(H.actor_id),String(k.actor_id)),w$($),ne(`Combined duplicate people into ${String(H.display_name||H.actor_id)}.`),await zt.loadSyncData()}catch(R){try{await zt.loadSyncData()}catch{}ne(Ze(R,"Failed to combine these people."),"warning")}},h=async E=>await Rl({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:E,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:$=>$.trim()?null:"Enter a device name to pair this device."}),v=!!p?.configured,b=l$(p);e.title=v?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?DM(w,e,m.primaryStatus):e.textContent=m.primaryStatus.meta,!v){Gb(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(_.lastSyncPeers)?_.lastSyncPeers:[],N=Array.isArray(m.attentionItems)?m.attentionItems:[],P=(Array.isArray(p.discovered_devices)?p.discovered_devices:[]).map(E=>{const $=String(E.device_id||"").trim(),L=ub({coordinatorName:String(E.display_name||"").trim(),deviceId:$})||"Discovered device",J=$&&L!==$?$:null,H=String(E.fingerprint||"").trim(),k=(Array.isArray(E.groups)?E.groups.map(Q=>String(Q||"").trim()).filter(Boolean):[]).length>1,R=T.find(Q=>String(Q?.peer_device_id||"")===$),j=cb({device:E,pairedLocally:!!R}),W=String(R?.fingerprint||"").trim(),ge=!!R&&!!H&&!!W&&W!==H,le=!b&&AL({device:E,hasAmbiguousCoordinatorGroup:k,pairedLocally:!!R}),ce=Array.isArray(E.addresses)?E.addresses:[],be=Number(E.address_count??0),Y=Number.isFinite(be)&&be>0?be:0,fe=[ce.length?ce.map(Q=>Ri()?xb(String(Q||"")):String(Q||"")).filter(Boolean).join(" · "):Y>0?`${Y} ${E.stale?"last-known":"fresh"} ${Y===1?"address":"addresses"} hidden`:"No fresh addresses"];!ce.length&&J&&fe.push(`device id: ${$}`);let X=null,_e=le?"accept":"none",he=null;return ge?_e="conflict":b&&(!R||j.state==="needs-your-approval")?(X=b.message,_e="setup-blocked"):k?(X="This device appears in multiple coordinator groups. Review team setup first or ask an admin to clean up the duplicate enrollment before approving it here.",_e="ambiguous"):R&&zd($)?(X="Review this device's Space access and advanced rules in Teams before you sync it.",_e="scope-pending"):R?.last_error?(fe.push(`error: ${String(R.last_error)}`),le||(_e="paired")):R?.status?.peer_state?(fe.push(`status: ${String(R.status.peer_state)}`),le||(_e="paired")):!R&&E.stale?(X="Wait for a fresh coordinator presence update, then review this device again here.",_e="stale"):R&&!le&&(_e="paired"),_e==="paired"&&(he=j.state==="waiting-for-other-device"?j.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:X,actionLabel:j.actionLabel||(R?"Review device":"Pair with this device"),approvalBadgeLabel:j.badgeLabel,availabilityLabel:E.stale?"Offline":"Available",connectionLabel:ge?wb.conflicts:R?wb.pairedLocally:"Not connected on this device",deviceId:$,displayName:L,displayTitle:J,fingerprint:H,mode:_e,note:fe.join(" · "),pairedMessage:he}}),A=[],M=P.filter(E=>E.mode!=="paired"&&E.mode!=="none"&&E.mode!=="scope-pending"),U=P.filter(E=>E.mode==="accept"||E.mode==="scope-pending").length,x=N.length+A.length+U;l&&(l.hidden=M.length===0&&!_.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=A.length===0&&!_.syncJoinRequestsFeedback),Gb(n,[c,u]);const G=document.createElement("div");G.id=du,n.appendChild(G),Qe(G,y(Bb,{actionItems:N,actionableCount:x,children:y(TM,{invitePanel:r,invitePanelOpen:Kd,inviteRestoreParent:i,joinPanel:o,joinPanelOpen:qd,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(m$(!Kd),Es())},onToggleJoinPanel:()=>{o&&(f$(!qd),Es())},pairedPeerCount:Number(p.paired_peer_count||0),presenceStatus:S}),discoveredListMount:u,discoveredRows:M,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async E=>{if(E.kind==="possible-duplicate-person"){await g(E);return}f(E)},onDenyJoinRequest:async()=>null,onInspectConflict:E=>{const $=document.querySelector(`[data-peer-device-id="${CSS.escape(E.deviceId)}"]`);if($ instanceof HTMLElement){$.scrollIntoView({block:"center",behavior:vo()}),ne(`Opened the conflicting local device record for ${E.displayName}.`,"warning");return}ne("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async E=>{if(!await Kt({title:`Remove ${E.displayName}?`,description:"This deletes the broken local device record. You can review this device again after the screen refreshes.",confirmLabel:"Remove device record",cancelLabel:"Keep device record",tone:"danger"}))return null;try{await Fu(E.deviceId);const $={message:`Removed the broken local device record for ${E.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return _.syncDiscoveredFeedback=$,await zt.loadSyncData(),$}catch($){return{message:Ze($,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async E=>{try{const $=await h(E.displayName);if(!$)return null;const L=await nw(E.deviceId,E.fingerprint),J=String(L?.name||E.displayName||"").trim()||E.displayName;_.pendingAcceptedSyncPeers=[...Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(k=>String(k?.peer_device_id||"").trim()!==E.deviceId):[],{peer_device_id:E.deviceId,name:J,fingerprint:E.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],g$(E.deviceId);let H={message:E.approvalBadgeLabel==="Needs your approval"?`Approved ${E.displayName} on this device. Two-way trust should be ready once both devices refresh.`:`Step 1 complete on this device for ${E.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};try{$.trim()!==J.trim()&&(await Bu(E.deviceId,$.trim()),_.pendingAcceptedSyncPeers=_.pendingAcceptedSyncPeers.map(k=>String(k?.peer_device_id||"").trim()===E.deviceId?{...k,name:$.trim()}:k),H={message:`Connected ${$.trim()} and saved its name.`,tone:"success"})}catch(k){H={message:Ze(k,"Device connected, but naming did not finish."),tone:"warning"}}_.syncDiscoveredFeedback=H;try{await zt.loadSyncData()}catch(k){H={message:Ze(k,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},_.syncDiscoveredFeedback=H}return H}catch($){return{message:Ze($,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:A,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 ii(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function Hb(e){return ii(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 Kb(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 qM({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],o=Object.fromEntries(r.map(k=>[k.workspaceIdentity,k.suggestedScopeId??""])),[s,c]=I({}),[l,d]=I({}),[u,p]=I(o),[m,f]=I({}),[g,h]=I("all"),[v,b]=I(""),[w,S]=I(null),T=r.length,N=e.totalGroupCount??T,P=r.filter(ii).length,A=r.filter(k=>k.suggestedScopeId&&!ii(k)&&Tt(k)).length,M=r.filter(k=>m[k.workspaceIdentity]&&Tt(k)).length,U=r.filter(k=>m[k.workspaceIdentity]&&Tt(k)&&!!u[k.workspaceIdentity]).length,x=r.filter(k=>{const R=ii(k);return g==="suggested"&&(!k.suggestedScopeId||R)||g==="cleanup"&&!R||g==="no-suggestion"&&(k.suggestedScopeId||R)||g==="selected"&&!m[k.workspaceIdentity]?!1:!v.trim()||HM(k,i).includes(v.trim().toLowerCase())});async function G(k){const R=u[k.workspaceIdentity]||k.suggestedScopeId||"";if(!(!R||!t||w)){S(k.workspaceIdentity),d(j=>{const W={...j};return delete W[k.workspaceIdentity],W});try{const j=await t(k,R,!!s[k.workspaceIdentity],s[k.workspaceIdentity]?.confirmation_token);c(j?W=>({...W,[k.workspaceIdentity]:j}):W=>{const ge={...W};return delete ge[k.workspaceIdentity],ge})}catch(j){d(W=>({...W,[k.workspaceIdentity]:Kb(j,R,i)}))}finally{S(null)}}}function E(k,R){p(j=>({...j,[k.workspaceIdentity]:R})),c(j=>{const W={...j};return delete W[k.workspaceIdentity],W}),d(j=>{const W={...j};return delete W[k.workspaceIdentity],W})}function $(k,R){f(j=>({...j,[k.workspaceIdentity]:R}))}function L(k){f(R=>({...R,...Object.fromEntries(x.filter(Tt).map(j=>[j.workspaceIdentity,k]))}))}function J(){f(k=>({...k,...Object.fromEntries(r.filter(R=>R.suggestedScopeId&&!ii(R)&&Tt(R)).map(R=>[R.workspaceIdentity,!0]))}))}async function H(){if(!t||w||U===0)return;const k=r.filter(R=>m[R.workspaceIdentity]&&Tt(R)&&!!u[R.workspaceIdentity]);if(!k.every(R=>s[R.workspaceIdentity])){S("bulk");try{for(const R of k){if(s[R.workspaceIdentity])continue;const j=u[R.workspaceIdentity]||R.suggestedScopeId||"";if(j)try{const W=await t(R,j,!1);d(ge=>{const le={...ge};return delete le[R.workspaceIdentity],le}),W&&c(ge=>({...ge,[R.workspaceIdentity]:W}))}catch(W){d(ge=>({...ge,[R.workspaceIdentity]:Kb(W,j,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:[N.toLocaleString()," older"," ",N===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",T<N?` 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 ${A.toLocaleString()}`],["cleanup",`Needs cleanup ${P.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${U.toLocaleString()}`]].map(([k,R])=>a("button",{className:g===k?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>h(k),type:"button",children:R},k))}),a("div",{className:"legacy-review-bulk-row",children:[a("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:k=>b(k.currentTarget.value),placeholder:"Search project, signal, or destination…",value:v}),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(k=>m[k.workspaceIdentity]&&Tt(k)&&!!u[k.workspaceIdentity]).every(k=>s[k.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(k=>m[k.workspaceIdentity]&&Tt(k)&&!!u[k.workspaceIdentity]).every(k=>s[k.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:x.map(k=>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 ${Hb(k)}`,checked:!!m[k.workspaceIdentity],className:"cm-checkbox",disabled:!Tt(k),onChange:R=>$(k,R.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:Hb(k)}),a("div",{className:"legacy-review-group-meta",children:[$M(k.identitySource),MM(k,i)]}),Tt(k)?k.peerOwnedMemoryCount?a("div",{className:"legacy-review-cleanup-note",children:[(k.reassignableMemoryCount??k.memoryCount).toLocaleString()," ","local memor",(k.reassignableMemoryCount??k.memoryCount)===1?"y":"ies"," ","can be reassigned; ",k.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",k.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."}),ii(k)?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:[k.memoryCount.toLocaleString()," memor",k.memoryCount===1?"y":"ies"]})]}),k.suggestionReason?a("div",{className:"legacy-review-reason",children:k.suggestionReason}):null,l[k.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:l[k.workspaceIdentity]}):null,s[k.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:[s[k.workspaceIdentity].warning," This will reassign"," ",s[k.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[k.workspaceIdentity].memory_count.toLocaleString()," memories",s[k.workspaceIdentity].skipped_memory_count?`; ${s[k.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,a(GM,{group:k}),i.length>0&&t&&Tt(k)?a("label",{className:"legacy-review-target",children:[a("span",{children:"Destination Space"}),a("select",{className:"peer-scope-input",disabled:w!=null,onChange:R=>E(k,R.currentTarget.value),value:u[k.workspaceIdentity]||"",children:[a("option",{value:"",children:"Choose Space…"}),i.map(R=>a("option",{value:R.scopeId,children:[R.label," · ",FM(R.authorityType),R.scopeId===k.suggestedScopeId?" · suggested":""]},R.scopeId))]})]}):null,i.length>0&&t&&Tt(k)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:w!=null||!u[k.workspaceIdentity],onClick:()=>{G(k)},children:w===k.workspaceIdentity?s[k.workspaceIdentity]?"Reassigning…":"Previewing…":s[k.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},k.workspaceIdentity))}):null]})}function WM({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(te,{children:[t?a(qM,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(KM,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function VM(){Pf("mine"),_.feedQuery="",window.location.hash="feed"}function zM(){window.location.hash="projects"}async function JM(e,t,n,r){try{const i=await _w({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return _.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}.`),qb(),null}catch(i){if(i instanceof Gu)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw ne(o,"warning"),new Error(o)}}function qb(){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(_.lastSyncSharingReview)?_.lastSyncSharingReview:[],o=_.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){ei(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=_.currentProject?`current project (${_.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,y(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:VM}))}var As="",yo=null,uu=0,YM=15e3;function Wb(e){return`project:${e||""}|includeJoinRequests:false`}function XM(e){const t=Wb(e);return!yo||yo.key!==t||Date.now()>=yo.expiresAtMs?null:yo.payload}function QM(e,t){yo={key:Wb(e),expiresAtMs:Date.now()+YM,payload:t}}function ZM(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 oi(){const e=++uu;try{const t=_.currentProject||"",n=!1,r=_.activeTab==="health";let i=!1;const o=!Ri();let s;r?(s=XM(t),s||(s=await Fs(o,t,{includeJoinRequests:!1}),i=!0)):(s=await Fs(o,t,{includeJoinRequests:n}),i=!0);let c=null,l=null,d=_.lastShareOperations,u=!1,p=!1,m=!1;const f=b$();try{c=await Z_()}catch{u=!0}try{l=await No()}catch{p=!0}try{const S=await Vu();d=Array.isArray(S.items)?S.items:[]}catch{m=!0}if(e!==uu)return;i&&QM(t,ZM(s));const g=JSON.stringify([s,c,l,d,m,f]);if(g===As)return;As=g;const h=s.status&&typeof s.status=="object"?s.status:null;h&&(_.lastSyncStatus=h),Array.isArray(c?.items)?_.lastSyncActors=c.items:_.lastSyncActors=[];const v=Array.isArray(s.peers)?s.peers:[],b=new Set(v.map(S=>String(S?.peer_device_id||"").trim()).filter(Boolean)),w=Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(S=>{const T=String(S?.peer_device_id||"").trim();return T&&!b.has(T)}):[];_.pendingAcceptedSyncPeers=w,_.lastSyncPeers=[...v,...w],_.lastShareOperations=d,_.shareOperationsLoadError=m,_.lastSyncSharingReview=s.sharing_review||[],_.lastSyncLegacySharedReview=s.legacy_shared_review&&typeof s.legacy_shared_review=="object"?s.legacy_shared_review:null,_.lastSyncCoordinator=s.coordinator||null,_.lastCoordinatorAdminStatus=l&&typeof l=="object"?l:null,_.lastSyncJoinRequests=Array.isArray(s.join_requests)?s.join_requests:[],_.lastSyncAttempts=s.attempts||[],_.lastSyncLegacyDevices=s.legacy_devices||[],_.lastSyncDuplicatePersonDecisions=f,_.lastSyncViewModel=u$({actors:_.lastSyncActors,peers:_.lastSyncPeers,coordinator:_.lastSyncCoordinator,status:h,shareOperations:_.lastShareOperations,shareOperationsLoadError:m,reconciliation:s.recipient_policy_reconciliation,duplicatePersonDecisions:_.lastSyncDuplicatePersonDecisions}),Rb(),Es(),lM(),uM(),qb(),ou(),jb(),Ib(),Py(),u&&dM(),p&&(_.lastCoordinatorAdminStatus=null,Es())}catch{if(e!==uu)return;As="",Ln("syncTeamSkeleton"),Ln("syncActorsSkeleton"),Ln("syncPeersSkeleton"),Ln("syncDiagSkeleton"),eO(),pM(),x$()}}function tO(){As="",_.lastSyncPeers?.length&&ou()}async function nO(){try{_.pairingPayloadRaw=await ew()||null,Zd()}catch{_.pairingPayloadRaw=null,Zd()}}function rO(e){cL(),Ba(),gM(oi),cM(oi),I$(ou),_M(e,oi),mM(oi),R$(e),au(),hM()}function iO(e,t){const n=Ae("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 z_();if(!e?.version)return;iO(e.version,"b4e17ed")}catch{}}var pu=null,Vb=1500,zb="codemem-legacy-upgrade-notice-dismissed",$n=null,Jt=!1,mu=!1,bo=null;function Jb(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function Yb(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=Jb(n.total_group_count,r.length),o=Jb(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function Xb(){try{return localStorage.getItem(zb)==="1"}catch{return!1}}function Is(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(zb,"1")}catch{}}function Qb(){const e=Ae("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=Ae("legacyUpgradeReviewGroups");(t&&e.includes(t)?t:e[0])?.focus()}function Zb(e){const t=Ae("legacyUpgradeModal");if(!t||t.hidden)return;if(e.key==="Escape"){e.preventDefault(),Is(),_o(!1);return}if(e.key==="Enter"){const o=Ae("legacyUpgradeReviewGroups");Dr(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 e_(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 _o(e,t){const n=Ae("legacyUpgradeModalBackdrop"),r=Ae("legacyUpgradeModal"),i=Ae("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){bo=document.activeElement,document.addEventListener("keydown",Zb),aO(),e_(!0);return}e_(!1),document.removeEventListener("keydown",Zb),bo&&document.contains(bo)&&bo.focus(),bo=null}}function t_(e){!e||mu||Xb()||(mu=!0,_o(!0,e))}async function sO(){if(!(mu||Xb()))try{t_(Yb(await Fs(!1,"",{includeJoinRequests:!1})))}catch{}}function vr(e,t){const n=Ae("viewerReconnectOverlay"),r=Ae("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.")}async function fu(){try{return await V_(),!0}catch{return!1}}function cO(){return document.visibilityState!=="hidden"&&!Qy()}function n_(){if(Jt)return;Jt=!0,hu(),yr("error","(reconnecting)"),vr(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await fu()){if($n&&(clearTimeout($n),$n=null),Jt=!1,vr(!0,"Viewer responded. Restoring your session…"),cO()){yr("refreshing"),wo();try{await Ds()}catch{}}else yr("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");Jt||vr(!1);return}vr(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),$n=setTimeout(e,Vb)};$n=setTimeout(e,Vb)}function yr(e,t){_.refreshState=e;const n=Ae("refreshStatus");if(!n)return;const r=o=>{const s=Ae("refreshAnnouncer");!s||pu===e||(s.textContent=o,pu=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}`,pu=null}function hu(){_.refreshTimer&&(clearInterval(_.refreshTimer),_.refreshTimer=null)}function wo(){_.refreshTimer||(_.refreshTimer=setInterval(()=>Mn(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(hu(),yr("paused","(tab hidden)")):!Qy()&&!Jt&&(wo(),Mn())});function lO(){const e=_.advancedSection==="sync",t=Ae("advancedSyncContent"),n=Ae("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=Ae("advancedSyncButton"),i=Ae("advancedTeamsButton");r?.setAttribute("aria-pressed",String(e)),i?.setAttribute("aria-pressed",String(!e)),queueMicrotask(()=>{const o=window.location.hash.replace(/^#/,"");au(o==="sync/diagnostics"||o==="advanced/sync/diagnostics"?"diagnostics":"main")})}function r_(e){const t=new Set(iN(_.lastCoordinatorAdminStatus));Jn.forEach(n=>{const r=Ae(`tab-${n}`);r&&(r.hidden=n!==e||!t.has(n))}),Jn.forEach(n=>{const r=Ae(`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 Rs(e,t={}){const n=Ii(e,_.lastCoordinatorAdminStatus);n==="advanced"&&Kc(t.advancedSection??Hc()??_.advancedSection),xf(n,t.canonicalHash?{canonicalHash:!0}:{}),r_(n),Mn()}function dO(){Jn.forEach(e=>{Ae(`tabBtn-${e}`)?.addEventListener("click",()=>Rs(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Ae("advancedSyncButton")?.addEventListener("click",()=>Kc("sync",!0)),Ae("advancedTeamsButton")?.addEventListener("click",()=>Kc("teams",!0)),window.addEventListener("hashchange",()=>{const e=Gc();if(e){const t=Hc();Rs(e,t?{advancedSection:t}:{})}}),Rs(_.activeTab)}async function uO(){try{const e=await ko();_.knownProjects=e,tO();const t=Fc("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=cT(),i_={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},o_=!1,ai=null;async function mO(){const e=[];let t=0;for(;;){const n=await Po({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return ea(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 _.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"offline":"available");for(const r of _.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),o=ho(r);n(i,o==="connected"||o==="available"?"available":o==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function a_(e){Rs(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}async function hO(){const e=document.getElementById("devicesMount");if(!e)return!0;o_||Ga(e,i_,{version:1,items:[]},[],[],{loading:!0});try{const[t,n,r]=await Promise.all([mO(),Gs(),rw(),oi()]),i=fO();return Ga(e,n,r,t,i,{onNavigate:a_}),ai={projects:t,intent:n,reconciliation:r,availability:i},o_=!0,!0}catch{return ai?Ga(e,ai.intent,ai.reconciliation,ai.projects,ai.availability,{onNavigate:a_,refreshError:!0}):Ga(e,i_,{version:1,items:[]},[],[],{loadError:!0}),!1}}Fc("projectFilter")?.addEventListener("change",()=>{_.currentProject=Fc("projectFilter")?.value||"",co(!0),Mn()});var gu=null;async function Mn(){Jt||(gu&&clearTimeout(gu),gu=setTimeout(()=>Ds(),80))}async function Ds(){if(!Jt){if(_.refreshInFlight){_.refreshQueued=!0;return}_.refreshInFlight=!0;try{yr("refreshing");const e=_.activeTab,t=[y0(),ED()];let n=!0;e==="feed"&&t.push(No().then(i=>{_.lastCoordinatorAdminStatus=i&&typeof i=="object"?i:null}).catch(()=>{_.lastCoordinatorAdminStatus=null})),e==="feed"&&t.push(Ty()),e==="projects"&&t.push(zy()),e==="sharing"&&t.push(pO()),e==="devices"&&t.push(hO().then(i=>{n=i})),(e==="advanced"&&_.advancedSection==="sync"||e==="health")&&t.push(oi()),e==="advanced"&&_.advancedSection==="teams"&&t.push(Ml()),_.syncPairingOpen&&t.push(nO()),await Promise.all(t),t_(Yb(_.lastSyncLegacySharedReview));const r=Ii(_.activeTab,_.lastCoordinatorAdminStatus);r!==_.activeTab&&xf(r),r_(_.activeTab),yr(n?"idle":"error")}catch{await fu()?yr("error"):n_()}finally{_.refreshInFlight=!1,_.refreshQueued&&!Jt&&(_.refreshQueued=!1,Ds())}}}mN();var s_=document.getElementById("toastRoot");s_&&zT(s_),fN(Bc("themeToggle")),If(Wc()),dO(),l0(),Z0(()=>Mn()),rO(()=>Mn()),nE(),aL(hu,wo,()=>Mn()),uO(),Ae("viewerReconnectRetry")?.addEventListener("click",async()=>{if(vr(!0,"Checking whether the viewer server is back…"),!await fu()){n_();return}$n&&(clearTimeout($n),$n=null),Jt=!1,vr(!0,"Viewer responded. Restoring your session…"),wo();try{await Ds()}catch{}Jt||vr(!1)}),Ae("legacyUpgradeReviewGroups")?.addEventListener("click",()=>{Is(),_o(!1),window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)}),Ae("legacyUpgradeReviewProjects")?.addEventListener("click",()=>{Is(),_o(!1),window.location.hash="projects"}),Ae("legacyUpgradeNotNow")?.addEventListener("click",()=>{Is(),_o(!1)}),oO(),sO(),Mn(),wo()})();
|
|
114
|
+
Global: ${Number(c.tokens_saved||0).toLocaleString()} saved`:"",v=[{label:d?"Savings (project)":"Savings",value:Ui(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:Ui(u.tokens_read||0),tooltip:`Tokens injected into context (pack size). Exact: ${Number(u.tokens_read||0).toLocaleString()} injected${g}`,icon:"book-open"},{label:d?"Reduction (project)":"Reduction",value:Fl(u.tokens_saved,u.tokens_read),tooltip:`Percent reduction from reuse. Factor: ${pE(u.tokens_saved,u.tokens_read)}.`+g+h,icon:"percent"},{label:d?"Work investment (project)":"Work investment",value:Ui(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:Hg(o.vector_coverage),tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:Hg(o.tags_coverage),tooltip:"Share of active memories with tags",icon:"tag"}];if(m>0?v.push({label:"Raw events pending",value:m,tooltip:"Pending raw events waiting to be flushed",icon:"activity"}):p>0&&v.push({label:"Raw sessions",value:p,tooltip:"Sessions with pending raw events",icon:"inbox"}),Ny(e,v),t){const b=s?` · project: ${s}`:"";ky(t,`DB: ${gE(o.path||"unknown")} · ${vE(o.size_bytes||0)}${b}`)}Nd()}async function y0(){const e=_.lastStatsPayload?.identity?.actor_id||null,[t,n,r,i]=await Promise.all([J_(),Y_(_.currentProject),X_(_.currentProject),Q_(_.currentProject)]);_.lastStatsPayload=t||{},_.lastUsagePayload=n||{},_.lastRawEventsPayload=i||{};const o=_.lastStatsPayload?.identity?.actor_id||null;v0(),g0(),Py(),_.activeTab==="feed"&&e!==o&&co(!0)}var dr=new Set,kd=new Set,Xr="";function ln(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function b0(e){return e.options.find(t=>t.decision===e.recommendedDecision)?.label??e.recommendedDecision.replaceAll("_"," ")}function Ey(e,t){const n=document.createElement("div");n.className="recipient-policy-preview-list";const r=document.createElement("strong");r.textContent=e;const i=document.createElement("ul");for(const o of t){const s=document.createElement("li");s.textContent=o,i.appendChild(s)}return n.append(r,i),n}function _0(e){const t=document.createElement("div");t.className="recipient-policy-preview settings-note";const n=document.createElement("strong");return n.textContent=`Exact preview: ${e.preview.affectedProjectCount.toLocaleString()} project${e.preview.affectedProjectCount===1?"":"s"} · ${e.preview.affectedMemoryCount.toLocaleString()} memor${e.preview.affectedMemoryCount===1?"y":"ies"} · ${e.preview.affectedDeviceCount.toLocaleString()} device${e.preview.affectedDeviceCount===1?"":"s"}`,t.appendChild(n),t.appendChild(Ey("Projects",e.preview.projects.map(r=>r.displayName))),t.appendChild(Ey("Devices",e.preview.effectiveDevices.map(r=>`${r.displayName} (${r.assignment})`))),t}function w0(e,t,n,r){const i=document.createElement("article");i.className="project-inventory-row recipient-policy-review-item";const o=document.createElement("h3");o.className="project-inventory-title",o.textContent=e.finding;const s=ln(e.reason,"project-inventory-meta"),c=ln(`Recommended: ${b0(e)}`,"settings-note"),l=document.createElement("div");l.className="project-inventory-actions";const d=`recipient-policy-decision-${t}`,u=document.createElement("label");u.htmlFor=d,u.textContent="Decision";const p=document.createElement("select");p.id=d,p.className="project-filter recipient-policy-review-select";for(const b of e.options){const w=document.createElement("option");w.value=b.decision,w.textContent=b.label,p.appendChild(w)}e.options.some(b=>b.decision===e.recommendedDecision)&&(p.value=e.recommendedDecision);const m=document.createElement("button");m.className="settings-button",m.type="button",m.textContent="Apply decision";const f=ln("","settings-note recipient-policy-deferred"),g=document.createElement("div");g.className="recipient-policy-preview-mount",g.setAttribute("aria-live","polite");const h=()=>e.options.find(b=>b.decision===p.value)??e.options[0],v=()=>{const b=h();b&&(g.replaceChildren(_0(b)),f.textContent=b.preview.requiresDecisionInput?"Recipient or device details are required for this decision. Complete it in a later review flow; no incomplete decision will be submitted.":"",f.hidden=!b.preview.requiresDecisionInput,m.disabled=b.preview.requiresDecisionInput||dr.has(e.reviewItemId))};return p.addEventListener("change",v),v(),kd.has(e.reviewItemId)&&i.appendChild(ln("Source state changed while this decision was being reviewed. Review the refreshed choices before trying again.","settings-note project-attention-note")),m.addEventListener("click",async()=>{const b=h();if(!(!b||b.preview.requiresDecisionInput||dr.has(e.reviewItemId))){dr.add(e.reviewItemId),p.disabled=!0,m.disabled=!0,m.textContent="Applying…",n.textContent=`Applying “${b.label}”…`;try{await lw({reviewItemId:e.reviewItemId,sourceFingerprint:e.sourceFingerprint,decision:b.decision}),kd.delete(e.reviewItemId),Xr="Decision applied. Review items refreshed.",dr.delete(e.reviewItemId),await r()}catch(w){if(w instanceof Hu){kd.add(e.reviewItemId),Xr="Source state changed. The review item is still open and its choices were refreshed.",n.textContent=Xr,dr.delete(e.reviewItemId),await r();return}Xr=w instanceof Error?w.message:"Unable to apply decision.",n.textContent=Xr,dr.delete(e.reviewItemId),p.disabled=!1,m.textContent="Apply decision",v()}finally{dr.delete(e.reviewItemId)}}}),l.append(u,p,m),i.prepend(o,s,c),i.append(l,f,g),i}function S0(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,ln(e.reason,"project-inventory-meta"),ln(`Owner: ${e.ownerLabel}`,"settings-note"),ln(`Repair: ${e.repairAction}`,"settings-note")),t}function C0(e,t,n){const r=t.reviewItems.filter(l=>l.options.length>0);if(r.length===0&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0;return}e.hidden=!1;const i=document.createElement("section");i.className="card recipient-policy-review",i.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const o=document.createElement("h2");o.id="recipientPolicyReviewTitle",o.textContent="Recipient migration review";const s=ln("Review how older project sharing should be represented. These decisions do not expose internal scope or transport details.","section-meta"),c=document.createElement("div");if(c.className="section-meta recipient-policy-review-status",c.setAttribute("role","status"),c.setAttribute("aria-live","polite"),c.textContent=Xr,i.append(o,s,c),r.length>0){const l=document.createElement("h3");l.textContent="Needs review";const d=document.createElement("div");d.className="project-inventory-list recipient-policy-review-list",r.forEach((u,p)=>{d.appendChild(w0(u,p,c,n))}),i.append(l,d)}if(t.blockedItems.length>0){const l=document.createElement("h3");l.className="recipient-policy-blocked-heading",l.textContent="Blocked";const d=document.createElement("div");d.className="project-inventory-list recipient-policy-review-list";for(const u of t.blockedItems)d.appendChild(S0(u));i.append(l,d)}e.replaceChildren(i)}function T0(e,t){e.hidden=!1;const n=document.createElement("section");n.className="card recipient-policy-review";const r=document.createElement("h2");r.textContent="Recipient migration review";const i=ln(t instanceof Error?t.message:"Unable to load recipient migration review.","settings-note project-attention-note");i.setAttribute("role","status"),n.append(r,i),e.replaceChildren(n)}var Ay=[["","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,lo=0,xd=250,Pd=[],Ed=new Set,Ad=new Set,ls=new Map,ds=new Map,ur=new Map,uo=new Map,us=!1,po=!1,Rn=!1,ps=0,Ct=new Set,Iy=new WeakMap,ms={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Qr=ms,Dn=!1;function Ke(e){return document.getElementById(e)}function N0(e){return Ay.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function k0(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 Zr(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Id(e){return e.identity_source!=="unmapped"&&!Zr(e)}function Rd(e){return Zr(e)?"Received from peers":fs(e.resolved_scope_id)}function x0(e){return Zr(e)?"source-owned project":k0(e.resolution_reason)}function P0(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 Ry(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Dy(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function pr(){const e=Ct.size,t=Ke("projectsShareSelected");t&&(t.textContent=e===0?"Share selected":`Share selected (${e})`,t.disabled=e===0||!Rn||!Dn,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=Iy.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=!Rn||!Dn}function E0(e){const t=e.every(n=>Ct.has(n));for(const n of e)t?Ct.delete(n):Ct.add(n);pr()}function Ly(e,t){const n=Dy(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),Iy.set(i,n),i.addEventListener("change",()=>E0(n));const o=document.createElement("span");return o.className="sr-only",o.textContent=t,r.append(i,o),r}function A0(e){if(!Dn)return[];const t=new Set(e),n=new Map(Qr.teams.filter(o=>o.status==="active").map(o=>[o.teamId,o.displayName])),r=new Map(Qr.identities.filter(o=>o.status==="active"||o.status==="pending").map(o=>[o.identityId,o.displayName])),i=new Map;for(const o of Qr.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 $y(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=A0(e),r=document.createElement("div");if(r.className="project-recipient-status",r.textContent=Dn?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 My(e,t){const n=document.createElement("button");return n.className="settings-button project-recipient-action project-selection-target",n.type="button",n.disabled=!Rn||!Dn,e.length===1?(n.textContent="Manage recipients",n.setAttribute("aria-label",`Manage recipients for ${t}`),n.dataset.projectFocusKey=`manage:${e[0]}`,n.addEventListener("click",()=>{Ti({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);pr(),Ti({mode:"project-add",projectIds:[...e].sort()})})),n}function I0(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function Dd(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function Ld(e){return e.project||e.display_project||"Unnamed Project"}function Oy(e){const t=String(e||"").trim();return t?_.lastCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function R0(){return new Set(_.lastCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function D0(e){return!po||e.authority_type!=="coordinator"||!e.group_id?!1:!R0().has(String(e.group_id).trim())}function jy(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function Fy(){us&&(us=!1,at?.())}async function L0(){try{const e=await No();_.lastCoordinatorAdminStatus=e&&typeof e=="object"?e:null}catch{_.lastCoordinatorAdminStatus=null,_.lastCoordinatorAdminGroups=[],po=!1;return}if(_.lastCoordinatorAdminStatus?.readiness!=="ready"||!_.lastCoordinatorAdminStatus.has_admin_secret){_.lastCoordinatorAdminGroups=[],po=!1;return}try{const e=await Du(!1);_.lastCoordinatorAdminGroups=Array.isArray(e?.items)?e.items:[],po=!0}catch{_.lastCoordinatorAdminGroups=[],po=!1}}function $0(e){return e.kind==="team_default"}function $d(e){const t=e.label||"Untitled Space";return $0(e)?`${t} (default)`:t}function M0(e,t){const n=$d(e);return t.some(r=>r.scope_id!==e.scope_id&&$d(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function O0(e){const t=Oy(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 j0(e){return e?Pd.find(t=>t.scope_id===e)??null:null}function fs(e){const t=j0(e);return e?t?`${$d(t)} · ${O0(t)}`:"Unknown Space":"—"}function Md(){return Pd.filter(e=>e.scope_id!=="legacy-shared-review"&&!D0(e))}function F0(e){return Md().some(t=>t.scope_id===e)}function By(...e){for(const t of e)if(t&&F0(t))return t;return e.find(t=>!!t)??""}function B0(e){const t=Oy(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function U0(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function G0(){const e=new Map;for(const t of Md()){const n=U0(t),r=B0(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function Uy(e){for(const t of G0()){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=M0(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function H0(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 Od(e,t,n=[]){try{await hw({...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}),ur.delete(e.workspace_identity),ls.delete(e.workspace_identity),ne("Project Space assignment updated. Device access grants are unchanged."),at?.()}catch(r){if(r instanceof xo){ur.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 K0(e,t){const n=e.filter(Id);if(n.length!==0)try{await gw({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.`),ds.delete(Dd(n[0])),at?.()}catch(r){ne(r instanceof xo?"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 q0(e){if(e.mapping_id!=null)try{await vw(e.mapping_id),ur.delete(e.workspace_identity),ls.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 Gy(e,t=!1){try{const n=uo.get(e.workspace_identity),r=await bw({...t&&n?{confirmation_token:n.confirmationToken}:{},confirmed:t,workspace_identity:e.workspace_identity});uo.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 Uu){uo.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 V0(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 Rl({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 yw({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 W0(e){const t=document.createElement("div");if(t.className="project-inventory-actions",Id(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=!Rn,Rn||(f.title="The complete project list is unavailable."),f.addEventListener("click",()=>ta([e.workspace_identity])),t.appendChild(f)}if(Zr(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=Md().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=`${fs(e.resolved_scope_id)} — not assignable`,f.disabled=!0,i.appendChild(f)}Uy(i),i.value=By(ls.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",()=>{Od(e,i.value)}),i.addEventListener("change",()=>{ls.set(e.workspace_identity,i.value),ur.delete(e.workspace_identity),t.querySelector(".project-space-guardrail-confirmation")?.remove(),s.textContent="Save Space",s.disabled=!i.value,at?.()}),i.addEventListener("blur",Fy);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{Od(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",()=>{q0(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",()=>{V0(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",()=>{Gy(e)}),t.append(n,i,s,c,l,d,u);const p=ur.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 g=document.createElement("strong");g.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 v=document.createElement("ul");for(const S of p.warnings){const T=document.createElement("li"),N=document.createElement("strong");N.textContent=`${H0(S)}: `;const P=document.createElement("span");P.textContent=S.message,T.append(N,P),v.appendChild(T)}const b=document.createElement("button");b.className="settings-button",b.type="button",b.textContent="I understand, save Space",b.addEventListener("click",()=>{const S=ur.get(e.workspace_identity);!S||S.scopeId!==i.value||Od(e,S.scopeId,S.requiredGuardrailTokens)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{ur.delete(e.workspace_identity),at?.()}),f.append(g,h,v,b,w),t.appendChild(f)}const m=uo.get(e.workspace_identity);if(m){const f=document.createElement("div");f.className="settings-note project-guardrail-confirmation",f.setAttribute("role","alert");const g=document.createElement("strong");g.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 v=document.createElement("p");v.textContent="Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device.";const b=document.createElement("button");b.className="settings-button danger",b.type="button",b.textContent="I understand, forget local memories",b.addEventListener("click",()=>{Gy(e,!0)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{uo.delete(e.workspace_identity),at?.()}),f.append(g,h,v,b,w),t.appendChild(f)}return t}function Hy(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(Ly([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(My([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 · ${Ry(e.latest_session_at)}`,t.appendChild(o),t.appendChild($y([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=Rd(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${x0(e)} · ${e.identity_source} · ${Ry(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 v=document.createElement("strong");v.textContent="Project sharing";const b=document.createElement("ul");b.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=P0(w);const N=document.createElement("span");N.textContent=` — ${w.lifecycle.label}. ${w.lifecycle.explanation}`,S.append(T,N),b.appendChild(S)}h.append(v,b),s.appendChild(h)}if(Zr(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=I0(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 ${fs(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(v=>v.message).join(" ")}`,s.appendChild(h)}if(e.statuses.length>0){const h=document.createElement("div");h.className="project-inventory-badges";for(const v of e.statuses){const b=document.createElement("span");b.className=`project-status-badge ${v}`,b.textContent=N0(v),h.appendChild(b)}s.appendChild(h)}const p=document.createElement("details");p.className="project-inventory-details",p.open=Ed.has(e.workspace_identity),p.addEventListener("toggle",()=>{p.open?Ed.add(e.workspace_identity):Ed.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 g=[["Workspace identity",e.workspace_identity],["Project",e.project],["CWD",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",Rd(e)],["Suggested Space",e.suggested_scope_id?fs(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,v]of g){const b=document.createElement("dt");b.textContent=h;const w=document.createElement("dd");w.textContent=v==null||v===""?"—":String(v),f.append(b,w)}return p.appendChild(f),p.appendChild(W0(e)),t.appendChild(p),t}function z0(e){const t=[...new Set(e.map(n=>Rd(n)))];return t.length===1?t[0]:"Mixed Spaces"}function J0(e){if(e.length===1)return Hy(e[0]);const t=Dd(e[0]),n=e.filter(Zo),r=Dy(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster";const o=Ld(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(Ly(n,`Select all identities for ${Ld(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(My(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=z0(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($y(r));const g=document.createElement("div");g.className="project-inventory-actions";const h=e.filter(Id);if(h.length===0){const S=document.createElement("div");S.className="settings-note",S.textContent=e.every(Zr)?"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.",g.appendChild(S),d.appendChild(g)}else{const S=h.map(x=>({project:x,warnings:(x.guardrail_warnings??[]).filter(G=>G.requires_confirmation)})),T=S.some(({warnings:x})=>x.length>0),N=new Set(h.map(x=>x.suggested_scope_id).filter(x=>!!x)),P=new Set(h.map(x=>x.resolved_scope_id)),A=document.createElement("select");A.className="project-domain-select",A.setAttribute("aria-label",`Space for ${Ld(e[0])} group`);const M=document.createElement("option");M.value="",M.textContent="Choose Space…",A.appendChild(M),Uy(A),A.value=By(ds.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=!A.value||T,U.addEventListener("click",()=>{K0(h,A.value)}),A.addEventListener("change",()=>{A.value?ds.set(t,A.value):ds.delete(t),U.disabled=!A.value||T}),A.addEventListener("blur",Fy),g.append(A,U),N.size>1||P.size>1||T){const x=document.createElement("div");if(x.className="settings-note project-attention-note",x.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:E,warnings:$}of S){if($.length===0)continue;const L=document.createElement("li"),J=document.createElement("strong");J.textContent=`Blocked identity: ${E.workspace_identity}`;const H=document.createElement("span");H.textContent=` — ${$.map(k=>k.message).join(" ")}`,L.append(J,H),G.appendChild(L)}x.appendChild(G)}g.appendChild(x)}d.appendChild(g)}const v=document.createElement("details");v.className="project-inventory-details",v.open=Ad.has(t),v.addEventListener("toggle",()=>{v.open?Ad.add(t):Ad.delete(t)});const b=document.createElement("summary"),w=e.reduce((S,T)=>S+(T.guardrail_warnings??[]).filter(N=>N.severity==="warning").length,0);b.textContent=w>0?`Advanced Project administration — ${w.toLocaleString()} item${w===1?"":"s"} need attention`:"Advanced Project administration",v.appendChild(b),v.appendChild(d);for(const S of e)v.appendChild(Hy(S));return i.appendChild(v),i}function Y0(e){const t=new Map;for(const n of e){const r=Dd(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function Ky(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 qy(){document.getElementById("projectsInventorySkeleton")?.remove()}function Vy(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(qy(),n.textContent="",e.projects.length===0)Ky("No projects match those filters.");else for(const s of Y0(e.projects))n.appendChild(J0(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),pr(),r&&[...n.querySelectorAll("[data-project-focus-key]")].find(s=>s.dataset.projectFocusKey===r)?.focus()}function X0(e,t){L0().then(()=>{t===ps&&(jy()||Vy(e))})}async function Q0(){const e=new Map;let t=0;for(;;){const n=await Po({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 Wy(e,t,n){const r=Ke("recipientPolicyManagementMount");r&&Fm(r,ea(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Ct.clear(),pr(),at?.()}})}async function zy(){const e=Ke("projectsInventoryMeta"),t=Ke("projectsInventoryList");if(!e||!t)return;if(jy()){us=!0;return}us=!1;const n=++ps;Rn=!1,Dn=!1,pr(),e.textContent="Loading project inventory…";try{const[r,i,o,s,c]=await Promise.all([Po({limit:xd,offset:lo,q:Ke("projectsSearch")?.value.trim()||void 0,status:Ke("projectsStatusFilter")?.value||void 0}),dw(),Q0().then(u=>({ok:!0,projects:u})).catch(()=>({ok:!1,projects:[]})),cw().then(u=>({ok:!0,review:u})).catch(u=>({ok:!1,error:u})),Gs().then(u=>({ok:!0,intent:u})).catch(u=>({ok:!1,error:u}))]);if(n!==ps)return;if(Pd=i.scopes,Rn=o.ok,Dn=c.ok,Qr=c.ok?c.intent:ms,o.ok){const u=new Set(ea(o.projects).map(p=>p.canonicalProjectIdentity));for(const p of Ct)u.has(p)||Ct.delete(p)}const l=Ke("projectShareFlowMount");l&&Gm(l,o.projects,{inventoryError:!o.ok});const d=Ke("recipientPolicyReviewMount");d&&("review"in s?C0(d,s.review,zy):T0(d,s.error)),Wy(o.projects,Qr,!o.ok||!c.ok),Vy(r),X0(r,n)}catch(r){if(n!==ps)return;Rn=!1,Dn=!1,Qr=ms;const i=Ke("projectShareFlowMount");i&&Gm(i,[],{inventoryError:!0}),Wy([],ms,!0),pr(),qy(),e.textContent="Project inventory failed to load.",Ky(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 Ay){const s=document.createElement("option");s.value=i,s.textContent=o,t.appendChild(s)}const n=()=>{lo=0,at?.()};Ke("projectsSearch")?.addEventListener("input",n),t?.addEventListener("change",n),Ke("projectsPrevPage")?.addEventListener("click",()=>{lo=Math.max(0,lo-xd),at?.()}),Ke("projectsNextPage")?.addEventListener("click",()=>{lo+=xd,at?.()});const r=Ke("projectsShareSelected");r&&r.dataset.recipientPolicyBound!=="true"&&(r.dataset.recipientPolicyBound="true",r.addEventListener("click",()=>{Ct.size!==0&&Ti({mode:"project-add",projectIds:[...Ct].sort()})})),pr()}function jd(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 eD(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 Jy="codemem-settings-advanced",Yy="gpt-5.1-codex-mini",Xy="claude-4.5-haiku",tD=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],nD={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"},rD=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),iD={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 oD(){try{return globalThis.localStorage?.getItem(Jy)==="1"}catch{return!1}}function aD(e){try{globalThis.localStorage?.setItem(Jy,e?"1":"0")}catch{}}function dn(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function ke(e,t,n){if(dn(t,n))return t[n];if(dn(e,n))return e[n]}function Ee(e){return e==null?"":String(e)}function hs(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 sD(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function cD(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function ze(e){const t=e.trim();return t===""?"":t}function lD(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:Xy,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:Yy,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:Xy,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:Yy,source:"Recommended (direct API)"}}function dD(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(!dn(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(!dn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!dn(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 hs(n[t]);default:return dn(n,t)?n[t]:""}}function uD(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{dn(r,i)&&(r[i]=dD(t,i))}),r}function pD(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=jd(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(T){if(!i||n.has("claude_command"))throw T;const N=r.claude_command;o=Array.isArray(N)?N.filter(P=>typeof P=="string").map(P=>P.trim()).filter(P=>P.length>0):[]}let s=[];try{s=jd(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(T){if(!i||n.has("codex_command"))throw T;const N=r.codex_command;s=Array.isArray(N)?N.filter(P=>typeof P=="string").map(P=>P.trim()).filter(P=>P.length>0):[]}let c=[];try{c=jd(t.observerAuthCommand,{label:"observer auth command"})}catch(T){if(!i||n.has("observer_auth_command"))throw T;const N=r.observer_auth_command;c=Array.isArray(N)?N.filter(P=>typeof P=="string"):[]}let l={};try{l=eD(t.observerHeaders)}catch(T){if(!i||n.has("observer_headers"))throw T;const N=r.observer_headers;N&&typeof N=="object"&&!Array.isArray(N)&&Object.entries(N).forEach(([P,A])=>{typeof P=="string"&&P.trim()&&typeof A=="string"&&(l[P]=A)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),p=t.observerRichTemperature.trim(),m=t.observerRichMaxOutputTokens.trim(),f=t.rawEventsSweeperIntervalS.trim(),g=d===""?"":Number(d),h=u===""?"":Number(u),v=p===""?"":Number(p),b=m===""?"":Number(m),w=Number(f),S=f===""?"":w;if(d!==""&&!Number.isFinite(g))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 v!="number"||!Number.isFinite(v)||v<0))throw new Error("rich tier temperature must be a non-negative number");if(m!==""&&(typeof b!="number"||!Number.isFinite(b)||b<=0||!Number.isInteger(b)))throw new Error("rich tier max output tokens must be a positive integer");if(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:v,observer_rich_reasoning_effort:ze(t.observerRichReasoningEffort),observer_rich_reasoning_summary:ze(t.observerRichReasoningSummary),observer_rich_max_output_tokens:b,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:g,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 mD(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,m])=>typeof p=="string"&&p.trim()&&typeof m=="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:Ee(ke(t,n,"observer_provider")),observerModel:Ee(ke(t,n,"observer_model")),observerTierRoutingEnabled:hs(ke(t,n,"observer_tier_routing_enabled")),observerSimpleModel:Ee(ke(t,n,"observer_simple_model")),observerSimpleTemperature:Ee(ke(t,n,"observer_simple_temperature")),observerReasoningEffort:Ee(ke(t,n,"observer_reasoning_effort")),observerReasoningSummary:Ee(ke(t,n,"observer_reasoning_summary")),observerRichModel:Ee(ke(t,n,"observer_rich_model")),observerRichTemperature:Ee(ke(t,n,"observer_rich_temperature")),observerRichReasoningEffort:Ee(ke(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:Ee(ke(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:Ee(ke(t,n,"observer_rich_max_output_tokens")),observerRuntime:Ee(ke(t,n,"observer_runtime"))||"api_http",observerAuthSource:Ee(ke(t,n,"observer_auth_source"))||"auto",observerAuthFile:Ee(ke(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:Ee(ke(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:Ee(ke(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:Ee(ke(t,n,"observer_max_chars")),packObservationLimit:Ee(ke(t,n,"pack_observation_limit")),packSessionLimit:Ee(ke(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:Ee(ke(t,n,"raw_events_sweeper_interval_s")),syncEnabled:hs(ke(t,n,"sync_enabled")),syncHost:Ee(ke(t,n,"sync_host")),syncPort:Ee(ke(t,n,"sync_port")),syncInterval:Ee(ke(t,n,"sync_interval_s")),syncMdns:hs(ke(t,n,"sync_mdns")),syncCoordinatorUrl:Ee(ke(t,n,"sync_coordinator_url")),syncCoordinatorGroup:Ee(ke(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:Ee(ke(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:Ee(ke(t,n,"sync_coordinator_presence_ttl_s"))}}function fD(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=lD(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),ze(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>dn(t,r))?"Env override":n.source}: ${n.model}`}function hD(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 gD(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function vD(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 yD(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 bD(e){return!e}function _D(e,t,n){return t.has(e)||n.has(e)}function wD(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:oD(),controller:null,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...iD}}};function SD(){W.controller?.hideTooltip()}function mr(e){if(W.controller){W.controller.setRenderState(e);return}W.renderState={...W.renderState,...e}}function CD(e){mr({values:{...W.renderState.values,...e}})}function TD(e){const t=["observer","queue","sync"].includes(e)?e:"observer";W.activeTab=t,W.controller?.setActiveTab(t)}function gs(e,t=!0){_.settingsDirty=e,t&&W.controller?.setDirty(e)}function ND(e){W.showAdvanced=e,W.controller?.setShowAdvanced(e)}function Qy(){return W.open}function kD(e){return _D(e,W.protectedKeys,rD)}function Zy(e={}){return pD({values:W.renderState.values,touchedKeys:W.touchedKeys,baseline:W.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function xD(e){mr({observerStatus:e&&typeof e=="object"?e:null})}function PD(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=mD(t);W.envOverrides=i,W.protectedKeys=new Set(o),_.configDefaults=n,_.configPath=t.path||"",mr({effectiveText:Object.keys(i).length>0?"Some fields are managed by environment settings.":"",overridesVisible:Object.keys(i).length>0,pathText:_.configPath?`Config path: ${_.configPath}`:"Config path: n/a",providers:sD(t.providers),statusText:"No unsaved changes",values:s}),W.touchedKeys=new Set;try{W.baseline=uD(Zy({allowUntouchedParseErrors:!0}),r,i)}catch{W.baseline={}}gs(!1)}async function ED(){if(!W.open)try{const[e,t]=await Promise.all([k_(),N_().catch(()=>null)]);PD(e),xD(t)}catch{}}function Fd(e){return String(e||"").replace(/_/g," ")}function Bd(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 ID(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 RD(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function DD({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),": ",ID(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 ${RD(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 eb(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 mo(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function LD(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 $D(){const e=Ie("settingsModal");(LD(e)[0]||e)?.focus()}function MD(){const[e,t]=I({anchor:null,content:"",visible:!1}),n=B(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=mo(u.target);p&&r(p)},s=u=>{const p=mo(u.target);if(!p)return;const m=u.relatedTarget;m instanceof Element&&p.contains(m)||i()},c=u=>{const p=mo(u.target);p&&r(p)},l=u=>{mo(u.target)&&i()},d=u=>{const p=mo(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&&eb(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&&eb(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:xe(()=>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 OD({DialogContent:e,onClose:t}){const[n,r]=I(W.open),[i,o]=I(["observer","queue","sync"].includes(W.activeTab)?W.activeTab:"observer"),[s,c]=I(_.settingsDirty),[l,d]=I(W.renderState),[u,p]=I(W.showAdvanced),{tooltipPortal:m,setTooltip:f}=MD();W.open=n,W.activeTab=i,_.settingsDirty=s,W.renderState=l,W.showAdvanced=u,K(()=>(W.controller={hideTooltip:()=>{f({anchor:null,content:"",visible:!1})},setActiveTab:h=>{const v=["observer","queue","sync"].includes(h)?h:"observer";W.activeTab=v,o(v)},setDirty:h=>{_.settingsDirty=h,c(h)},setOpen:h=>{W.open=h,r(h)},setRenderState:h=>{const v={...W.renderState,...h};W.renderState=v,d(v)},setShowAdvanced:h=>{W.showAdvanced=h,aD(h),p(h)}},()=>{W.controller&&(W.controller=null)}),[]),K(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const g=re(()=>{W.startPolling&&W.refresh&&t(W.startPolling,W.refresh)},[t]);return a(te,{children:[a(wi,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:h=>{h.preventDefault()},onOpenAutoFocus:h=>{h.preventDefault(),$D()},onOpenChange:h=>{if(h){r(!0);return}g()},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 fo({children:e,hidden:t=!1}){return a("div",{className:"settings-note",hidden:t,children:e})}function Ud({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 jD({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(Ud,{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(Se,{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(Kr,{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(Kr,{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(Se,{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(Se,{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(Kr,{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(fo,{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(Se,{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(Se,{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(Kr,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),a("div",{className:"small",children:m("observer_headers")})]})]})]})}function vs({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(Br,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"})]})}function FD({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:o}){return a(te,{children:[a(Ud,{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(Se,{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(vs,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),a("div",{className:"small",children:o()}),a(fo,{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(Se,{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(Se,{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(Se,{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(Se,{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(Se,{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(Se,{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(Se,{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(Se,{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(Se,{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(fo,{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(Se,{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(Se,{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 BD({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(te,{children:[a(Ud,{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(vs,{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(Se,{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(Se,{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(Se,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),a(vs,{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(Se,{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(Se,{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(fo,{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(Se,{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(Se,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function UD({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=>Dr(p,{onSubmit:s,disabled:u}),children:[a("div",{className:"modal-header",children:[a("h2",{id:"settingsTitle",children:"Settings"}),a(Mo,{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(vs,{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(fo,{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(Wf,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:tD,triggerClassName:"settings-tab",value:t,children:[a(Yn,{className:"settings-panel",forceMount:!0,value:"observer",children:a(jD,{...e,observerStatusBannerSlot:d})}),a(Yn,{className:"settings-panel",forceMount:!0,value:"queue",children:a(FD,{...e})}),a(Yn,{className:"settings-panel",forceMount:!0,value:"sync",children:a(BD,{...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 GD(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};return Object.entries(t).forEach(([c,l])=>{o(c)||dn(r,c)&&!i.has(c)||cD(l,n[c])||(s[c]=l)}),s}function HD(e){const t=s=>{const c=nD[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 KD(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=>Fd(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>Fd(String(p))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>Fd(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: ${Bd(r)}.`),i.length&&d.push(`Live settings updated: ${Bd(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 ${Bd(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 qD=()=>fD(W.renderState.values,W.envOverrides),VD=()=>hD(W.renderState.values),WD=()=>gD(W.renderState.values),zD=()=>vD(W.renderState.values),JD=()=>yD(W.renderState.values),YD=()=>bD(W.showAdvanced),{onTextInput:XD,onSelectValueChange:QD,onSwitchInput:ZD}=HD({getTouchedKeys:()=>W.touchedKeys,getValues:()=>W.renderState.values,updateFormState:CD,setDirty:e=>gs(e)});function eL(){const e=W.renderState.observerStatus;return a(DD,{status:e})}function tL(){const e=W.renderState.values,t=String(_.configDefaults?.observer_max_chars||""),n=e.observerAuthSource==="file",r=e.observerAuthSource==="command",i=e.observerTierRoutingEnabled;return a(UD,{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:YD,onTextInput:XD,onSelectValueChange:QD,onSwitchInput:ZD,getObserverModelLabel:WD,getObserverModelTooltip:zD,getObserverModelDescription:JD,getObserverModelHint:qD,getTieredRoutingHelperText:VD,protectedConfigHelp:wD},activeTab:W.activeTab,showAdvanced:W.showAdvanced,renderState:W.renderState,settingsDirty:_.settingsDirty,onClose:()=>{W.startPolling&&W.refresh&&ys(W.startPolling,W.refresh)},onSave:()=>{W.startPolling&&W.refresh&&oL(W.startPolling,W.refresh)},onActiveTabChange:TD,onAdvancedToggle:ND,observerStatusBannerSlot:a(eL,{})})}function nL(){return a(OD,{DialogContent:tL,onClose:ys})}function rL(){const e=Ie("settingsDialogMount");e&&Ue(a(nL,{}),e)}function tb(){Ie("settingsDialogMount")&&(W.shellMounted||(rL(),W.shellMounted=!0))}function iL(e){W.shellMounted||tb(),W.open=!0,W.previouslyFocused=document.activeElement,e(),W.controller?.setOpen(!0)}function ys(e,t){if(_.settingsDirty&&!globalThis.confirm("Discard unsaved changes?")){W.controller?.setOpen(!0);return}W.open=!1,W.controller?.setOpen(!1),SD(),(W.previouslyFocused&&typeof W.previouslyFocused.focus=="function"?W.previouslyFocused:Bc("settingsButton"))?.focus(),W.previouslyFocused=null,W.touchedKeys=new Set,e(),t()}async function oL(e,t){if(!W.renderState.isSaving){mr({isSaving:!0,statusText:"Saving changes…"});try{const n=GD({current:Zy({allowUntouchedParseErrors:!0}),baseline:W.baseline,envOverrides:W.envOverrides,touchedKeys:W.touchedKeys,isProtected:kD});if(Object.keys(n).length===0){mr({isSaving:!1,statusText:"No unsaved changes"}),gs(!1),ys(e,t);return}const r=KD(await x_(n));mr({isSaving:!1,statusText:"Saved changes"}),gs(!1),ys(e,t),ne(r.message,r.type)}catch(n){mr({isSaving:!1,statusText:`Save failed: ${n instanceof Error?n.message:"unknown error"}`})}}}function aL(e,t,n){W.startPolling=t,W.refresh=n,tb(),Bc("settingsButton")?.addEventListener("click",()=>iL(e))}function sL(e){e.dataset.syncRenderRoot="preact"}function cL(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function Ze(e,t){sL(e),Ue(t,e)}function ei(e){e.dataset.syncRenderRoot==="preact"&&Ue(null,e)}function lL(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 dL(e){return typeof e=="object"&&e!==null}function uL(e,t){return _.pairingCommandRaw="",{payloadText:e,hintText:t}}function pL(e){if(!dL(e))return uL("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 _.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function mL(){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 fL(){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 hL(){const e=_.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 gL(){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 vL(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 yL({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 bL({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 nb({text:e}){return a(te,{children:e})}function _L({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function wL(e,t){if(!t.length){ei(e);return}Ze(e,a(yL,{items:t}))}function SL(e,t,n){if(!t.length){ei(e);return}Ze(e,a(bL,{attempts:t,note:n}))}function fr(e,t){Ze(e,a(_L,{...t}))}function rb(e,t,n){Ze(e,a(nb,{text:n.payloadText})),t&&Ze(t,a(nb,{text:n.hintText}))}function ib({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:o,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=B(null),p=B(null),m=B(!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(ya,{forceMount:!0,asChild:!0,children:a("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return a(va,{open:e,onOpenChange:t,children:[a(Qf,{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 CL({open:e,onOpenChange:t}){return a(ib,{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(Se,{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(Se,{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(Kr,{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 TL({contentHost:e,open:t,onOpenChange:n}){return a(ib,{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 NL(e,t){Ze(e,a(CL,{...t}))}function kL(e,t){Ze(e,a(TL,{...t}))}function de(e){return String(e??"").trim()}function xL(e){return de(e).replace(/\s+/g," ").toLowerCase()}function PL(e){const t=de(e);return t?t.slice(0,8):"Unnamed device"}function ob(e){return de(e?.last_error).toLowerCase()}function ab(e){return e.includes("401")&&e.includes("unauthorized")}function sb(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var EL={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function cb(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=cb(e);return!de(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function lb(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=LL(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=>db(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=>db(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 db(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 IL(n)?"trust":RL(n)?"scope":null}function IL(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function RL(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function DL(e){const t=de(e?.reason);return EL[t]??(t.replaceAll("_"," ")||"sync filters")}function LL(e){const t=new Map;for(const n of e){const r=DL(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 ub(e){const t=de(e.localName);if(t)return t;const n=de(e.coordinatorName);return n||PL(de(e.deviceId))}function $L(e){const t=de(e.localName),n=de(e.coordinatorName);return t||n?!1:!!de(e.deviceId)}function ML(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 ho(e){const t=de(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=ob(e);return ab(n)?"needs-repair":sb(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function ti(e){const t=e?.status||{},n=de(t.peer_state),r=ob(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}:ab(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}:sb(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 OL={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 jL(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:OL[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 pb(e){return Array.isArray(e)?e.map(t=>de(t)).filter(t=>!!t):[]}function mb(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 bs(e,t){return e?e.replaceAll("_"," "):t}function FL(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=[bs(de(r.kind),"user"),bs(de(r.authority_type),"local"),`${bs(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 fb(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=bs(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 BL=["personal","private","home","mine","me"],UL=["oss","open source","opensource","community","public"],GL=["work","client"],HL=["local","legacy","review"];function KL(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>de(t)??"").join(" ").toLowerCase()}function qL(e){return[e.scope_id,e.label,e.kind].map(t=>de(t)??"").join(" ").toLowerCase()}function hb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gd(e,t){const n=KL(e);return t.some(r=>{const i=hb(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function gb(e){return Gd(e,BL)||Gd(e,UL)}function VL(e){const t=qL(e);return HL.some(n=>{const r=hb(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function WL(e){return!gb(e)&&(!VL(e)||Gd(e,GL))}function zL(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(gb),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 JL(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function YL(e){const t=pb(e?.effective_include),n=pb(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${mb(t,"all projects")}`,o=`Exclude filter: ${mb(n,"no exclusions")}`,s=JL(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 XL(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=de(n?.display_name),i=de(n?.actor_id),o=xL(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 vb(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 QL=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),ZL=new Set(["pending","verifying","waiting"]);function e$(e){return(Array.isArray(e?.groups)?e.groups.map(t=>de(t)).filter(Boolean):[]).join(", ")||"none"}function yb(e){return de(e?.projects?.[0]?.display_name)||"the shared Project"}function t$(e){const t=e?.items?.find(n=>n.state!=="active");return de(t?.canonicalProjectIdentity)||"the shared Project"}function n$(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=ti(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function r$(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&ti(n).state==="mutual-trust"&&!fb(n).rows.some(r=>r.status==="pending"))}function i$(e){return e.some(t=>de(t.status?.peer_state)==="online"&&ti(t).state==="mutual-trust")}function o$(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=ti(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function a$(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 bb(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=e$(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=yb(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&&QL.has(m)}),d=i.find(p=>{const m=p.state;return m!==void 0&&ZL.has(m)});if(l||d){const p=l?yb(l):t$(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(a$(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(n$(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."}:o$(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&&r$(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}:i$(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 s$(e){return e.discovered?.stale?e.peer?ho(e.peer)!=="connected":!0:!1}function _b(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 Hd(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 c$(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 l$(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 d$(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 u$(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=d$(n,r),o=e.duplicatePersonDecisions??{},s=XL(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=ub({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId}),u=l.peer?ho(l.peer):"waiting",p=l.peer?ti(l.peer):null,m=de(l.discovered?.fingerprint),f=de(l.peer?.fingerprint);if(l.peer&&m&&f&&m!==f){c.push(_b({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 g=p?.description||de(l.peer?.last_error)||"Sync needs review.";c.push(_b({id:l.deviceId,name:d,title:p?.state==="needs-repairing"?`${d} needs re-pairing`:`${d} needs review`,summary:g}))}l.peer&&p?.state==="trusted-by-you"&&c.push(Hd({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(Hd({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(Hd({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&&$L({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(c$({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:bb({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>ho(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>s$(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 Ln(e){const t=document.getElementById(e);t&&t.remove()}var Sb=!1;function p$(e){Sb=e}var Kd=!1;function m$(e){Kd=e}var qd=!1;function f$(e){qd=e}var h$=new Set,Vd=new Set,Wd=new Set,Cb="codemem-sync-duplicate-person-decisions";function g$(e){const t=String(e||"").trim();t&&(Vd.add(t),Wd.add(t),h$.add(t))}function zd(e){const t=String(e||"").trim();return!!t&&Vd.has(t)}function v$(e){const t=String(e||"").trim();t&&Vd.delete(t)}function y$(e){const t=String(e||"").trim();return!t||!Wd.has(t)?!1:(Wd.delete(t),!0)}function Jd(){try{const e=localStorage.getItem(Cb);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Tb(e){try{localStorage.setItem(Cb,JSON.stringify(e))}catch{}}function Nb(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function b$(){return Jd()}function _$(e,t){const n=Nb(e);if(!n)return;const r=Jd();r[n]=t,Tb(r)}function w$(e){const t=Nb(e);if(!t)return;const n=Jd();delete n[t],Tb(n)}function kb(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function xb(e){const t=String(e||"");return t?kb(t):""}function S$(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function C$(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function _s(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 ws(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":_s(e)}function T$(e){return(Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function Pb(){return vb({actors:_.lastSyncActors,peers:_.lastSyncPeers,duplicatePeople:_.lastSyncViewModel?.duplicatePeople}).visibleActors}function N$(e=""){const t=[{value:"",label:"No person assigned"}],n=Pb(),r=(Array.isArray(_.lastSyncActors)?_.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:ws(i)})}),t.filter((i,o,s)=>o===s.findIndex(c=>c.value===i.value))}function Eb(e){return Pb().filter(t=>String(t?.actor_id||"")!==e)}function k$(e,t){const n=Eb(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${ws(n)}. Assigned devices move now; existing memories keep their current provenance.`}function Yd(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=fa("div","sync-action"),i=fa("div","sync-action-text");i.textContent=n.label,i.appendChild(fa("span","sync-action-command",n.command));const o=fa("button","settings-button sync-action-copy","Copy");o.addEventListener("click",()=>Ai(n.command,o)),r.append(i,o),e.appendChild(r)})}}function Ab(e,t){return t&&e.error_redacted===!0}function Ib(){const e=document.getElementById("syncAttempts");if(!e)return;const t=_.lastSyncAttempts,n=String(_.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){fr(e,hL());return}const r=vL(n,t.slice(0,5).some(i=>i.status==="error"));SL(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(_.lastSyncPeers)?_.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=Ri();if(d&&i.error){const m=String(i.error);u.push(p?kb(m):m),Ab(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):"",...Ab(i,p)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}}),r)}function x$(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&fr(e,fL()),t&&fr(t,gL()),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."),Yd(r,[])}function ni(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function P$(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=ni(n.would_remove),o=ni(n.ambiguous),s=ni(r.applied),c=ni(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 Rb(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;Ln("syncDiagSkeleton");const r=_.lastSyncStatus;if(!r){fr(e,mL()),Yd(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||lL(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"),g=r.retention||{},h=r.cleanup_diagnostics,v=h?.stale_peer_rows??{},b=ni(v.would_remove),w=ni(v.ambiguous),S=g.enabled===!0,T=Number(g.last_deleted_ops||0),N=g.last_run_at||null,P=String(g.last_error||""),A=f==="offline-peers"?"Offline peers":f==="needs_attention"?"Needs attention":f==="rebootstrapping"?"Rebootstrapping":Kg(f),M=f==="disabled"||r.enabled===!1,U=Object.keys(i).length,x=!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"]:x?["Advanced sync is ready but idle","Use Show pairing command under People & devices to connect another device, then this panel will start showing live peer status and recent attempts"]:[`Advanced state: ${A}`,`Peers: ${U}`,c?`Last sync: ${xn(qr(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(N?`Retention last ran ${xn(qr(N))} ago (approx oldest-first)`:"Retention enabled"),b>0?$.push(`${b.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"}]:x?[{label:"State",value:"No peers"},{label:"Mode",value:"Ready to pair"},{label:"Pending events",value:p},{label:"Last sync",value:"Waiting for first peer"}]:[{label:"State",value:A},{label:"Pending events",value:p},{label:"Last sync",value:c?`${xn(qr(c))} ago`:"never"},{label:"Last peer ping",value:l?`${xn(qr(l))} ago`:"never"},{label:"Retention",value:S?N?`${T.toLocaleString()} ops last run (approx)`:"Enabled":"Disabled"}];!M&&!x&&(d||u)&&G.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!M&&!x&&s.seconds_since_last&&G.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!M&&!x&&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&&!x&&h&&G.push({label:"Cleanup",value:P$(h)}),wL(e,G);const E=[];x||f==="offline-peers"||(f==="stopped"?(E.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),E.push({label:"Run one sync pass now.",command:"codemem sync once"})):f==="needs_attention"?E.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):f==="rebootstrapping"?E.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||f==="error"?(E.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),E.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!M&&!x&&p>0&&E.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!M&&w>0?E.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!M&&b>0&&E.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),Yd(n,E)}var E$="syncRedactMount",A$="syncRedactLabel",Db=()=>{};function I$(e){Db=e}var Xd=()=>{};function Qd(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;kL(e,{contentHost:t,open:_.syncPairingOpen,onOpenChange:r=>{if(uN(r),Qd(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&rb(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}Xd()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=_.pairingCommandRaw;r&&await Ai(r,n)})}function Zd(){Qd();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;rb(e,t,pL(_.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!_.pairingCommandRaw)}function Lb(){const e=document.getElementById(E$);e&&Ze(e,y(Br,{"aria-labelledby":A$,checked:Ri(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{pN(t),Lb(),Xd(),Rb(),Db(),Ib(),Zd()},thumbClassName:"sync-redact-switch-thumb"}))}function R$(e){Xd=e,Qd(),Lb()}function D$(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function ri(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),D$(e),e.addEventListener("input",()=>go(e),{once:!0}),!1}function go(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 hr=new Map,eu=null,L$={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 $$(e){return L$[e instanceof Error?e.message:String(e)]??"Setup could not be retried. Review diagnostics for details."}function M$(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 O$(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function tu(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 j$({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[o,s]=I(!1),[c,l]=I(()=>hr.get(e.operation_id)??null),d=B(null),u=e.lifecycle.primary_action;K(()=>{eu!==e.operation_id||!d.current||(eu=null,d.current.focus())},[c?.message,e.operation_id]);async function p(h){s(!0);try{let v=h;if(!v&&n){const w=(await n(e.operation_id)).lifecycle.primary_action;w?.kind==="copy_invite"&&(v=w.invite_link)}if(!v)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(w=>navigator.clipboard.writeText(w)))(v);const b={message:"Invite copied.",tone:"success"};hr.set(e.operation_id,b),l(b)}catch(v){const b={message:v instanceof Error?v.message:"Invite could not be copied.",tone:"warning"};hr.set(e.operation_id,b),l(b)}finally{s(!1)}}async function m(){s(!0);try{const h=await t(e.operation_id),v=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"};hr.set(e.operation_id,v),eu=e.operation_id,l(v),await r()}catch(h){const v={message:$$(h),tone:"warning"};hr.set(e.operation_id,v),l(v),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function f(){const h=e.projects.map(v=>v.project_id?.trim()).filter(v=>!!v);if(h.length!==e.projects.length){const v={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};hr.set(e.operation_id,v),l(v);return}if(!ta(h,e.person.display_name)){const v={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};hr.set(e.operation_id,v),l(v)}}function g(){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":`${tu(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:tu(e.lifecycle.state)}),a("ul",{"aria-label":`${tu(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((h,v)=>a("li",{className:"peer-scope-chip",children:h.display_name},`${h.display_name}:${v}`))}),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:g,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 F$({operations:e,...t}){const n=e[0].person,r=O$(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(j$,{operation:i,...t},i.operation_id))]})}function B$(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:M$(e.operations).map(t=>a(F$,{...e,operations:t},t[0].person.actor_id))})}function U$(e,t){Ze(e,a(B$,{...t}))}function $b({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 G$(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 H$({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=_s(e),c=T$(o),l=Eb(o),d=l.map(E=>String(E.actor_id||"")).join("|"),[u,p]=I(s),[m,f]=I(!1),[g,h]=I("Rename"),[v,b]=I(!1),[w,S]=I("Merge into selected person"),[T,N]=I(""),[P,A]=I(!1);K(()=>{p(s),f(!1),h("Rename"),b(!1),S("Merge into selected person"),N(""),A(!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(E=>{const $=String(E.actor_id||"");return{label:E.is_local?ws(E):_s(E),value:$}})];async function x(){const E=u.trim();if(!E)return;f(!0),h("Saving…");let $=!1;try{await n(o,E),$=!0}catch{h("Retry rename")}finally{f(!1),$&&h("Rename")}}async function G(){if(!T)return;const E=l.find(L=>String(L.actor_id||"")===T);if(!E||!await Kt({title:`Merge ${s} into ${_s(E)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;b(!0),S("Merging…");let $=!1;try{await r(T,o),$=!0}catch{S("Retry merge")}finally{b(!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:ws(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?G$(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(Se,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:m||v,type:"text",value:u,onInput:E=>p(E.currentTarget.value),onKeyDown:E=>Dr(E,{onSubmit:()=>{x()},disabled:m||v||!u.trim()})}),a("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:m||v,onClick:()=>{x()},children:g}),a("button",{type:"button",className:"settings-button danger",disabled:m||v,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||v,onClick:()=>A(E=>!E),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:v||l.length===0,itemClassName:"sync-radix-select-item",onValueChange:N,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:v||l.length===0||!T,onClick:()=>{G()},children:w})]}),a("div",{className:"peer-meta actor-merge-note",children:M})]}):null]})})]})}function K$({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(H$,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a($b,{detail:"Create a named person here, then assign devices below so team ownership stays readable.",title:"No people set up yet."})}function q$(e,t){Ze(e,a(K$,{...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: ${ir(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function z$({devices:e}){return a(te,{children:W$(e)})}function J$(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 Y$(e){const t=V$(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),ei(e.mount),ei(e.meta);return}const n=t.map(J$),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(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"})),Ze(e.meta,a(z$,{devices:t}))}var X$={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function Q$({state:e,size:t=8,"aria-label":n}){return a("span",{"aria-label":n??X$[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 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 eM(e){switch(ho(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var Ss=null,Mb=0,nu=new Set;function Ob(e){if(Ss!==e){Ss=e,Mb+=1;for(const t of nu)t(Mb)}}function tM(){const[,e]=I(0);return K(()=>(nu.add(e),()=>{nu.delete(e)}),[]),Ss}var nM={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 rM(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 iM(){window.location.hash="coordinator-admin"}function ru(e=_.lastCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function oM({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=ti(e),d=nM[ML(e)],u=e.status||{},p=FL(e),m=zd(o),f=m&&p.total===0,g=zL(e),h=jL(e),v=fb(e),b=YL(e.project_scope||{}),w=S$(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),N=Number.isFinite(T)&&T>0?T:0,P=S.length?S.map(ae=>Ri()?xb(ae):ae).join(" · "):N>0?`${N} ${N===1?"address":"addresses"} hidden`:"No addresses",A=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||""),x=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=y$(o),E=B(null),[$,L]=I(s),[J,H]=I(()=>_.syncPeerFeedbackById.get(o)??null),[k,R]=I(!1),[j,V]=I("Save name"),[ge,le]=I(!1),[ce,be]=I(!1),[Y,fe]=I("Remove device"),[X,_e]=I(String(e.actor_id||"")),[he,Q]=I(!1),[$e,ue]=I("Save assignment"),q=xe(()=>{const ae=N$(X),Ge=ae.some(On=>On.value===X);return X&&!Ge&&ae.push({value:X,label:e.claimed_local_actor?"You":String(e.actor_display_name||"Current assignment")}),ae},[e.actor_display_name,e.claimed_local_actor,X,_.lastSyncActors,_.lastSyncPeers,_.lastSyncViewModel]);K(()=>{m&&p.total>0&&v$(o)},[p.total,o,m]),K(()=>{L(s),H(_.syncPeerFeedbackById.get(o)??null),R(!1),V("Save name"),le(!1),be(!1),fe("Remove device"),_e(String(e.actor_id||"")),Q(!1),ue("Save assignment")},[s,e.actor_id,o]),K(()=>{!G||!E.current||queueMicrotask(()=>E.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),_.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),_.syncPeerFeedbackById.set(o,Ge),V("Save name")}catch{V("Retry")}finally{R(!1)}}async function qe(){if(f){const ae=ru();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}le(!0);try{const ae=await i(e,w);H(ae),ae&&_.syncPeerFeedbackById.set(o,ae)}finally{le(!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),fe("Removing…");let ae=!1;try{await n(o,c),ae=!0}catch{fe("Retry remove")}finally{be(!1),ae&&fe("Remove device")}}async function tt(){if(o){Q(!0),ue("Saving…");try{const ae=await t(o,X||null);H(ae),_.syncPeerFeedbackById.set(o,ae),ue("Save assignment")}catch{ue("Retry")}finally{Q(!1)}}}const pn=tM()===o&&o!=="",Lt=`device-drawer-${o||"unknown"}`,Nt=eM(e),$t=M?`Sync: ${ir(M)}`:"Sync: never",nt=ru(),Mt=`${pn?"Collapse":"Expand"} device ${s}`;return a(va,{asChild:!0,open:pn,onOpenChange:ae=>{ae?Ob(o):Ss===o&&Ob(null)},children:a("div",{ref:E,className:"peer-card","data-peer-device-id":o||void 0,children:[a(Qf,{asChild:!0,children:a("button",{"aria-label":Mt,className:"device-row-head device-row-head--trigger",type:"button",children:[a(Q$,{state:Nt}),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,g.badgeLabel?a("span",{className:"badge badge-offline",title:"Review whether explicit Space access matches this device's intended role.",children:g.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(ya,{"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:ge,onClick:()=>{qe()},title:w?void 0:"Address details are hidden; sync will target this device by ID.",children:ge?"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(Se,{"aria-label":`Friendly name for ${s}`,className:"peer-scope-input","data-device-name-input":o||void 0,disabled:k,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:k,onClick:()=>{oe()},children:j}),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}),x?a("div",{className:"peer-meta",children:x}):null,a("div",{className:"peer-meta",children:[M?`Sync: ${ir(M)}`:"Sync: never",U?`Ping: ${ir(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,g.isVisible?a("div",{className:"settings-note",role:"status",children:[a("strong",{children:g.title}),a("div",{children:g.message}),a("div",{children:g.detail})]}):null,a("div",{className:"peer-meta",children:b.note}),a("div",{className:"peer-scope-summary",children:"Space sync progress"}),a("div",{className:"peer-meta",children:v.total>0?"Per-Space progress for this device. Open details to see technical identifiers.":v.emptyMessage}),v.rows.length>0?a("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:v.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 ",ir(h.lastAt)]}):null]}):null,a("div",{className:"peer-scope-summary",children:"Who this device belongs to"}),a("div",{className:"peer-meta",children:A}),e.claimed_local_actor?a("div",{className:"peer-meta",children:rM(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:he,itemClassName:"sync-radix-select-item",onValueChange:_e,options:q,placeholder:"No person assigned yet",triggerClassName:"sync-radix-select-trigger sync-actor-select",value:X,viewportClassName:"sync-radix-select-viewport"})}),a("button",{type:"button",className:"settings-button",disabled:he,onClick:()=>{tt()},children:$e})]}),a("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),a("div",{className:"peer-meta",children:[b.statusLabel,". ",b.summary," ",b.note]}),nt?a("div",{className:"peer-actions",children:a("button",{type:"button",className:"settings-button",onClick:iM,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:J})]})]})]})})}function aM(e){const t=_.syncPeersSectionFeedback,n=_.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?a(te,{children:[a(gr,{feedback:t}),e.peers.map(i=>{const o=String(i.peer_device_id||i.name||"unknown-peer");return a(oM,{peer:i,...e},o)})]}):a(te,{children:[a(gr,{feedback:t}),a($b,{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 sM(e,t){Ze(e,a(aM,{...t}))}var un=async()=>{},Cs="";function iu(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function cM(e){un=e}function lM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;Ln("syncActorsSkeleton"),iu(!1);const n=vb({actors:_.lastSyncActors,peers:_.lastSyncPeers,duplicatePeople:_.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.`)),q$(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await Tw(i,o),await un()},onMerge:async(i,o)=>{try{await zu(i,o),ne("People combined. Assigned devices moved to the selected person."),await un()}catch(s){throw ne(et(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await Nw(i),ne("Person removed. Assigned devices have been unassigned."),await un()}catch(o){throw ne(et(o,"Failed to remove person."),"warning"),o}}})}function dM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");iu(!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&&fr(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function uM(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;U$(e,{operations:_.lastShareOperations,onAdvance:n=>fw(n),onLoadOperation:n=>mw(n),onReload:un});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=_.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":_.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function ou(){const e=document.getElementById("syncPeers");if(!e)return;Ln("syncPeersSkeleton");const t=_.lastSyncPeers,n=Array.isArray(t)?t:[];C$(_.syncPeersSectionFeedback,n)&&(_.syncPeersSectionFeedback=null),sM(e,{peers:n,onRename:async(r,i)=>{try{return await Bu(r,i),await un(),{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=lb(await Hs({address:i,peerDeviceId:o||void 0}));let c;s.ok?o&&zd(o)?c={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${ru()?"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 un()}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 Fu(r);const o={message:`Removed peer ${i}.`,tone:"success"};return _.syncPeerFeedbackById.delete(r),_.syncPeersSectionFeedback={...o,relatedPeerDeviceId:r},await un(),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 tw(r,i),await un(),{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 pM(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");iu(!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&&fr(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&&fr(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 jb(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");!e||!t||!n||Y$({devices:Array.isArray(_.lastSyncLegacyDevices)?_.lastSyncLegacyDevices:[],meta:n,mount:t,onValueChange:r=>{r!==Cs&&(Cs=r,jb())},panel:e,value:Cs})}function mM(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{Dr(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){ri(n,"Enter a name for the person.");return}go(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await Cw(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(Cs||"").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 kw(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 fM(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function au(e=fM()){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 Fb=!1;function hM(){Fb||(Fb=!0,window.addEventListener("hashchange",()=>{au()}))}var zt={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function gM(e){zt.loadSyncData=e}var vM=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function yM(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=_.lastCoordinatorAdminStatus?.readiness,r=String(_.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 su(){const e=document.getElementById("syncAdminDisclosureMount");e&&NL(e,{open:Sb,onOpenChange:t=>{p$(t),su(),Ns(),cu()}})}function bM(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function cu(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(_.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(_.lastTeamInvite?.warnings)?_.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function Ts(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=_.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 Ns(){const e=document.getElementById("syncInvitePolicyMount");e&&Ze(e,y(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,Ns())},options:vM,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:zt.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function _M(e,t){su(),Ns();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"),g=document.getElementById("syncRecipientDeviceName");let h="",v=0;r?.addEventListener("click",()=>{ta()||ne("Project sharing is unavailable. Refresh Projects and try again.","warning")});const b=async(w,S)=>{if(!u||!f||!g)return"other";const T=await ju(w);if(S!==v||d?.value.trim()!==w)return"stale";if(T.kind!=="project_share_invite")return"other";const N=(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 ${N||"selected projects"}.`),f.value=T.recipient_name??"",g.value=T.device_name??"",u.hidden=!1,h=w,l&&(l.textContent="Accept and start syncing"),m?.focus(),"project"};d?.addEventListener("input",()=>{v+=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?go(o):T=ri(o,"Team name is required."),!S||S<1?T=ri(s,"Must be at least 1 hour."):go(s),!!T){i.disabled=!0,i.textContent="Creating…";try{const N=await $u({group_id:w,policy:zt.invitePolicy,ttl_hours:S||24});_.lastTeamInvite=N,cu(),c.value=String(N.encoded||""),c.hidden=!1,c.focus(),c.select();const P=Array.isArray(N.warnings)?N.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(N){ne(et(N,"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=>{Dr(w,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d)return;const w=d.value.trim();if(!w){ri(d,"Paste a team invite or pairing payload.");return}if(go(d),h!==w){const T=v;try{const N=await b(w,T);if(N==="project"||N==="stale")return}catch{}if(T!==v||d.value.trim()!==w)return;h=w,l.textContent="Accept invite";return}const S=u&&!u.hidden?{recipient_name:f?.value.trim()??"",device_name:g?.value.trim()??""}:void 0;if(S){const T=N=>!N||[...N].length>120||[...N].some(P=>/[\p{Cc}\p{Cf}]/u.test(P));if(T(S.recipient_name)){f&&ri(f,"Enter a valid name using 120 characters or fewer.");return}if(T(S.device_name)){g&&ri(g,"Enter a valid device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const T=await Bs(w,S);_.lastTeamJoin=T;const N=T,P=typeof N.type=="string"?N.type:"team_join";let A;if(P==="pair"){const M=String(T.peer_device_id??"").trim();A={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=N.restart_required===!0||N.setup_state==="pending_inviter"||T.status==="pending_setup",U=typeof N.detail=="string"?N.detail.trim():"";A=M?{message:U||(N.restart_required===!0?"Project invitation accepted. Restart codemem to finish setup.":N.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 A={message:T.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"};_.syncJoinFlowFeedback=A,Ts(),d.value="",h="",u&&(u.hidden=!0);try{await t()}catch(M){A={message:et(M,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},_.syncJoinFlowFeedback=A,Ts()}}catch(T){_.syncJoinFlowFeedback={message:et(T,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},Ts(),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=lb(await Hs());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 lu({element:e,hidden:t=!1,restoreParent:n=null}){const r=B(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 wM({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(lu,{element:e,hidden:!t,restoreParent:n}):null]})}function SM(){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=>Ai("codemem sync pair --payload-only",e.currentTarget),children:"Copy pairing command"})]})}function CM({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(lu,{element:e,hidden:!t,restoreParent:n}):null]})}function TM({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(lu,{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(CM,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:o,onToggle:c}),a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:a(wM,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?a(SM,{}):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 xs({children:e}){return a("div",{className:"section-meta sync-section-note",children:e})}function NM({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(gr,{feedback:o})]})}function xM({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(gr,{feedback:s})]})}function PM(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(xs,{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(NM,{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 EM({children:e}){return e?a(te,{children:[a(ks,{label:"Add devices & teammates"}),a(xs,{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&&!_.syncDiscoveredFeedback?null:en(a(te,{children:[a(ks,{count:t.length||void 0,label:"Devices waiting for review"}),a(xs,{children:"Review team devices here when they still need trust, re-pairing, or approval on this machine."}),a(gr,{feedback:_.syncDiscoveredFeedback}),t.map(o=>a(xM,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},o.deviceId))]}),e)}function IM({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!_.syncJoinRequestsFeedback?null:en(a(te,{children:[a(ks,{count:t.length||void 0,label:"Join requests to review"}),a(xs,{children:"Approve or deny requests here before those devices become part of the team."}),a(gr,{feedback:_.syncJoinRequestsFeedback}),t.map(i=>a(kM,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function Bb(e){return a(te,{children:[a(PM,{...e}),a(EM,{children:e.children}),a(IM,{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 Ub(e){e&&(e.textContent="")}function Ps(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 RM(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function vo(){return RM()?"auto":"smooth"}var du="syncTeamActionsMount";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=du,e.appendChild(n),Ze(n,y(Bb,{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 Gb(e,t){const n=document.getElementById(du);n&&(ei(n),n.remove()),Ub(e),t.forEach(r=>{Ub(r)})}function Es(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;su(),Ns(),cu(),Ts(),yM();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");Ln("syncTeamSkeleton"),bM();const p=_.lastSyncCoordinator,m=_.lastSyncViewModel||{primaryStatus:bb({status:_.lastSyncStatus,coordinator:p,peers:_.lastSyncPeers,shareOperations:_.lastShareOperations,shareOperationsLoadError:_.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]},f=E=>{if(E.kind==="possible-duplicate-person"){const H=document.getElementById("syncActorsList");H instanceof HTMLElement&&(H.scrollIntoView({block:"center",behavior:vo()}),Ps(H));return}const $=String(E.deviceId||"").trim();if(!$)return;if(E.kind==="name-device"){const H=document.querySelector(`[data-device-name-input="${CSS.escape($)}"]`);if(H instanceof HTMLInputElement){H.scrollIntoView({block:"center",behavior:vo()}),H.focus(),H.select(),Ps(H);return}}const L=document.querySelector(`[data-peer-device-id="${CSS.escape($)}"]`);if(L instanceof HTMLElement){L.scrollIntoView({block:"center",behavior:vo()}),Ps(L);return}const J=document.querySelector(`[data-discovered-device-id="${CSS.escape($)}"]`);J instanceof HTMLElement&&(J.scrollIntoView({block:"center",behavior:vo()}),Ps(J))},g=async E=>{const $=Array.isArray(E.actorIds)?E.actorIds.map(R=>String(R||"").trim()).filter(Boolean):[],L=(Array.isArray(_.lastSyncActors)?_.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 xP({title:"Review possible duplicate people",summary:E.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"){_$($,"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),k=L.find(R=>String(R?.actor_id||"")===J.secondaryActorId);if(!H?.actor_id||!k?.actor_id){ne("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await zu(String(H.actor_id),String(k.actor_id)),w$($),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 E=>await Rl({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:E,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:$=>$.trim()?null:"Enter a device name to pair this device."}),v=!!p?.configured,b=l$(p);e.title=v?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?DM(w,e,m.primaryStatus):e.textContent=m.primaryStatus.meta,!v){Gb(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(_.lastSyncPeers)?_.lastSyncPeers:[],N=Array.isArray(m.attentionItems)?m.attentionItems:[],P=(Array.isArray(p.discovered_devices)?p.discovered_devices:[]).map(E=>{const $=String(E.device_id||"").trim(),L=ub({coordinatorName:String(E.display_name||"").trim(),deviceId:$})||"Discovered device",J=$&&L!==$?$:null,H=String(E.fingerprint||"").trim(),k=(Array.isArray(E.groups)?E.groups.map(Q=>String(Q||"").trim()).filter(Boolean):[]).length>1,R=T.find(Q=>String(Q?.peer_device_id||"")===$),j=cb({device:E,pairedLocally:!!R}),V=String(R?.fingerprint||"").trim(),ge=!!R&&!!H&&!!V&&V!==H,le=!b&&AL({device:E,hasAmbiguousCoordinatorGroup:k,pairedLocally:!!R}),ce=Array.isArray(E.addresses)?E.addresses:[],be=Number(E.address_count??0),Y=Number.isFinite(be)&&be>0?be:0,fe=[ce.length?ce.map(Q=>Ri()?xb(String(Q||"")):String(Q||"")).filter(Boolean).join(" · "):Y>0?`${Y} ${E.stale?"last-known":"fresh"} ${Y===1?"address":"addresses"} hidden`:"No fresh addresses"];!ce.length&&J&&fe.push(`device id: ${$}`);let X=null,_e=le?"accept":"none",he=null;return ge?_e="conflict":b&&(!R||j.state==="needs-your-approval")?(X=b.message,_e="setup-blocked"):k?(X="This device appears in multiple coordinator groups. Review team setup first or ask an admin to clean up the duplicate enrollment before approving it here.",_e="ambiguous"):R&&zd($)?(X="Review this device's Space access and advanced rules in Teams before you sync it.",_e="scope-pending"):R?.last_error?(fe.push(`error: ${String(R.last_error)}`),le||(_e="paired")):R?.status?.peer_state?(fe.push(`status: ${String(R.status.peer_state)}`),le||(_e="paired")):!R&&E.stale?(X="Wait for a fresh coordinator presence update, then review this device again here.",_e="stale"):R&&!le&&(_e="paired"),_e==="paired"&&(he=j.state==="waiting-for-other-device"?j.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:X,actionLabel:j.actionLabel||(R?"Review device":"Pair with this device"),approvalBadgeLabel:j.badgeLabel,availabilityLabel:E.stale?"Offline":"Available",connectionLabel:ge?wb.conflicts:R?wb.pairedLocally:"Not connected on this device",deviceId:$,displayName:L,displayTitle:J,fingerprint:H,mode:_e,note:fe.join(" · "),pairedMessage:he}}),A=[],M=P.filter(E=>E.mode!=="paired"&&E.mode!=="none"&&E.mode!=="scope-pending"),U=P.filter(E=>E.mode==="accept"||E.mode==="scope-pending").length,x=N.length+A.length+U;l&&(l.hidden=M.length===0&&!_.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=A.length===0&&!_.syncJoinRequestsFeedback),Gb(n,[c,u]);const G=document.createElement("div");G.id=du,n.appendChild(G),Ze(G,y(Bb,{actionItems:N,actionableCount:x,children:y(TM,{invitePanel:r,invitePanelOpen:Kd,inviteRestoreParent:i,joinPanel:o,joinPanelOpen:qd,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(m$(!Kd),Es())},onToggleJoinPanel:()=>{o&&(f$(!qd),Es())},pairedPeerCount:Number(p.paired_peer_count||0),presenceStatus:S}),discoveredListMount:u,discoveredRows:M,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async E=>{if(E.kind==="possible-duplicate-person"){await g(E);return}f(E)},onDenyJoinRequest:async()=>null,onInspectConflict:E=>{const $=document.querySelector(`[data-peer-device-id="${CSS.escape(E.deviceId)}"]`);if($ instanceof HTMLElement){$.scrollIntoView({block:"center",behavior:vo()}),ne(`Opened the conflicting local device record for ${E.displayName}.`,"warning");return}ne("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async E=>{if(!await Kt({title:`Remove ${E.displayName}?`,description:"This deletes the broken local device record. You can review this device again after the screen refreshes.",confirmLabel:"Remove device record",cancelLabel:"Keep device record",tone:"danger"}))return null;try{await Fu(E.deviceId);const $={message:`Removed the broken local device record for ${E.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return _.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 E=>{try{const $=await h(E.displayName);if(!$)return null;const L=await nw(E.deviceId,E.fingerprint),J=String(L?.name||E.displayName||"").trim()||E.displayName;_.pendingAcceptedSyncPeers=[...Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(k=>String(k?.peer_device_id||"").trim()!==E.deviceId):[],{peer_device_id:E.deviceId,name:J,fingerprint:E.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],g$(E.deviceId);let H={message:E.approvalBadgeLabel==="Needs your approval"?`Approved ${E.displayName} on this device. Two-way trust should be ready once both devices refresh.`:`Step 1 complete on this device for ${E.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};try{$.trim()!==J.trim()&&(await Bu(E.deviceId,$.trim()),_.pendingAcceptedSyncPeers=_.pendingAcceptedSyncPeers.map(k=>String(k?.peer_device_id||"").trim()===E.deviceId?{...k,name:$.trim()}:k),H={message:`Connected ${$.trim()} and saved its name.`,tone:"success"})}catch(k){H={message:et(k,"Device connected, but naming did not finish."),tone:"warning"}}_.syncDiscoveredFeedback=H;try{await zt.loadSyncData()}catch(k){H={message:et(k,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},_.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:A,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 ii(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function Hb(e){return ii(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 Kb(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 qM({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],o=Object.fromEntries(r.map(k=>[k.workspaceIdentity,k.suggestedScopeId??""])),[s,c]=I({}),[l,d]=I({}),[u,p]=I(o),[m,f]=I({}),[g,h]=I("all"),[v,b]=I(""),[w,S]=I(null),T=r.length,N=e.totalGroupCount??T,P=r.filter(ii).length,A=r.filter(k=>k.suggestedScopeId&&!ii(k)&&Tt(k)).length,M=r.filter(k=>m[k.workspaceIdentity]&&Tt(k)).length,U=r.filter(k=>m[k.workspaceIdentity]&&Tt(k)&&!!u[k.workspaceIdentity]).length,x=r.filter(k=>{const R=ii(k);return g==="suggested"&&(!k.suggestedScopeId||R)||g==="cleanup"&&!R||g==="no-suggestion"&&(k.suggestedScopeId||R)||g==="selected"&&!m[k.workspaceIdentity]?!1:!v.trim()||HM(k,i).includes(v.trim().toLowerCase())});async function G(k){const R=u[k.workspaceIdentity]||k.suggestedScopeId||"";if(!(!R||!t||w)){S(k.workspaceIdentity),d(j=>{const V={...j};return delete V[k.workspaceIdentity],V});try{const j=await t(k,R,!!s[k.workspaceIdentity],s[k.workspaceIdentity]?.confirmation_token);c(j?V=>({...V,[k.workspaceIdentity]:j}):V=>{const ge={...V};return delete ge[k.workspaceIdentity],ge})}catch(j){d(V=>({...V,[k.workspaceIdentity]:Kb(j,R,i)}))}finally{S(null)}}}function E(k,R){p(j=>({...j,[k.workspaceIdentity]:R})),c(j=>{const V={...j};return delete V[k.workspaceIdentity],V}),d(j=>{const V={...j};return delete V[k.workspaceIdentity],V})}function $(k,R){f(j=>({...j,[k.workspaceIdentity]:R}))}function L(k){f(R=>({...R,...Object.fromEntries(x.filter(Tt).map(j=>[j.workspaceIdentity,k]))}))}function J(){f(k=>({...k,...Object.fromEntries(r.filter(R=>R.suggestedScopeId&&!ii(R)&&Tt(R)).map(R=>[R.workspaceIdentity,!0]))}))}async function H(){if(!t||w||U===0)return;const k=r.filter(R=>m[R.workspaceIdentity]&&Tt(R)&&!!u[R.workspaceIdentity]);if(!k.every(R=>s[R.workspaceIdentity])){S("bulk");try{for(const R of k){if(s[R.workspaceIdentity])continue;const j=u[R.workspaceIdentity]||R.suggestedScopeId||"";if(j)try{const V=await t(R,j,!1);d(ge=>{const le={...ge};return delete le[R.workspaceIdentity],le}),V&&c(ge=>({...ge,[R.workspaceIdentity]:V}))}catch(V){d(ge=>({...ge,[R.workspaceIdentity]:Kb(V,j,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:[N.toLocaleString()," older"," ",N===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",T<N?` 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 ${A.toLocaleString()}`],["cleanup",`Needs cleanup ${P.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${U.toLocaleString()}`]].map(([k,R])=>a("button",{className:g===k?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>h(k),type:"button",children:R},k))}),a("div",{className:"legacy-review-bulk-row",children:[a("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:k=>b(k.currentTarget.value),placeholder:"Search project, signal, or destination…",value:v}),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(k=>m[k.workspaceIdentity]&&Tt(k)&&!!u[k.workspaceIdentity]).every(k=>s[k.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(k=>m[k.workspaceIdentity]&&Tt(k)&&!!u[k.workspaceIdentity]).every(k=>s[k.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:x.map(k=>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 ${Hb(k)}`,checked:!!m[k.workspaceIdentity],className:"cm-checkbox",disabled:!Tt(k),onChange:R=>$(k,R.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:Hb(k)}),a("div",{className:"legacy-review-group-meta",children:[$M(k.identitySource),MM(k,i)]}),Tt(k)?k.peerOwnedMemoryCount?a("div",{className:"legacy-review-cleanup-note",children:[(k.reassignableMemoryCount??k.memoryCount).toLocaleString()," ","local memor",(k.reassignableMemoryCount??k.memoryCount)===1?"y":"ies"," ","can be reassigned; ",k.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",k.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."}),ii(k)?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:[k.memoryCount.toLocaleString()," memor",k.memoryCount===1?"y":"ies"]})]}),k.suggestionReason?a("div",{className:"legacy-review-reason",children:k.suggestionReason}):null,l[k.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:l[k.workspaceIdentity]}):null,s[k.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:[s[k.workspaceIdentity].warning," This will reassign"," ",s[k.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[k.workspaceIdentity].memory_count.toLocaleString()," memories",s[k.workspaceIdentity].skipped_memory_count?`; ${s[k.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,a(GM,{group:k}),i.length>0&&t&&Tt(k)?a("label",{className:"legacy-review-target",children:[a("span",{children:"Destination Space"}),a("select",{className:"peer-scope-input",disabled:w!=null,onChange:R=>E(k,R.currentTarget.value),value:u[k.workspaceIdentity]||"",children:[a("option",{value:"",children:"Choose Space…"}),i.map(R=>a("option",{value:R.scopeId,children:[R.label," · ",FM(R.authorityType),R.scopeId===k.suggestedScopeId?" · suggested":""]},R.scopeId))]})]}):null,i.length>0&&t&&Tt(k)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:w!=null||!u[k.workspaceIdentity],onClick:()=>{G(k)},children:w===k.workspaceIdentity?s[k.workspaceIdentity]?"Reassigning…":"Previewing…":s[k.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},k.workspaceIdentity))}):null]})}function VM({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(te,{children:[t?a(qM,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(KM,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function WM(){Pf("mine"),_.feedQuery="",window.location.hash="feed"}function zM(){window.location.hash="projects"}async function JM(e,t,n,r){try{const i=await _w({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return _.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}.`),qb(),null}catch(i){if(i instanceof Gu)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw ne(o,"warning"),new Error(o)}}function qb(){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(_.lastSyncSharingReview)?_.lastSyncSharingReview:[],o=_.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){ei(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=_.currentProject?`current project (${_.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(VM,{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:WM}))}var As="",yo=null,uu=0,YM=15e3;function Vb(e){return`project:${e||""}|includeJoinRequests:false`}function XM(e){const t=Vb(e);return!yo||yo.key!==t||Date.now()>=yo.expiresAtMs?null:yo.payload}function QM(e,t){yo={key:Vb(e),expiresAtMs:Date.now()+YM,payload:t}}function ZM(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 oi(){const e=++uu;try{const t=_.currentProject||"",n=!1,r=_.activeTab==="health";let i=!1;const o=!Ri();let s;r?(s=XM(t),s||(s=await Fs(o,t,{includeJoinRequests:!1}),i=!0)):(s=await Fs(o,t,{includeJoinRequests:n}),i=!0);let c=null,l=null,d=_.lastShareOperations,u=!1,p=!1,m=!1;const f=b$();try{c=await Z_()}catch{u=!0}try{l=await No()}catch{p=!0}try{const S=await Wu();d=Array.isArray(S.items)?S.items:[]}catch{m=!0}if(e!==uu)return;i&&QM(t,ZM(s));const g=JSON.stringify([s,c,l,d,m,f]);if(g===As)return;As=g;const h=s.status&&typeof s.status=="object"?s.status:null;h&&(_.lastSyncStatus=h),Array.isArray(c?.items)?_.lastSyncActors=c.items:_.lastSyncActors=[];const v=Array.isArray(s.peers)?s.peers:[],b=new Set(v.map(S=>String(S?.peer_device_id||"").trim()).filter(Boolean)),w=Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(S=>{const T=String(S?.peer_device_id||"").trim();return T&&!b.has(T)}):[];_.pendingAcceptedSyncPeers=w,_.lastSyncPeers=[...v,...w],_.lastShareOperations=d,_.shareOperationsLoadError=m,_.lastSyncSharingReview=s.sharing_review||[],_.lastSyncLegacySharedReview=s.legacy_shared_review&&typeof s.legacy_shared_review=="object"?s.legacy_shared_review:null,_.lastSyncCoordinator=s.coordinator||null,_.lastCoordinatorAdminStatus=l&&typeof l=="object"?l:null,_.lastSyncJoinRequests=Array.isArray(s.join_requests)?s.join_requests:[],_.lastSyncAttempts=s.attempts||[],_.lastSyncLegacyDevices=s.legacy_devices||[],_.lastSyncDuplicatePersonDecisions=f,_.lastSyncViewModel=u$({actors:_.lastSyncActors,peers:_.lastSyncPeers,coordinator:_.lastSyncCoordinator,status:h,shareOperations:_.lastShareOperations,shareOperationsLoadError:m,reconciliation:s.recipient_policy_reconciliation,duplicatePersonDecisions:_.lastSyncDuplicatePersonDecisions}),Rb(),Es(),lM(),uM(),qb(),ou(),jb(),Ib(),Py(),u&&dM(),p&&(_.lastCoordinatorAdminStatus=null,Es())}catch{if(e!==uu)return;As="",Ln("syncTeamSkeleton"),Ln("syncActorsSkeleton"),Ln("syncPeersSkeleton"),Ln("syncDiagSkeleton"),eO(),pM(),x$()}}function tO(){As="",_.lastSyncPeers?.length&&ou()}async function nO(){try{_.pairingPayloadRaw=await ew()||null,Zd()}catch{_.pairingPayloadRaw=null,Zd()}}function rO(e){cL(),Ba(),gM(oi),cM(oi),I$(ou),_M(e,oi),mM(oi),R$(e),au(),hM()}function iO(e,t){const n=Ie("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 z_();if(!e?.version)return;iO(e.version,"c0e1417")}catch{}}var pu=null,Wb=1500,zb="codemem-legacy-upgrade-notice-dismissed",$n=null,Jt=!1,mu=!1,bo=null;function Jb(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function Yb(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=Jb(n.total_group_count,r.length),o=Jb(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function Xb(){try{return localStorage.getItem(zb)==="1"}catch{return!1}}function Is(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(zb,"1")}catch{}}function Qb(){const e=Ie("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=Ie("legacyUpgradeReviewGroups");(t&&e.includes(t)?t:e[0])?.focus()}function Zb(e){const t=Ie("legacyUpgradeModal");if(!t||t.hidden)return;if(e.key==="Escape"){e.preventDefault(),Is(),_o(!1);return}if(e.key==="Enter"){const o=Ie("legacyUpgradeReviewGroups");Dr(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 e_(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 _o(e,t){const n=Ie("legacyUpgradeModalBackdrop"),r=Ie("legacyUpgradeModal"),i=Ie("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){bo=document.activeElement,document.addEventListener("keydown",Zb),aO(),e_(!0);return}e_(!1),document.removeEventListener("keydown",Zb),bo&&document.contains(bo)&&bo.focus(),bo=null}}function t_(e){!e||mu||Xb()||(mu=!0,_o(!0,e))}async function sO(){if(!(mu||Xb()))try{t_(Yb(await Fs(!1,"",{includeJoinRequests:!1})))}catch{}}function vr(e,t){const n=Ie("viewerReconnectOverlay"),r=Ie("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.")}async function fu(){try{return await W_(),!0}catch{return!1}}function cO(){return document.visibilityState!=="hidden"&&!Qy()}function n_(){if(Jt)return;Jt=!0,hu(),yr("error","(reconnecting)"),vr(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await fu()){if($n&&(clearTimeout($n),$n=null),Jt=!1,vr(!0,"Viewer responded. Restoring your session…"),cO()){yr("refreshing"),wo();try{await Ds()}catch{}}else yr("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");Jt||vr(!1);return}vr(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),$n=setTimeout(e,Wb)};$n=setTimeout(e,Wb)}function yr(e,t){_.refreshState=e;const n=Ie("refreshStatus");if(!n)return;const r=o=>{const s=Ie("refreshAnnouncer");!s||pu===e||(s.textContent=o,pu=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}`,pu=null}function hu(){_.refreshTimer&&(clearInterval(_.refreshTimer),_.refreshTimer=null)}function wo(){_.refreshTimer||(_.refreshTimer=setInterval(()=>Mn(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(hu(),yr("paused","(tab hidden)")):!Qy()&&!Jt&&(wo(),Mn())});function lO(){const e=_.advancedSection==="sync",t=Ie("advancedSyncContent"),n=Ie("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=Ie("advancedSyncButton"),i=Ie("advancedTeamsButton");r?.setAttribute("aria-pressed",String(e)),i?.setAttribute("aria-pressed",String(!e)),queueMicrotask(()=>{const o=window.location.hash.replace(/^#/,"");au(o==="sync/diagnostics"||o==="advanced/sync/diagnostics"?"diagnostics":"main")})}function r_(e){const t=new Set(iN(_.lastCoordinatorAdminStatus));Jn.forEach(n=>{const r=Ie(`tab-${n}`);r&&(r.hidden=n!==e||!t.has(n))}),Jn.forEach(n=>{const r=Ie(`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 Rs(e,t={}){const n=Ii(e,_.lastCoordinatorAdminStatus);n==="advanced"&&Kc(t.advancedSection??Hc()??_.advancedSection),xf(n,t.canonicalHash?{canonicalHash:!0}:{}),r_(n),Mn()}function dO(){Jn.forEach(e=>{Ie(`tabBtn-${e}`)?.addEventListener("click",()=>Rs(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Ie("advancedSyncButton")?.addEventListener("click",()=>Kc("sync",!0)),Ie("advancedTeamsButton")?.addEventListener("click",()=>Kc("teams",!0)),window.addEventListener("hashchange",()=>{const e=Gc();if(e){const t=Hc();Rs(e,t?{advancedSection:t}:{})}}),Rs(_.activeTab)}async function uO(){try{const e=await ko();_.knownProjects=e,tO();const t=Fc("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=cT(),i_={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},o_=!1,ai=null;async function mO(){const e=[];let t=0;for(;;){const n=await Po({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return ea(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 _.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"offline":"available");for(const r of _.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),o=ho(r);n(i,o==="connected"||o==="available"?"available":o==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function a_(e){Rs(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}async function hO(){const e=document.getElementById("devicesMount");if(!e)return!0;o_||Ga(e,i_,{version:1,items:[]},[],[],{loading:!0});try{const[t,n,r]=await Promise.all([mO(),Gs(),rw(),oi()]),i=fO();return Ga(e,n,r,t,i,{onNavigate:a_}),ai={projects:t,intent:n,reconciliation:r,availability:i},o_=!0,!0}catch{return ai?Ga(e,ai.intent,ai.reconciliation,ai.projects,ai.availability,{onNavigate:a_,refreshError:!0}):Ga(e,i_,{version:1,items:[]},[],[],{loadError:!0}),!1}}Fc("projectFilter")?.addEventListener("change",()=>{_.currentProject=Fc("projectFilter")?.value||"",co(!0),Mn()});var gu=null;async function Mn(){Jt||(gu&&clearTimeout(gu),gu=setTimeout(()=>Ds(),80))}async function Ds(){if(!Jt){if(_.refreshInFlight){_.refreshQueued=!0;return}_.refreshInFlight=!0;try{yr("refreshing");const e=_.activeTab,t=[y0(),ED()];let n=!0;e==="feed"&&t.push(No().then(i=>{_.lastCoordinatorAdminStatus=i&&typeof i=="object"?i:null}).catch(()=>{_.lastCoordinatorAdminStatus=null})),e==="feed"&&t.push(Ty()),e==="projects"&&t.push(zy()),e==="sharing"&&t.push(pO()),e==="devices"&&t.push(hO().then(i=>{n=i})),(e==="advanced"&&_.advancedSection==="sync"||e==="health")&&t.push(oi()),e==="advanced"&&_.advancedSection==="teams"&&t.push(Ml()),_.syncPairingOpen&&t.push(nO()),await Promise.all(t),t_(Yb(_.lastSyncLegacySharedReview));const r=Ii(_.activeTab,_.lastCoordinatorAdminStatus);r!==_.activeTab&&xf(r),r_(_.activeTab),yr(n?"idle":"error")}catch{await fu()?yr("error"):n_()}finally{_.refreshInFlight=!1,_.refreshQueued&&!Jt&&(_.refreshQueued=!1,Ds())}}}mN();var s_=document.getElementById("toastRoot");s_&&zT(s_),fN(Bc("themeToggle")),If(Vc()),dO(),l0(),Z0(()=>Mn()),rO(()=>Mn()),nE(),aL(hu,wo,()=>Mn()),uO(),Ie("viewerReconnectRetry")?.addEventListener("click",async()=>{if(vr(!0,"Checking whether the viewer server is back…"),!await fu()){n_();return}$n&&(clearTimeout($n),$n=null),Jt=!1,vr(!0,"Viewer responded. Restoring your session…"),wo();try{await Ds()}catch{}Jt||vr(!1)}),Ie("legacyUpgradeReviewGroups")?.addEventListener("click",()=>{Is(),_o(!1),window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)}),Ie("legacyUpgradeReviewProjects")?.addEventListener("click",()=>{Is(),_o(!1),window.location.hash="projects"}),Ie("legacyUpgradeNotNow")?.addEventListener("click",()=>{Is(),_o(!1)}),oO(),sO(),Mn(),wo()})();
|