@popmelt.com/core 0.30.0 → 0.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,7 +22,7 @@ ${t}`,[o,i]=A({linked:!1,error:"",key:""});return D(()=>{if(i({linked:!1,error:"
22
22
  [data-popmelt-session-connection] .lucide-loader-circle { animation: popmelt-connection-spin .8s linear infinite; }
23
23
  [data-popmelt-session-connection] > svg { flex-shrink: 0; }
24
24
  @media (prefers-reduced-motion: reduce) { [data-popmelt-session-connection] .lucide-loader-circle { animation: none; } }
25
- `}),y("button",{"data-popmelt-session-connection":!0,type:"button",disabled:v,title:_,"aria-label":`${F}. ${_}`,"aria-busy":v,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),onFocus:()=>h(!0),onBlur:()=>h(!1),onClick:()=>{de()},style:{...pn(Ee[e],$),cursor:v?"default":"pointer",minWidth:0,maxWidth:"100%"},children:[v||n&&!$?l(Xn,{size:14,strokeWidth:1.5,"aria-hidden":"true"}):$||S?l(Co,{size:14,strokeWidth:1.5,"aria-hidden":"true"}):l(da,{size:14,strokeWidth:1.5,"aria-hidden":"true"}),y("span",{style:{display:"inline-grid",textAlign:"left",whiteSpace:"nowrap",position:"relative",minWidth:0},children:[L.map(he=>l("span",{"aria-hidden":"true",style:{gridArea:"1 / 1",visibility:"hidden",pointerEvents:"none",overflow:"hidden"},children:he},he)),l("span",{"data-popmelt-connection-label":!0,title:F,style:{position:"absolute",inset:0,overflow:"hidden",textOverflow:"ellipsis"},children:F})]})]})]})}function $n(e){return e<=767}function fn(e){return $n(e)?8:16}function wt(e){let t=fn(e);return e<=480?Math.max(0,e-t*2):Math.min(360,Math.max(0,e-t*2))}var mn=16,Ke=40,Pt=8,ba="popmelt-toolbar-snap-position";function hn(e){return e.startsWith("top-")}function An(e){return e.endsWith("-right")}function Yn(e){return e.endsWith("-center")}function va(){try{let e=localStorage.getItem(ba);if(e&&Wc(e))return e}catch{}return"bottom-right"}function xa(e){try{localStorage.setItem(ba,e)}catch{}}function Wc(e){return["bottom-right","bottom-center","bottom-left","top-right","top-center","top-left"].includes(e)}function Bc(e,t,n){let r=$n(t),o=fn(t),i=hn(e)?r?`max(${o}px, env(safe-area-inset-top))`:o:r?"auto":n-o-Ke,a=!hn(e)&&r?`max(${o}px, env(safe-area-inset-bottom))`:void 0;return Yn(e)?{position:"fixed",top:i,bottom:a,left:"50%",transform:"translateX(-50%)"}:An(e)?{position:"fixed",top:i,bottom:a,right:r?`max(${o}px, env(safe-area-inset-right))`:o,left:"auto"}:{position:"fixed",top:i,bottom:a,left:r?`max(${o}px, env(safe-area-inset-left))`:o,right:"auto"}}function Wt(e,t,n,r=12){let o=hn(e),i=$n(t),a=fn(t),s=o?{top:i?`calc(max(${a}px, env(safe-area-inset-top)) + ${Ke+r}px)`:a+Ke+r}:{bottom:i?`calc(max(${a}px, env(safe-area-inset-bottom)) + ${Ke+r}px)`:a+Ke+r},d;return Yn(e)?d={left:"50%",transform:"translateX(-50%)"}:An(e)?d={right:i?`max(${a}px, env(safe-area-inset-right))`:a}:d={left:i?`max(${a}px, env(safe-area-inset-left))`:a},{position:"fixed",...s,...d}}function Dc(e,t,n){let r=hn(e),o=$n(t),i=fn(t),a=r?{top:o?`calc(max(${i}px, env(safe-area-inset-top)) + ${Ke+8}px)`:i+Ke+8}:{bottom:o?`calc(max(${i}px, env(safe-area-inset-bottom)) + ${Ke+8}px)`:i+Ke+8},s,d;return Yn(e)?(s={left:"50%",transform:"translateX(-50%)"},d="center"):An(e)?(s={right:o?`max(${i}px, env(safe-area-inset-right))`:i},d="flex-end"):(s={left:o?`max(${i}px, env(safe-area-inset-left))`:i},d="flex-start"),{position:"fixed",...a,...s,zIndex:9999,display:"flex",flexDirection:"column",alignItems:d}}function Fc(e,t=typeof window<"u"?window.innerWidth:1920){let n=hn(e),r=An(e)||Yn(e),o=$n(t),i=fn(t),a=n&&r?i+Ke+Pt:i,s=!n&&r?i+Ke+Pt:i;return{position:"fixed",top:o?`max(${a}px, env(safe-area-inset-top))`:a,right:o?`max(${i}px, env(safe-area-inset-right))`:i,bottom:o?`max(${s}px, env(safe-area-inset-bottom))`:s,width:wt(t)}}function Vc(e,t,n){let r=wt(t),o=fn(t),i=hn(e),a,s;An(e)||Yn(e)?(a=t-o,s=a-r):(s=o,a=s+r);let d=i?o+Ke+Pt:n-o-Ke-Pt;return{left:s,right:a,y:d}}var Qc=["top-left","top-center","top-right","bottom-left","bottom-center","bottom-right"],wa=100,St=200,Mr={surface:null,phase:"visible"};function So({openDelayMs:e=wa,exitDurationMs:t=St,pinnedSurface:n=null}={}){let[r,o]=A(Mr),i=M(Mr),a=M(null),s=M(n);s.current=n;let d=M(null),c=M(null),u=ie(w=>{i.current.surface===w.surface&&i.current.phase===w.phase||(i.current=w,o(w))},[]),p=ie(()=>{d.current&&(clearTimeout(d.current),d.current=null)},[]),m=ie(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),h=ie(w=>{a.current=w,p(),m(),u({surface:w,phase:"visible"})},[m,p,u]),v=ie(w=>{if(!(s.current&&i.current.surface===s.current&&w!==s.current)){if(a.current=w,p(),m(),i.current.surface!==null){u({surface:w,phase:"visible"});return}d.current=setTimeout(()=>{d.current=null,a.current===w&&u({surface:w,phase:"visible"})},e)}},[m,p,e,u]),x=ie(w=>{w!==s.current&&(a.current===w&&(a.current=null),p(),i.current.surface===w&&(m(),u({surface:w,phase:"exiting"}),c.current=setTimeout(()=>{c.current=null,a.current===null&&u(Mr)},t)))},[m,p,t,u]),T=ie(w=>{w&&i.current.surface!==w||(a.current=null,p(),m(),u(Mr))},[m,p,u]);return Ze(()=>{n&&i.current.surface===n&&h(n)},[n,h]),D(()=>()=>{p(),m()},[m,p]),{surface:r.surface,phase:r.phase,enter:v,leave:x,show:h,dismiss:T}}var _c={version:"0.30.0"},Ca=_c.version;function Io({theme:e,expanded:t,width:n,snapPosition:r,viewport:o,toolbarRef:i,style:a,...s}){let d=Ee[e];return l("div",{...s,ref:i,id:"devtools-toolbar",role:"toolbar","data-popmelt-theme":e,style:{...Bc(r,o.w,o.h),zIndex:9999,display:"flex",alignItems:"center",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",cursor:"pointer",overflow:"visible",transition:"none",backgroundColor:d.surface,color:d.primary,colorScheme:e,boxSizing:"border-box",border:t?0:`1px solid ${d.border}`,boxShadow:t?`0 0 0 1px ${d.border}`:void 0,borderRadius:20,padding:t?"4px 8px 4px 4px":0,width:t?n:40,height:40,gap:t?6:0,justifyContent:t?"flex-start":"center",...a}})}function Mo({expanded:e,active:t=!1,color:n,onSettlingChange:r,...o}){return l("button",{type:"button",title:e?"Collapse (\u2318\u2318)":"Open Popmelt (\u2318\u2318)",...o,style:{display:"flex",alignItems:"center",justifyContent:"center",width:e?24:40,height:e?32:40,flexShrink:0,border:"none",background:"none",padding:0,cursor:"pointer"},children:l(pa,{"data-popmelt-logo":!0,active:t,onSettlingChange:r,width:"24",height:"24",viewBox:"0 0 40 40",fill:e||t?n:"none",stroke:e||t?"none":n,strokeWidth:"1",strokeLinejoin:"round",xmlns:"http://www.w3.org/2000/svg"})})}function ka({theme:e,active:t,busy:n,color:r,onSettlingChange:o,onOpen:i,onCrosshairHover:a,onMouseEnter:s,toolbarRef:d,...c}){let u=M(null);return D(()=>{let p=u.current;if(!p)return;let m=p.querySelector("[data-popmelt-logo]"),h=()=>{p.style.opacity="1",!n&&m&&(m.style.fill=Ee[e].primary,m.style.stroke="none")},v=()=>{p.style.opacity=n?"1":"0.2",!n&&m&&(m.style.fill="none",m.style.removeProperty("stroke"))};return p.addEventListener("mouseenter",h),p.addEventListener("mouseleave",v),()=>{p.removeEventListener("mouseenter",h),p.removeEventListener("mouseleave",v)}},[n,e]),l(Io,{...c,theme:e,expanded:!1,width:40,toolbarRef:p=>{u.current=p,typeof d=="function"?d(p):d&&(d.current=p)},onMouseEnter:s,style:{opacity:n?1:.2,...c.style},children:l(Mo,{expanded:!1,active:t,color:r,onSettlingChange:o,onClick:i,onMouseEnter:()=>a?.(!0),onMouseLeave:()=>a?.(!1)})})}function Sa(){let e=()=>typeof window>"u"?{w:1920,h:1080}:{w:window.visualViewport?.width??window.innerWidth,h:window.visualViewport?.height??window.innerHeight},[t,n]=A(e);return D(()=>{let r=()=>n(e());return window.addEventListener("resize",r),window.visualViewport?.addEventListener("resize",r),()=>{window.removeEventListener("resize",r),window.visualViewport?.removeEventListener("resize",r)}},[]),t}function Ia(e){let t=M(e);t.current=e,D(()=>{let n=0,r=0,o=a=>{if(a.key!=="Meta"&&a.key!=="Control"){r=0;return}let s=Date.now();r=s-n<wr.toolbar.toggleWindowMs?r+1:1,r>=2&&(t.current(),r=0),n=s},i=a=>{a.key!=="Meta"&&a.key!=="Control"&&(r=0)};return window.addEventListener("keydown",o),window.addEventListener("keyup",i),()=>{window.removeEventListener("keydown",o),window.removeEventListener("keyup",i)}},[])}var Zc=(e,t)=>({display:"flex",width:t,height:32,borderRadius:16,overflow:"hidden",background:Ee[e].control});function qc({theme:e,icon:t,menuOpen:n=!1,interactive:r=!0,primaryLabel:o="Cycle annotations",primaryCursor:i=!1,dotColor:a,onPrimary:s,onMenu:d}){let c=Ee[e];return y("div",{"data-popmelt-compact-tool-control":!0,style:{...Zc(e,46),pointerEvents:r?void 0:"none"},children:[y("button",{type:"button","aria-label":o,"aria-disabled":!r,tabIndex:r?void 0:-1,onClick:s,style:{width:26,height:32,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",padding:0,border:0,background:"transparent",color:c.primary,cursor:r&&i?"pointer":"default"},children:[t,a&&l("span",{"aria-hidden":"true",style:{position:"absolute",left:16,top:14,width:4,height:4,borderRadius:"50%",background:a,pointerEvents:"none"}})]}),l("button",{type:"button","aria-label":"Choose tool","aria-haspopup":"menu","aria-expanded":n,"aria-disabled":!r,tabIndex:r?void 0:-1,onClick:d,style:{width:20,height:32,display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",padding:"0 6px 0 2px",border:0,background:"transparent",color:c.mutedStrong,cursor:r?"pointer":"default"},children:l(wo,{size:12,strokeWidth:2,style:{transform:n?"rotate(180deg)":"rotate(0deg)",transition:"transform 120ms ease"}})})]})}function Jc({theme:e,themePreference:t=e,onThemePreferenceChange:n,action:r,logoOnly:o=!1,connection:i,panel:a,deemphasizeControls:s=!1,onCollapse:d,ariaLabel:c="Popmelt admission"}){let[u,p]=A(()=>!o),[m,h]=A(va),v=M(null),x=So(),{leave:T,dismiss:w}=x,S=x.surface!==null&&x.phase==="visible",H=Sa(),L=()=>{if(u){w(),d?.(),p(!1);return}p(!0),o&&x.show("popmelt-guide")};return Ia(L),D(()=>{let k=v.current;if(!k)return;let E=R=>{R.relatedTarget instanceof Node&&k.contains(R.relatedTarget)||T("popmelt-guide")};return k.addEventListener("pointerout",E),()=>k.removeEventListener("pointerout",E)},[u,T]),u?y("div",{ref:v,style:{display:"contents"},onKeyDown:k=>{k.key==="Escape"&&w()},onBlur:k=>{k.relatedTarget instanceof Node&&v.current?.contains(k.relatedTarget)||T("popmelt-guide")},children:[l("style",{children:`
25
+ `}),y("button",{"data-popmelt-session-connection":!0,type:"button",disabled:v,title:_,"aria-label":`${F}. ${_}`,"aria-busy":v,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),onFocus:()=>h(!0),onBlur:()=>h(!1),onClick:()=>{de()},style:{...pn(Ee[e],$),cursor:v?"default":"pointer",minWidth:0,maxWidth:"100%"},children:[v||n&&!$?l(Xn,{size:14,strokeWidth:1.5,"aria-hidden":"true"}):$||S?l(Co,{size:14,strokeWidth:1.5,"aria-hidden":"true"}):l(da,{size:14,strokeWidth:1.5,"aria-hidden":"true"}),y("span",{style:{display:"inline-grid",textAlign:"left",whiteSpace:"nowrap",position:"relative",minWidth:0},children:[L.map(he=>l("span",{"aria-hidden":"true",style:{gridArea:"1 / 1",visibility:"hidden",pointerEvents:"none",overflow:"hidden"},children:he},he)),l("span",{"data-popmelt-connection-label":!0,title:F,style:{position:"absolute",inset:0,overflow:"hidden",textOverflow:"ellipsis"},children:F})]})]})]})}function $n(e){return e<=767}function fn(e){return $n(e)?8:16}function wt(e){let t=fn(e);return e<=480?Math.max(0,e-t*2):Math.min(360,Math.max(0,e-t*2))}var mn=16,Ke=40,Pt=8,ba="popmelt-toolbar-snap-position";function hn(e){return e.startsWith("top-")}function An(e){return e.endsWith("-right")}function Yn(e){return e.endsWith("-center")}function va(){try{let e=localStorage.getItem(ba);if(e&&Wc(e))return e}catch{}return"bottom-right"}function xa(e){try{localStorage.setItem(ba,e)}catch{}}function Wc(e){return["bottom-right","bottom-center","bottom-left","top-right","top-center","top-left"].includes(e)}function Bc(e,t,n){let r=$n(t),o=fn(t),i=hn(e)?r?`max(${o}px, env(safe-area-inset-top))`:o:r?"auto":n-o-Ke,a=!hn(e)&&r?`max(${o}px, env(safe-area-inset-bottom))`:void 0;return Yn(e)?{position:"fixed",top:i,bottom:a,left:"50%",transform:"translateX(-50%)"}:An(e)?{position:"fixed",top:i,bottom:a,right:r?`max(${o}px, env(safe-area-inset-right))`:o,left:"auto"}:{position:"fixed",top:i,bottom:a,left:r?`max(${o}px, env(safe-area-inset-left))`:o,right:"auto"}}function Wt(e,t,n,r=12){let o=hn(e),i=$n(t),a=fn(t),s=o?{top:i?`calc(max(${a}px, env(safe-area-inset-top)) + ${Ke+r}px)`:a+Ke+r}:{bottom:i?`calc(max(${a}px, env(safe-area-inset-bottom)) + ${Ke+r}px)`:a+Ke+r},d;return Yn(e)?d={left:"50%",transform:"translateX(-50%)"}:An(e)?d={right:i?`max(${a}px, env(safe-area-inset-right))`:a}:d={left:i?`max(${a}px, env(safe-area-inset-left))`:a},{position:"fixed",...s,...d}}function Dc(e,t,n){let r=hn(e),o=$n(t),i=fn(t),a=r?{top:o?`calc(max(${i}px, env(safe-area-inset-top)) + ${Ke+8}px)`:i+Ke+8}:{bottom:o?`calc(max(${i}px, env(safe-area-inset-bottom)) + ${Ke+8}px)`:i+Ke+8},s,d;return Yn(e)?(s={left:"50%",transform:"translateX(-50%)"},d="center"):An(e)?(s={right:o?`max(${i}px, env(safe-area-inset-right))`:i},d="flex-end"):(s={left:o?`max(${i}px, env(safe-area-inset-left))`:i},d="flex-start"),{position:"fixed",...a,...s,zIndex:9999,display:"flex",flexDirection:"column",alignItems:d}}function Fc(e,t=typeof window<"u"?window.innerWidth:1920){let n=hn(e),r=An(e)||Yn(e),o=$n(t),i=fn(t),a=n&&r?i+Ke+Pt:i,s=!n&&r?i+Ke+Pt:i;return{position:"fixed",top:o?`max(${a}px, env(safe-area-inset-top))`:a,right:o?`max(${i}px, env(safe-area-inset-right))`:i,bottom:o?`max(${s}px, env(safe-area-inset-bottom))`:s,width:wt(t)}}function Vc(e,t,n){let r=wt(t),o=fn(t),i=hn(e),a,s;An(e)||Yn(e)?(a=t-o,s=a-r):(s=o,a=s+r);let d=i?o+Ke+Pt:n-o-Ke-Pt;return{left:s,right:a,y:d}}var Qc=["top-left","top-center","top-right","bottom-left","bottom-center","bottom-right"],wa=100,St=200,Mr={surface:null,phase:"visible"};function So({openDelayMs:e=wa,exitDurationMs:t=St,pinnedSurface:n=null}={}){let[r,o]=A(Mr),i=M(Mr),a=M(null),s=M(n);s.current=n;let d=M(null),c=M(null),u=ie(w=>{i.current.surface===w.surface&&i.current.phase===w.phase||(i.current=w,o(w))},[]),p=ie(()=>{d.current&&(clearTimeout(d.current),d.current=null)},[]),m=ie(()=>{c.current&&(clearTimeout(c.current),c.current=null)},[]),h=ie(w=>{a.current=w,p(),m(),u({surface:w,phase:"visible"})},[m,p,u]),v=ie(w=>{if(!(s.current&&i.current.surface===s.current&&w!==s.current)){if(a.current=w,p(),m(),i.current.surface!==null){u({surface:w,phase:"visible"});return}d.current=setTimeout(()=>{d.current=null,a.current===w&&u({surface:w,phase:"visible"})},e)}},[m,p,e,u]),x=ie(w=>{w!==s.current&&(a.current===w&&(a.current=null),p(),i.current.surface===w&&(m(),u({surface:w,phase:"exiting"}),c.current=setTimeout(()=>{c.current=null,a.current===null&&u(Mr)},t)))},[m,p,t,u]),T=ie(w=>{w&&i.current.surface!==w||(a.current=null,p(),m(),u(Mr))},[m,p,u]);return Ze(()=>{n&&i.current.surface===n&&h(n)},[n,h]),D(()=>()=>{p(),m()},[m,p]),{surface:r.surface,phase:r.phase,enter:v,leave:x,show:h,dismiss:T}}var _c={version:"0.30.1"},Ca=_c.version;function Io({theme:e,expanded:t,width:n,snapPosition:r,viewport:o,toolbarRef:i,style:a,...s}){let d=Ee[e];return l("div",{...s,ref:i,id:"devtools-toolbar",role:"toolbar","data-popmelt-theme":e,style:{...Bc(r,o.w,o.h),zIndex:9999,display:"flex",alignItems:"center",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",cursor:"pointer",overflow:"visible",transition:"none",backgroundColor:d.surface,color:d.primary,colorScheme:e,boxSizing:"border-box",border:t?0:`1px solid ${d.border}`,boxShadow:t?`0 0 0 1px ${d.border}`:void 0,borderRadius:20,padding:t?"4px 8px 4px 4px":0,width:t?n:40,height:40,gap:t?6:0,justifyContent:t?"flex-start":"center",...a}})}function Mo({expanded:e,active:t=!1,color:n,onSettlingChange:r,...o}){return l("button",{type:"button",title:e?"Collapse (\u2318\u2318)":"Open Popmelt (\u2318\u2318)",...o,style:{display:"flex",alignItems:"center",justifyContent:"center",width:e?24:40,height:e?32:40,flexShrink:0,border:"none",background:"none",padding:0,cursor:"pointer"},children:l(pa,{"data-popmelt-logo":!0,active:t,onSettlingChange:r,width:"24",height:"24",viewBox:"0 0 40 40",fill:e||t?n:"none",stroke:e||t?"none":n,strokeWidth:"1",strokeLinejoin:"round",xmlns:"http://www.w3.org/2000/svg"})})}function ka({theme:e,active:t,busy:n,color:r,onSettlingChange:o,onOpen:i,onCrosshairHover:a,onMouseEnter:s,toolbarRef:d,...c}){let u=M(null);return D(()=>{let p=u.current;if(!p)return;let m=p.querySelector("[data-popmelt-logo]"),h=()=>{p.style.opacity="1",!n&&m&&(m.style.fill=Ee[e].primary,m.style.stroke="none")},v=()=>{p.style.opacity=n?"1":"0.2",!n&&m&&(m.style.fill="none",m.style.removeProperty("stroke"))};return p.addEventListener("mouseenter",h),p.addEventListener("mouseleave",v),()=>{p.removeEventListener("mouseenter",h),p.removeEventListener("mouseleave",v)}},[n,e]),l(Io,{...c,theme:e,expanded:!1,width:40,toolbarRef:p=>{u.current=p,typeof d=="function"?d(p):d&&(d.current=p)},onMouseEnter:s,style:{opacity:n?1:.2,...c.style},children:l(Mo,{expanded:!1,active:t,color:r,onSettlingChange:o,onClick:i,onMouseEnter:()=>a?.(!0),onMouseLeave:()=>a?.(!1)})})}function Sa(){let e=()=>typeof window>"u"?{w:1920,h:1080}:{w:window.visualViewport?.width??window.innerWidth,h:window.visualViewport?.height??window.innerHeight},[t,n]=A(e);return D(()=>{let r=()=>n(e());return window.addEventListener("resize",r),window.visualViewport?.addEventListener("resize",r),()=>{window.removeEventListener("resize",r),window.visualViewport?.removeEventListener("resize",r)}},[]),t}function Ia(e){let t=M(e);t.current=e,D(()=>{let n=0,r=0,o=a=>{if(a.key!=="Meta"&&a.key!=="Control"){r=0;return}let s=Date.now();r=s-n<wr.toolbar.toggleWindowMs?r+1:1,r>=2&&(t.current(),r=0),n=s},i=a=>{a.key!=="Meta"&&a.key!=="Control"&&(r=0)};return window.addEventListener("keydown",o),window.addEventListener("keyup",i),()=>{window.removeEventListener("keydown",o),window.removeEventListener("keyup",i)}},[])}var Zc=(e,t)=>({display:"flex",width:t,height:32,borderRadius:16,overflow:"hidden",background:Ee[e].control});function qc({theme:e,icon:t,menuOpen:n=!1,interactive:r=!0,primaryLabel:o="Cycle annotations",primaryCursor:i=!1,dotColor:a,onPrimary:s,onMenu:d}){let c=Ee[e];return y("div",{"data-popmelt-compact-tool-control":!0,style:{...Zc(e,46),pointerEvents:r?void 0:"none"},children:[y("button",{type:"button","aria-label":o,"aria-disabled":!r,tabIndex:r?void 0:-1,onClick:s,style:{width:26,height:32,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",padding:0,border:0,background:"transparent",color:c.primary,cursor:r&&i?"pointer":"default"},children:[t,a&&l("span",{"aria-hidden":"true",style:{position:"absolute",left:16,top:14,width:4,height:4,borderRadius:"50%",background:a,pointerEvents:"none"}})]}),l("button",{type:"button","aria-label":"Choose tool","aria-haspopup":"menu","aria-expanded":n,"aria-disabled":!r,tabIndex:r?void 0:-1,onClick:d,style:{width:20,height:32,display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",padding:"0 6px 0 2px",border:0,background:"transparent",color:c.mutedStrong,cursor:r?"pointer":"default"},children:l(wo,{size:12,strokeWidth:2,style:{transform:n?"rotate(180deg)":"rotate(0deg)",transition:"transform 120ms ease"}})})]})}function Jc({theme:e,themePreference:t=e,onThemePreferenceChange:n,action:r,logoOnly:o=!1,connection:i,panel:a,deemphasizeControls:s=!1,onCollapse:d,ariaLabel:c="Popmelt admission"}){let[u,p]=A(()=>!o),[m,h]=A(va),v=M(null),x=So(),{leave:T,dismiss:w}=x,S=x.surface!==null&&x.phase==="visible",H=Sa(),L=()=>{if(u){w(),d?.(),p(!1);return}p(!0),o&&x.show("popmelt-guide")};return Ia(L),D(()=>{let k=v.current;if(!k)return;let E=R=>{R.relatedTarget instanceof Node&&k.contains(R.relatedTarget)||T("popmelt-guide")};return k.addEventListener("pointerout",E),()=>k.removeEventListener("pointerout",E)},[u,T]),u?y("div",{ref:v,style:{display:"contents"},onKeyDown:k=>{k.key==="Escape"&&w()},onBlur:k=>{k.relatedTarget instanceof Node&&v.current?.contains(k.relatedTarget)||T("popmelt-guide")},children:[l("style",{children:`
26
26
  [data-popmelt-entry-dimmed] [data-popmelt-entry-content],
27
27
  [data-popmelt-entry-dimmed] [data-popmelt-entry-control] > [data-popmelt-logo] {
28
28
  opacity: 1;
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{c as d}from"./chunk-4BEN6VQ7.mjs";import{A as p,b as c}from"./chunk-OFHBVUTT.mjs";import{e as f}from"./chunk-4V7SK3M6.mjs";async function S(t,e){let r=await f(t);if(!r||!e)return[];let n=await c(t,e);return n.length?(await Promise.all([r,...r.mountedStores].map(async i=>{try{let o=await d(i,t);if(!o)return[];let{endpoint:u,request:m}=o,s=[];for(let l of n){let a=await p(u,"/participants/read-canvas-receipt",{...m,method:"POST",body:JSON.stringify({receiptId:l})});a.response.ok&&s.push({storeId:i.storeId,receipt:a.body})}return s}catch{return[]}}))).flat():[]}export{S as a};
2
+ import{c as d}from"./chunk-GHBFZOHT.mjs";import{A as p,b as c}from"./chunk-PCP5ENOU.mjs";import{e as f}from"./chunk-4V7SK3M6.mjs";async function S(t,e){let r=await f(t);if(!r||!e)return[];let n=await c(t,e);return n.length?(await Promise.all([r,...r.mountedStores].map(async i=>{try{let o=await d(i,t);if(!o)return[];let{endpoint:u,request:m}=o,s=[];for(let l of n){let a=await p(u,"/participants/read-canvas-receipt",{...m,method:"POST",body:JSON.stringify({receiptId:l})});a.response.ok&&s.push({storeId:i.storeId,receipt:a.body})}return s}catch{return[]}}))).flat():[]}export{S as a};
@@ -1,7 +1,7 @@
1
1
  "use client";
2
- import{b as Xf,f as Oi,h as Kf,g as ms,a as dc,d as cc,c as uc}from"./chunk-3LBOX7HQ.mjs";import{a as Vf}from"./chunk-HTHUSDZT.mjs";import{M as il,vb as gs,Ua as pc,f as Gf,e as fc,tb as ys,a as Qf,xb as hc,yb as mc,wb as vs,c as Zf,jb as eh,kb as th,Ja as _i,ja as nh,Db as rh,Eb as gc,ia as oh,Kb as ih,Gb as ah,Hb as lh,Ib as sh,_a as dh,ka as ch,Da as uh,za as yc,ab as ph,ba as fh,ca as bs,da as hh,ea as mh,$a as gh,Fa as yh,ha as vh,ob as xs,nb as bh,mb as ws,Fb as xh,la as wh,Oa as vc,Ba as bc,Ma as xc,Na as Sh,La as wc,Ka as Ih,Ga as Ss,N as kh,Cb as Th,p as Sc,ya as Eh,b as Ch,ub as Ic,Ra as Ah,Qa as Mh,Ta as Rh,Pa as $h,Sa as Lh,Ca as Ph,D as jh,E as zh,l as Dh,ra as en,ua as Hh,xa as Nh,Ha as Oh,sa as kc,na as Fi,T as _h,ma as Fh,R as Tc,Y as Wh,fb as ci,Mb as Bh,Jb as Jh,eb as Ec,gb as Cc,Ab as qh,Bb as Uh,lb as Yh,hb as Xh,ib as Kh,Aa as Vh,Ea as Is,Q as Gh,C as Ac,F as Mc,L as Rc,K as $c,o as ui,G as Lc,J as Wi,P as Qh,va as ks,qa as Zh,pa as Ts,oa as Es,O as em,ga as tm,fa as nm,Ia as rm,ta as Pc,wa as jc,q as om,W as zc,U as Dc,V as Hc,X as im,Z as Nc,$ as Oc,aa as am,S as lm,zb as _c,m as Bi,A as Cs,r as pi,I as al,u as Fc,g as sm,_ as dm,t as ll,h as Wc,y as cm,j as Pr,v as As,s as Ia,i as Ms,k as um,z as pm,x as fm,H as Rs,w as Bc,n as Jc,B as hm}from"./chunk-2BVRVVHJ.mjs";import{h as mm,Ba as qc,R as Ji,ma as gm,N as ym,H as Uc,A as no,la as sl,ka as vm,P as bm,D as Yc,O as xm,da as Sn,Y as $s,aa as ar,fa as Ls,$ as ka,ha as wm,S as dl,ua as Xc,_ as ro,za as Sm,Aa as Kc,ta as Vc,J as Ps,v as Gc,u as Ta,r as cl,w as qi,Z as Qc,Q as Zc,I as Im,K as km,M as Tm,f as Em,ba as Cm,ca as Am,wa as Mm,va as eu,ya as Rm,xa as $m,sa as tu,z as nu,t as js,g as Lm,ea as zs,C as Pm,E as ru,G as jm,F as zm,ga as ou,ia as iu,B as Dm,s as ul,L as Hm,y as Ds,q as au,x as Nm}from"./chunk-ENGMQINZ.mjs";import{c as Om,a as lu,b as Ea}from"./chunk-JQHZFDY5.mjs";import{i as su,k as _m,m as Fm,h as du,g as Wm,a as pl,e as Bm,b as jr,d as Jm,f as it,c as qm}from"./chunk-MP7S5ALD.mjs";import{c as pn,a as Lo,i as vn,j as Ui,d as Um,e as Ym,b as cu,l as Xm,m as Km,k as Vm}from"./chunk-XOGBFVWI.mjs";import{a as Gm}from"./chunk-2P2NUZW7.mjs";import{d as Hs,i as Qm}from"./chunk-MZNY6VXR.mjs";import{a as Ns,h as uu,d as Zm,c as eg,g as Os,e as _s,b as tg}from"./chunk-2RRYBN2J.mjs";import{b as Yt,f as pu,d as fu,e as Fs,i as ng,j as Ca,l as hu,m as mu,r as rg,p as og,u as ig,t as ag,s as lg,k as sg,a as dg,c as cg}from"./chunk-CPOYMGYY.mjs";import{a as gu,b as ug}from"./chunk-EX63NVDN.mjs";import{d as pg,g as fg,m as hg,l as mg}from"./chunk-N2ZEZCHO.mjs";import{a as gg}from"./chunk-J3UIBBU2.mjs";import{b as yg}from"./chunk-6VXFTT5U.mjs";import{a as vg}from"./chunk-LVEMYZOA.mjs";import{d as bn,o as Aa,n as Yi,a as yu,i as vu,v as bu,u as xu,h as fl,k as bg,f as xg,c as Ws,m as wu,l as Bs}from"./chunk-HGW2U6PD.mjs";import{lazy as hl,memo as wg,useContext as zr,useState as P,Suspense as ml,Fragment as Sg,useRef as B,useEffect as O,useLayoutEffect as It,useCallback as J,useMemo as we,cloneElement as Ig,useSyncExternalStore as kg,useId as Tg}from"react";import{jsx as f,jsxs as M,Fragment as ut}from"react/jsx-runtime";import{Fingerprint as oo,Component as gl,Reply as Su,Ban as yl,Terminal as Eg,PenLine as Cg,ImageIcon as Ag,Plug as Mg,SquareMousePointer as Rg,ChevronRight as Js,ThumbsUp as $g,Clock as qs,ChevronDown as Xi,Check as fi,ChevronLeft as Lg,X as Us,Send as Iu,Lock as Pg,ArrowDown as jg,OctagonAlert as ku,MessageCircleQuestionMark as zg,TriangleAlert as Dg,Command as Tu,CornerDownLeft as Ys,EyeOff as Hg}from"lucide-react";import{createPortal as Eu}from"react-dom";function Cu(e,t){return e.store===void 0&&(e.store=t),e.store}function Ng(e,t){let n=e.listeners??(e.listeners=new Set);return n.add(t),()=>n.delete(t)}function Og(e,t,n){let r=n(Cu(e,t));e.store=r;for(let o of e.listeners??[])o();return r}var nt=globalThis.__POPMELT_BRIDGE_CONNECTION__??(globalThis.__POPMELT_BRIDGE_CONNECTION__={}),vl=nt.sourceId??(typeof localStorage<"u"?localStorage.getItem("popmelt-source-id"):null)??(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).slice(2));nt.sourceId=vl;try{typeof localStorage<"u"&&localStorage.setItem("popmelt-source-id",vl)}catch{}function Xs(){return vl}var bl={isConnected:!1,status:"disconnected",jobResponses:{},jobThinking:{},activeJobIds:[],activeJobThreads:{},currentResponse:"",currentThinking:"",events:[],activeJobId:null,lastCompletedJobId:null,lastResponseText:null,lastThreadId:null,lastErrorByJob:{},pendingQuestions:[],incrementalResolutions:[],capabilitiesVersion:0};nt.store??(nt.store={...bl}),nt.listeners??(nt.listeners=new Set);var Dr=nt.activeEs??null,xl=nt.activeBridgeUrl??null,io=null,Jn=nt.connectionGeneration??0,Ma=new Set,hi=new Map,Po={},wl=new Set,jo=new Map;function $n(e,t){if(!e)return!1;if(wl.has(e))return!0;if(Ma.has(e)){let r=hi.get(e);return r||(r=[],hi.set(e,r)),r.push({type:t.type??"",data:t}),!0}let n=Po[e];return n!==void 0&&typeof t.seq=="number"&&t.seq<=n}async function Au(e,t,n,r=new Map){let o=()=>n!==(nt.connectionGeneration??0);for(let l of t){if(o())return;jo.set(l,r.get(l)??jo.get(l)),Ma.add(l),hi.set(l,[])}let{mergeBackfillHistory:i,selectBackfillTerminalEvent:a}=await import("./bridge-recovery-3IQN3U6D.mjs");o()||await Promise.all(t.map(async l=>{try{let s=await hu(e,l,-1,{retryUnavailable:!0});if(o()||wl.has(l))return;let d=hi.get(l)??[];if(s){ft(u=>{let h={...u.jobResponses,[l]:s.accumulated.response},m={...u.jobThinking,[l]:s.accumulated.thinking},g=i(u.events,l,s.events);return{...u,jobResponses:h,jobThinking:m,currentResponse:l===u.activeJobId?s.accumulated.response:u.currentResponse,currentThinking:l===u.activeJobId?s.accumulated.thinking:u.currentThinking,events:g}}),Po[l]=s.currentSeq;let c=[...s.events].reverse().find(u=>u.type==="job_started"||u.type==="job_parked");c?.type==="job_parked"&&Ki("job_parked",c,l);let p=a(s.events,s.jobActive,r.get(l));p&&Ki(p.type,p,l);for(let u of d)typeof u.data.seq=="number"&&u.data.seq<=s.currentSeq||Ki(u.type,u.data,l)}else{let c=!1;for(let u of d)Ki(u.type,u.data,l),(u.type==="done"||u.type==="error")&&(c=!0);let p=r.get(l);!c&&p&&Ki(p.type,p,l)}jo.delete(l)}finally{o()||(Ma.delete(l),hi.delete(l))}}))}function Ki(e,t,n){if(e==="job_parked")ft(r=>{let o=r.activeJobIds.filter(i=>i!==n);return{...r,activeJobIds:o,activeJobId:o.at(-1)??null,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}});else if(e==="job_started")ft(r=>({...r,status:"streaming",activeJobId:n,activeJobIds:[...new Set([...r.activeJobIds,n])],activeJobThreads:typeof t.threadId=="string"?{...r.activeJobThreads,[n]:t.threadId}:r.activeJobThreads,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}));else if(e==="delta"){let r=t.text||"";ft(o=>({...o,jobResponses:{...o.jobResponses,[n]:(o.jobResponses[n]||"")+r},currentResponse:n===o.activeJobId?o.currentResponse+r:o.currentResponse,events:[...o.events,{type:"delta",data:t,timestamp:Date.now()}]}))}else if(e==="thinking"){let r=t.text||"";ft(o=>({...o,jobThinking:{...o.jobThinking,[n]:(o.jobThinking[n]||"")+r},currentThinking:n===o.activeJobId?o.currentThinking+r:o.currentThinking,events:[...o.events,{type:"thinking",data:t,timestamp:Date.now()}]}))}else if(e==="status")ft(r=>({...r,events:[...r.events,{type:"status",data:t,timestamp:Date.now()}]}));else if(e==="done")delete Po[n],ft(r=>{let o=r.activeJobIds.filter(d=>d!==n),i={...r.jobResponses},a={...r.jobThinking},l=i[n];delete i[n],delete a[n];let s=n===r.activeJobId?o.length>0?o[o.length-1]:null:r.activeJobId;return{...r,activeJobIds:o,activeJobId:s,jobResponses:i,jobThinking:a,lastCompletedJobId:n,lastResponseText:t.responseText||l||r.currentResponse||null,lastThreadId:t.threadId??null,...n===r.activeJobId?{currentResponse:s&&i[s]||"",currentThinking:s&&a[s]||""}:{},events:[...r.events,{type:"done",data:t,timestamp:Date.now()}]}});else if(e==="error"){delete Po[n];let r=t.message??"";ft(o=>{let i=o.activeJobIds.filter(l=>l!==n),a=i.length>0?o.status:"error";return{...o,status:a,activeJobIds:i,lastCompletedJobId:n,lastErrorByJob:r?{...o.lastErrorByJob,[n]:r}:o.lastErrorByJob,events:[...o.events,{type:"error",data:t,timestamp:Date.now()}]}})}else ft(e==="question"?r=>{let o=typeof t.threadId=="string"?t.threadId:"",i=typeof t.question=="string"?t.question:"",a=Array.isArray(t.annotationIds)?t.annotationIds.filter(s=>typeof s=="string"):void 0,l=r.pendingQuestions.some(s=>s.jobId===n);return{...r,pendingQuestions:i&&o&&!l?[...r.pendingQuestions,{jobId:n,threadId:o,question:i,annotationIds:a,timestamp:Date.now()}]:r.pendingQuestions,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}}:r=>({...r,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}))}var qn=nt.discoveredBridgeUrl??null,Ln=nt.discoveredBridgeProjectId??null,zo=null,Vi=null;function Mu(e,t=!1){let n=e??null;if(!(!t&&(nt.expectedProjectId??null)===n)){Dr&&(Dr.close(),Dr=null,nt.activeEs=null),io&&(clearTimeout(io),io=null),xl=null,nt.activeBridgeUrl=null,qn=null,Ln=null,nt.discoveredBridgeUrl=null,nt.discoveredBridgeProjectId=null,zo=null,Vi=null,Ma.clear(),hi.clear(),wl.clear(),jo.clear();for(let r of Object.keys(Po))delete Po[r];nt.expectedProjectId=n,Jn=(nt.connectionGeneration??Jn)+1,nt.connectionGeneration=Jn,ft(()=>({...bl}))}}function _g(){nt.listeners?.size||Mu(null,!0)}async function Ru(e,t){if(qn&&(t?Ln===t:!Ln))return qn;if(!t&&Ln&&(qn=null,Ln=null,nt.discoveredBridgeUrl=qn,nt.discoveredBridgeProjectId=Ln),t&&Ln&&Ln!==t&&(qn=null,Ln=null,nt.discoveredBridgeUrl=qn,nt.discoveredBridgeProjectId=Ln),zo&&Vi===(t??null))return zo;let n=Jn;return Vi=t??null,zo=sg(e,t).then(r=>n!==Jn?null:(qn=r?.url??null,Ln=r?.projectId??t??null,nt.discoveredBridgeUrl=qn,nt.discoveredBridgeProjectId=Ln,zo=null,Vi=null,qn)).catch(()=>(n!==Jn||(zo=null,Vi=null),null)),zo}function Fg(){return qn}async function Wg(e,t){qn=null,Ln=null,nt.discoveredBridgeUrl=null,nt.discoveredBridgeProjectId=null,zo=null,Vi=null;let n=Jn,r=await Ru(e,t);return r&&n===Jn&&Ks(r),r}function Ra(){return Cu(nt,{...bl})}function Bg(e){return Ng(nt,e)}function ft(e){Og(nt,{...bl},t=>{let n=e(t),r=new Set(n.activeJobIds),o=n.activeJobId&&r.has(n.activeJobId)?n.activeJobId:n.activeJobIds.at(-1)??null;return{...n,activeJobId:o,activeJobThreads:Object.keys(n.activeJobThreads).some(i=>!r.has(i))?Object.fromEntries(Object.entries(n.activeJobThreads).filter(([i])=>r.has(i))):n.activeJobThreads,status:n.status==="streaming"&&r.size===0?"idle":n.status}})}function Jg(){return typeof window<"u"?window.__POPMELT_PROJECT_ID__??null:null}function Ks(e){if(Dr&&Dr.readyState!==EventSource.CLOSED&&xl===e)return;Dr&&(Dr.close(),Dr=null,nt.activeEs=null),io&&(clearTimeout(io),io=null),xl=e,nt.activeBridgeUrl=xl,Jn=(nt.connectionGeneration??Jn)+1;let t=Jn;nt.connectionGeneration=Jn;let n=new URLSearchParams({sourceId:vl}),r=Jg();r&&n.set("projectId",r);let o=dg(`${e}/events?${n.toString()}`);Dr=o,nt.activeEs=Dr;let i=!1,a=()=>t!==(nt.connectionGeneration??0),l=()=>i||a();Ma.clear(),hi.clear();let s=5e3,d=()=>{a()||io||(io=setTimeout(()=>{io=null,!a()&&Ca(e).then(p=>{a()||(p&&(!r||p.projectId===r)?Ks(e):(s=Math.min(s*2,3e4),d()))})},s))},c=()=>{l()||(i=!0,o.close(),ft(p=>({...p,isConnected:!1,status:"disconnected"})),d())};o.addEventListener("connected",()=>{l()||Ca(e).then(async p=>{if(l())return;if(!p||r&&p.projectId!==r){c();return}let u=[...p?.activeJobs??(p?.activeJob?[p.activeJob]:[]),...p?.queuedJobs?.filter(j=>j.parked)??[]],h=p?.recentJobs??[],{planBridgeReconnectRecovery:m}=await import("./bridge-recovery-3IQN3U6D.mjs");if(l())return;let g=m(Ra().activeJobIds,u,h),{serverActiveIds:x,terminalJobs:S}=g,z=S.map(j=>j.id),H=new Map(jo);for(let j of S)H.set(j.id,j.status==="error"?{type:"error",jobId:j.id,message:j.error??"The agent run failed.",threadId:j.threadId,annotationIds:j.annotationIds}:{type:"done",jobId:j.id,success:!0,threadId:j.threadId,annotationIds:j.annotationIds});ft(j=>{let Z={...j.lastErrorByJob};for(let N of S)N?.status==="error"&&N.error&&(Z[N.id]=N.error);let k=m(j.activeJobIds,u,h).reconciledActiveIds,V={};for(let N of u)N.threadId&&(V[N.id]=N.threadId);return{...j,isConnected:!0,status:k.length>0?"streaming":z.length>0||j.status==="disconnected"?"idle":j.status,activeJobId:k.length>0?k[k.length-1]:null,activeJobIds:k,activeJobThreads:V,lastErrorByJob:Z,workspaceGeneration:p?.workspaceGeneration}});let w=[...new Set([...x,...z,...jo.keys()])];w.length>0&&Au(e,w,t,H).catch(c)}).catch(c)}),o.addEventListener("job_parked",p=>{if(l())return;let u=JSON.parse(p.data);$n(u.jobId,u)||Ki("job_parked",u,u.jobId)}),o.addEventListener("thread_changed",p=>{if(l())return;let u=JSON.parse(p.data);ft(h=>({...h,events:[...h.events,{type:"thread_changed",data:u,timestamp:Date.now()}]}))}),o.addEventListener("job_started",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if($n(h,u))return;let m=u.threadId;ft(g=>({...g,status:"streaming",activeJobId:h,activeJobIds:g.activeJobIds.includes(h)?g.activeJobIds:[...g.activeJobIds,h],activeJobThreads:m?{...g.activeJobThreads,[h]:m}:g.activeJobThreads,jobResponses:{...g.jobResponses,[h]:g.jobResponses[h]??""},jobThinking:{...g.jobThinking,[h]:g.jobThinking[h]??""},currentResponse:g.jobResponses[h]??"",currentThinking:g.jobThinking[h]??"",lastResponseText:null,lastThreadId:null,events:[...g.events,{type:"job_started",data:u,timestamp:Date.now()}]}))}),o.addEventListener("delta",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if($n(h,u))return;let m=u.text||"";ft(g=>({...g,jobResponses:h?{...g.jobResponses,[h]:(g.jobResponses[h]||"")+m}:g.jobResponses,currentResponse:!h||h===g.activeJobId?g.currentResponse+m:g.currentResponse,events:[...g.events,{type:"delta",data:u,timestamp:Date.now()}]}))}),o.addEventListener("thinking",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if($n(h,u))return;let m=u.text||"";ft(g=>({...g,jobThinking:h?{...g.jobThinking,[h]:(g.jobThinking[h]||"")+m}:g.jobThinking,currentThinking:!h||h===g.activeJobId?g.currentThinking+m:g.currentThinking,events:[...g.events,{type:"thinking",data:u,timestamp:Date.now()}]}))}),o.addEventListener("status",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||ft(m=>({...m,events:[...m.events,{type:"status",data:u,timestamp:Date.now()}]}))}),o.addEventListener("orientation",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||ft(m=>({...m,events:[...m.events,{type:"orientation",data:u,timestamp:Date.now()}]}))}),o.addEventListener("approval",p=>{if(l())return;let u=JSON.parse(p.data);$n(u.jobId,u)||ft(h=>({...h,events:[...h.events,{type:"approval",data:u,timestamp:Date.now()}]}))}),o.addEventListener("imprint_used",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||ft(m=>({...m,events:[...m.events,{type:"imprint_used",data:u,timestamp:Date.now()}]}))}),o.addEventListener("tool_use",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||ft(m=>({...m,events:[...m.events,{type:"tool_use",data:u,timestamp:Date.now()}]}))});for(let p of["image_generation","image_ready"])o.addEventListener(p,u=>{if(l())return;let h=JSON.parse(u.data),m=h.jobId;$n(m,h)||ft(g=>({...g,events:[...g.events,{type:p,data:h,timestamp:Date.now()}]}))});o.addEventListener("done",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||(h&&delete Po[h],ft(m=>{let g=h?m.activeJobIds.filter(j=>j!==h):m.activeJobIds,x={...m.jobResponses},S={...m.jobThinking},z={...m.activeJobThreads},H=h?x[h]:void 0;h&&(delete x[h],delete S[h],delete z[h]);let w=h===m.activeJobId?g.length>0?g[g.length-1]:null:m.activeJobId;return{...m,activeJobIds:g,activeJobId:w,jobResponses:x,jobThinking:S,lastCompletedJobId:h??m.activeJobId,lastResponseText:u.responseText||H||m.currentResponse||null,lastThreadId:u.threadId??null,...h===m.activeJobId?{currentResponse:w&&x[w]||"",currentThinking:w&&S[w]||""}:{},events:[...m.events,{type:"done",data:u,timestamp:Date.now()}]}}))}),o.addEventListener("question",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||ft(m=>({...m,pendingQuestions:[...m.pendingQuestions,{jobId:u.jobId,threadId:u.threadId,question:u.question,annotationIds:u.annotationIds,timestamp:Date.now()}],events:[...m.events,{type:"question",data:u,timestamp:Date.now()}]}))}),o.addEventListener("capabilities_changed",()=>{l()||ft(p=>({...p,capabilitiesVersion:p.capabilitiesVersion+1}))}),o.addEventListener("workspace_cleared",p=>{if(l())return;let u=JSON.parse(p.data);typeof u.workspaceGeneration!="number"||!Number.isInteger(u.workspaceGeneration)||u.workspaceGeneration<0||ft(h=>{for(let m of[...h.activeJobIds,...jo.keys()])wl.add(m);return jo.clear(),{...h,workspaceGeneration:u.workspaceGeneration,status:"idle",activeJobId:null,activeJobIds:[],activeJobThreads:{},jobResponses:{},jobThinking:{},currentResponse:"",currentThinking:"",events:[],lastCompletedJobId:null,lastResponseText:null,lastThreadId:null,lastErrorByJob:{},pendingQuestions:[],incrementalResolutions:[]}})}),o.addEventListener("queue_drained",()=>{if(l())return;let p=[...Ra().activeJobIds];if(p.length===0){ft(u=>({...u,status:u.status==="error"?"error":"idle",incrementalResolutions:[]}));return}Au(e,p,t).then(()=>{l()||ft(u=>({...u,status:u.activeJobIds.length>0?u.status:u.status==="error"?"error":"idle",incrementalResolutions:u.activeJobIds.length>0?u.incrementalResolutions:[]}))}).catch(c)}),o.addEventListener("error",p=>{if(!l()){if(o.readyState===EventSource.CLOSED)c();else if(p instanceof MessageEvent){let u=JSON.parse(p.data),h=u.jobId??null;if($n(h??void 0,u))return;h&&delete Po[h];let m=u.message??"";ft(g=>{let x=h?g.activeJobIds.filter(z=>z!==h):g.activeJobIds,S=x.length>0?g.status:"error";return{...g,status:S,activeJobIds:x,lastCompletedJobId:h??g.activeJobId,lastErrorByJob:h&&m?{...g.lastErrorByJob,[h]:m}:g.lastErrorByJob,events:[...g.events,{type:"error",data:u,timestamp:Date.now()}]}})}}}),o.onerror=()=>{l()||o.readyState===EventSource.CLOSED&&ft(p=>({...p,isConnected:!1,status:"disconnected"}))}}function qg(e="http://localhost:1111",t=!0,n){let r=kg(Bg,Ra,Ra);O(()=>{if(Mu(n),!t)return;let a=!1;return Ru(e,n).then(l=>{!l||a||Ca(l).then(s=>{!a&&s&&(!n||s.projectId===n)&&Ks(l)})}),()=>{a=!0}},[e,t,n]);let o=J(()=>{ft(()=>({...Ra(),events:[],currentResponse:"",currentThinking:"",jobResponses:{},jobThinking:{},lastResponseText:null,lastThreadId:null,lastErrorByJob:{},incrementalResolutions:[]}))},[]),i=J(a=>{ft(l=>({...l,pendingQuestions:l.pendingQuestions.filter(s=>s.threadId!==a)}))},[]);return{...r,clearEvents:o,dismissQuestion:i}}function $u(e,t,n,r,o){let i=`devtools-model-id:${r}`,[a,l]=P(()=>typeof window>"u"?"":localStorage.getItem(i)??""),s=o?.(a)??!1,d=s?-1:e.findIndex(u=>u.id===a),c=d>=0?d:0,p=J(u=>{l(u),localStorage.setItem(i,u)},[i]);return O(()=>{n&&a&&(s||t&&d<0&&e.some(u=>u.id))&&p("")},[n,t,a,d,e,p,s]),{index:c,select:p}}function Ug(e,t,n){let r=e.flatMap(({requestedAt:a,resolvedAt:l})=>Number.isFinite(a)&&Number.isFinite(l)?[[Math.max(t,a),Math.min(n,l)]]:[]).sort((a,l)=>a[0]-l[0]),o=t,i=0;for(let[a,l]of r)i+=Math.max(0,l-Math.max(o,a)),o=Math.max(o,l);return i}function Lu(e){let t=new Map,n=new Set;for(let r of e)if(r.type==="approval"){let o=r.data.approval;t.set(o.id,o)}else(r.type==="done"||r.type==="error")&&n.add(String(r.data.jobId));return new Set([...t.values()].filter(r=>r.status==="pending"&&!n.has(r.jobId)).map(r=>r.jobId))}function Pu(e){let t=new MutationObserver(n=>{let r=n.filter(o=>document.body.contains(o.target)||o.target===document.documentElement&&[...o.addedNodes,...o.removedNodes].some(i=>i instanceof Element&&i.tagName==="BODY"));r.length&&e(r)});return t.observe(document.documentElement,{childList:!0,subtree:!0}),t}function Yg(e,t,n,r=8*1024*1024){let o=d=>JSON.stringify({id:e,clientId:t,result:d}),i=d=>new TextEncoder().encode(d).length<=r,a=o(n);if(i(a))return a;let l=Array.isArray(n.images)?n.images:[],s=[l.filter(d=>d.kind==="annotated-viewport"),l.filter(d=>d.kind!=="annotated-viewport"),[]];for(let d of s){let c=o({...n,images:d,visualEvidence:{status:"partial",reason:"response_size_limit",omitted:l.filter(p=>!d.includes(p)).map(p=>p.kind)}});if(i(c))return c}return o({status:"context_too_large",targetKey:n.targetKey,images:[],warning:"Context exceeds the response limit even without images."})}function Xg(e,t,n){let r=B(n);r.current=n;let[o,i]=P([]),a=h=>i(h?[h]:[]),l=B(null),s=B(null),d=B(null),c=J(()=>d.current?.(),[]),p=J(h=>{l.current=h,s.current?.(h)},[]),u=B(null);return O(()=>{if(!e)return;u.current?.url!==t&&(u.current={url:t,clientId:crypto.randomUUID(),sequence:0,sending:!1});let h=u.current,m={clientId:h.clientId,sequence:0,page:location.origin+location.pathname,title:document.title,active:!0,windowFocused:document.hasFocus(),lastInteractionAt:0,blurredAt:0,hover:null,pinned:null,history:[]},g=null,x=new WeakMap,S=new Map,z,H=!1,w,j=0,Z=()=>{let _=location.origin+location.pathname;m.page!==_&&(m.page=_,m.title=document.title,m.hover=null,m.pinned=null,m.history=[],m.recent=null,m.selected=null,S.clear(),g=null,m.lastInteractionAt=0),m.sequence=++h.sequence,h.pendingBody=JSON.stringify(m),!h.sending&&(h.sending=!0,(async()=>{for(;h.pendingBody;){let R=h.pendingBody;h.pendingBody=void 0;try{await Yt(`${t}/focus`,{method:"POST",headers:{"Content-Type":"application/json"},body:R,signal:AbortSignal.timeout(3e3)})}catch{}}h.sending=!1})())},k=(_,R)=>{x.has(_)||x.set(_,crypto.randomUUID());let D=vn(_),L=bn(_),E=getComputedStyle(_),te={...R?{subject:R}:{},key:x.get(_),capturedAt:Date.now(),selector:D.selector,tagName:D.tagName,text:D.textContent?.slice(0,200),component:D.reactComponent,source:D.reactSource,rect:{x:L.x,y:L.y,width:L.width,height:L.height},styles:Object.fromEntries(["color","background-color","font-size","font-family","display","padding","border-radius"].map(re=>[re,E.getPropertyValue(re)]))};if(S.set(te.key,{element:_,target:te}),S.size>32){let re=[...S.keys()].find(ee=>ee!==m.pinned?.key);re&&S.delete(re)}return te},V=_=>{let R=_?.element??null,D=_?.selection==="selected",L=m.selected??m.hover;R===g&&!!m.selected===D&&L?.subject?.key===_?.subject?.key||(g=R,clearTimeout(z),z=setTimeout(()=>{if(H)return;let E=R?.isConnected&&!Aa(R,"input, textarea, select, [contenteditable], [data-popmelt-private], [data-popmelt-canvas-block], [data-devtools]")?k(R,_?.subject):null;m.selected=D?E:null,m.hover=D?null:E,D&&(m.recent=null),m.hover&&(m.history=[...m.history,m.hover].slice(-8)),m.windowFocused&&(m.recent=null),Z()},R&&!D?120:0))};s.current=V,d.current=()=>{H||document.visibilityState!=="visible"||(m.lastInteractionAt=Date.now(),m.windowFocused=document.hasFocus(),!w&&(w=setTimeout(()=>{w=void 0,j=Date.now(),Z()},Math.max(0,250-(Date.now()-j)))))},V(l.current);let N=()=>{m.windowFocused=document.hasFocus(),m.blurredAt=m.windowFocused?0:Date.now(),m.recent=m.windowFocused?null:m.hover,Z()},Y=()=>{m.active=document.visibilityState==="visible",m.active?V(l.current):(clearTimeout(z),m.hover=null,m.history=[],m.recent=null,m.selected=null,S.clear(),g=null,m.lastInteractionAt=0),Z()};document.addEventListener("visibilitychange",Y),window.addEventListener("focus",N),window.addEventListener("blur",N);let q=setInterval(Z,1e4),ie=!1,I,Q=new Set,$=setInterval(async()=>{if(!(H||ie||document.visibilityState!=="visible")){ie=!0;try{let _=await Yt(`${t}/focus/requests?clientId=${m.clientId}`,{signal:AbortSignal.timeout(3e3)});if(!_.ok)return;let R=await _.json();for(let D of R){if(Q.has(D.id)||H||D.expiresAt<Date.now())continue;Q.add(D.id),Q.size>64&&Q.delete(Q.values().next().value);let L=S.get(D.targetKey),E={status:"target_unavailable"};if(D.tasteProposal){let{tasteProposalSession:te}=await import("./taste-proposal-session-XU4N7RUV.mjs");if(H||D.expiresAt<Date.now())continue;let re=document.activeElement;for(;re?.shadowRoot?.activeElement;)re=re.shadowRoot.activeElement;E=re?.matches("input, textarea, select, [contenteditable]")&&Aa(re,"[data-taste-editor]")&&D.tasteProposal.action!=="inspect"?{status:"busy",reason:"The human is editing a proposal field. Retry after editing ends."}:te.command(D.tasteProposal)}else if(D.workspace){let{collectWorkspaceSnapshot:te,workspaceAttentionTarget:re}=await import("./workspace-snapshot-EJQHHDQ4.mjs");if(H||D.expiresAt<Date.now())continue;E=te(r.current.state,D.workspace);let ee=D.workspace.entryId?[D.workspace.entryId]:"entries"in E?E.entries.map(U=>U.id):[],oe=[...new Set(ee.map(U=>re(r.current.state,U,r.current.registry)).filter(U=>!!U))];i(oe);for(let U of oe)U instanceof HTMLElement&&U.hasAttribute("data-popmelt-thread-header")&&vg(U,U);if(oe.length&&(clearTimeout(I),I=setTimeout(()=>a(null),Math.max(0,D.expiresAt-Date.now())),await new Promise(U=>requestAnimationFrame(()=>setTimeout(U,0))),H))break;E.attention=D.workspace.entryId?oe.length?"shown":re(r.current.state,D.workspace.entryId,r.current.registry,!0)?"target_offscreen":"target_missing_hidden_or_ambiguous":{shown:oe.length,requested:ee.length}}else if(L?.element.isConnected&&m.page===location.origin+location.pathname&&!Aa(L.element,"[data-popmelt-private], input, textarea, select, [contenteditable]"))try{let te=D.attentionOnly?null:(await import("./focus-inspection-2FPCQIN2.mjs")).inspectFocusElement;if(H||D.expiresAt<Date.now()||!L.element.isConnected||m.page!==location.origin+location.pathname)continue;if(a(L.element),clearTimeout(I),I=setTimeout(()=>a(null),Math.max(0,D.expiresAt-Date.now())),await new Promise(re=>requestAnimationFrame(()=>setTimeout(re,0))),H)break;E=te?await te(L.element,L.target,D.screenshot,r.current):{status:"ok",attention:"shown"}}catch{E={status:"capture_failed"}}if(H||document.visibilityState!=="visible")break;(await Yt(`${t}/focus/response`,{method:"POST",headers:{"Content-Type":"application/json"},body:Yg(D.id,m.clientId,E),signal:AbortSignal.timeout(3e3)})).ok||await Yt(`${t}/focus/response`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:D.id,clientId:m.clientId,result:{status:"response_rejected"}}),signal:AbortSignal.timeout(3e3)}),clearTimeout(I),a(null)}}catch{}finally{clearTimeout(I),H||a(null),ie=!1}}},1e3);return Y(),()=>{H=!0,clearTimeout(z),clearTimeout(w),clearInterval(q),clearInterval($),clearTimeout(I),a(null),document.removeEventListener("visibilitychange",Y),window.removeEventListener("focus",N),window.removeEventListener("blur",N),s.current=null,d.current=null,S.clear(),m.hover=null,m.selected=null,m.history=[],m.active=!1,Z()}},[e,t]),{onCanvasFocusChange:p,onCanvasActivity:c,inspectingElement:e?o[0]??null:null,inspectingElements:e?o:[]}}function Kg(e,t,n,r){let[o,i]=P(null),[a,l]=P(null),s=B(0),d=B(Promise.resolve(!0)),c=J(()=>{s.current=Date.now()},[]),p=J(h=>{s.current=Date.now(),i(h)},[]),u=J(h=>l(m=>JSON.stringify(m)===JSON.stringify(h)?m:h),[]);return O(()=>{if(!e||!r)return;let h=o?.element;if(h&&Aa(h,"[data-private], [data-sensitive]"))return;let m=a?.targets??(h?[{selector:o?.subject?lu(o.subject):Lo(h),...o?.subject?{subject:o.subject}:{}}]:[]);if(!m.length)return;let g={pathname:window.location.pathname,ownerId:t,color:n,targets:m,activity:"looking",...a?{threadId:a.threadId}:{}},x=!1,S=null,z=!1,H=(N,Y,q)=>{let ie=d.current.then(()=>N!=="finish"&&(x||S!==Y)?!1:e(N,Y,q));return d.current=ie.catch(()=>!1),ie},w=()=>{let N=S;S=null,N&&H("finish",N).catch(()=>{})},j=async()=>{if(x||z)return;if(!(document.visibilityState!=="hidden"&&document.hasFocus()&&g.pathname===window.location.pathname&&(a||h?.isConnected&&(o?.selection==="selected"||Date.now()-s.current<5e3)))){w();return}z=!0;let N=S?"renew":"start",Y=S??crypto.randomUUID();S=Y;try{!await H(N,Y,g)&&S===Y&&(S=null),x&&w()}catch{S===Y&&(S=null)}finally{z=!1}},Z=setTimeout(j,120),k=setInterval(j,1e3),V=()=>w();return window.addEventListener("blur",V),window.addEventListener("focus",j),document.addEventListener("visibilitychange",j),()=>{x=!0,clearTimeout(Z),clearInterval(k),w(),window.removeEventListener("blur",V),window.removeEventListener("focus",j),document.removeEventListener("visibilitychange",j)}},[e,r,t,n,o,a]),{onFocus:p,onActivity:c,onThread:u}}var Sl="data-popmelt-preview-target",ju="script,iframe,object,embed,link,meta,base,style,template";function Vg({root:e,targets:t,revision:n,width:r,height:o,cleanClone:i}){let a=e.cloneNode(!0),l=[e,...e.querySelectorAll("*")],s=[a,...a.querySelectorAll("*")],d=new Set,c=new Map;for(let[u,h]of t){if(!u||!l.includes(h))throw new Error("Target is outside the preview root");if(c.has(h))throw new Error("Target has multiple identities");c.set(h,u)}l.forEach((u,h)=>{let m=s[h];(u.shadowRoot||u.matches("canvas,video"))&&d.add("Shadow DOM, canvas and video state are not mirrored");for(let x of[...m.attributes])(/^on/i.test(x.name)||["src","srcset","href","xlink:href","action","formaction","autofocus","contenteditable",Sl].includes(x.name))&&m.removeAttribute(x.name);u instanceof HTMLInputElement&&(u.type==="password"||u.type==="file"?m.removeAttribute("value"):m.setAttribute("value",u.value),m.toggleAttribute("checked",u.checked)),u instanceof HTMLTextAreaElement&&(m.textContent=u.value),u instanceof HTMLOptionElement&&m.toggleAttribute("selected",u.selected);let g=c.get(u);g&&m.setAttribute(Sl,g),i?.(u,m)});for(let u of a.querySelectorAll(ju))u.remove();for(let u of a.querySelectorAll("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-root], popmelt-root"))u.remove();if(a.matches(ju))throw new Error("Unsupported preview root");let p="";for(let u of e.ownerDocument.styleSheets)if(!(u.ownerNode instanceof Element&&u.ownerNode.closest("[data-devtools], [data-popmelt-top-layer-host]")))try{p+=[...u.cssRules].map(h=>h.cssText).join(`
2
+ import{b as Xf,f as Oi,h as Kf,g as ms,a as dc,d as cc,c as uc}from"./chunk-3LBOX7HQ.mjs";import{a as Vf}from"./chunk-HTHUSDZT.mjs";import{M as il,vb as gs,Ua as pc,f as Gf,e as fc,tb as ys,a as Qf,xb as hc,yb as mc,wb as vs,c as Zf,jb as eh,kb as th,Ja as _i,ja as nh,Db as rh,Eb as gc,ia as oh,Kb as ih,Gb as ah,Hb as lh,Ib as sh,_a as dh,ka as ch,Da as uh,za as yc,ab as ph,ba as fh,ca as bs,da as hh,ea as mh,$a as gh,Fa as yh,ha as vh,ob as xs,nb as bh,mb as ws,Fb as xh,la as wh,Oa as vc,Ba as bc,Ma as xc,Na as Sh,La as wc,Ka as Ih,Ga as Ss,N as kh,Cb as Th,p as Sc,ya as Eh,b as Ch,ub as Ic,Ra as Ah,Qa as Mh,Ta as Rh,Pa as $h,Sa as Lh,Ca as Ph,D as jh,E as zh,l as Dh,ra as en,ua as Hh,xa as Nh,Ha as Oh,sa as kc,na as Fi,T as _h,ma as Fh,R as Tc,Y as Wh,fb as ci,Mb as Bh,Jb as Jh,eb as Ec,gb as Cc,Ab as qh,Bb as Uh,lb as Yh,hb as Xh,ib as Kh,Aa as Vh,Ea as Is,Q as Gh,C as Ac,F as Mc,L as Rc,K as $c,o as ui,G as Lc,J as Wi,P as Qh,va as ks,qa as Zh,pa as Ts,oa as Es,O as em,ga as tm,fa as nm,Ia as rm,ta as Pc,wa as jc,q as om,W as zc,U as Dc,V as Hc,X as im,Z as Nc,$ as Oc,aa as am,S as lm,zb as _c,m as Bi,A as Cs,r as pi,I as al,u as Fc,g as sm,_ as dm,t as ll,h as Wc,y as cm,j as Pr,v as As,s as Ia,i as Ms,k as um,z as pm,x as fm,H as Rs,w as Bc,n as Jc,B as hm}from"./chunk-5IEPFMP7.mjs";import{h as mm,Ba as qc,R as Ji,ma as gm,N as ym,H as Uc,A as no,la as sl,ka as vm,P as bm,D as Yc,O as xm,da as Sn,Y as $s,aa as ar,fa as Ls,$ as ka,ha as wm,S as dl,ua as Xc,_ as ro,za as Sm,Aa as Kc,ta as Vc,J as Ps,v as Gc,u as Ta,r as cl,w as qi,Z as Qc,Q as Zc,I as Im,K as km,M as Tm,f as Em,ba as Cm,ca as Am,wa as Mm,va as eu,ya as Rm,xa as $m,sa as tu,z as nu,t as js,g as Lm,ea as zs,C as Pm,E as ru,G as jm,F as zm,ga as ou,ia as iu,B as Dm,s as ul,L as Hm,y as Ds,q as au,x as Nm}from"./chunk-ENGMQINZ.mjs";import{c as Om,a as lu,b as Ea}from"./chunk-JQHZFDY5.mjs";import{i as su,k as _m,m as Fm,h as du,g as Wm,a as pl,e as Bm,b as jr,d as Jm,f as it,c as qm}from"./chunk-MP7S5ALD.mjs";import{c as pn,a as Lo,i as vn,j as Ui,d as Um,e as Ym,b as cu,l as Xm,m as Km,k as Vm}from"./chunk-XOGBFVWI.mjs";import{a as Gm}from"./chunk-2P2NUZW7.mjs";import{d as Hs,i as Qm}from"./chunk-MZNY6VXR.mjs";import{a as Ns,h as uu,d as Zm,c as eg,g as Os,e as _s,b as tg}from"./chunk-2RRYBN2J.mjs";import{b as Yt,f as pu,d as fu,e as Fs,i as ng,j as Ca,l as hu,m as mu,r as rg,p as og,u as ig,t as ag,s as lg,k as sg,a as dg,c as cg}from"./chunk-CPOYMGYY.mjs";import{a as gu,b as ug}from"./chunk-EX63NVDN.mjs";import{d as pg,g as fg,m as hg,l as mg}from"./chunk-N2ZEZCHO.mjs";import{a as gg}from"./chunk-J3UIBBU2.mjs";import{b as yg}from"./chunk-6VXFTT5U.mjs";import{a as vg}from"./chunk-LVEMYZOA.mjs";import{d as bn,o as Aa,n as Yi,a as yu,i as vu,v as bu,u as xu,h as fl,k as bg,f as xg,c as Ws,m as wu,l as Bs}from"./chunk-HGW2U6PD.mjs";import{lazy as hl,memo as wg,useContext as zr,useState as P,Suspense as ml,Fragment as Sg,useRef as B,useEffect as O,useLayoutEffect as It,useCallback as J,useMemo as we,cloneElement as Ig,useSyncExternalStore as kg,useId as Tg}from"react";import{jsx as f,jsxs as M,Fragment as ut}from"react/jsx-runtime";import{Fingerprint as oo,Component as gl,Reply as Su,Ban as yl,Terminal as Eg,PenLine as Cg,ImageIcon as Ag,Plug as Mg,SquareMousePointer as Rg,ChevronRight as Js,ThumbsUp as $g,Clock as qs,ChevronDown as Xi,Check as fi,ChevronLeft as Lg,X as Us,Send as Iu,Lock as Pg,ArrowDown as jg,OctagonAlert as ku,MessageCircleQuestionMark as zg,TriangleAlert as Dg,Command as Tu,CornerDownLeft as Ys,EyeOff as Hg}from"lucide-react";import{createPortal as Eu}from"react-dom";function Cu(e,t){return e.store===void 0&&(e.store=t),e.store}function Ng(e,t){let n=e.listeners??(e.listeners=new Set);return n.add(t),()=>n.delete(t)}function Og(e,t,n){let r=n(Cu(e,t));e.store=r;for(let o of e.listeners??[])o();return r}var nt=globalThis.__POPMELT_BRIDGE_CONNECTION__??(globalThis.__POPMELT_BRIDGE_CONNECTION__={}),vl=nt.sourceId??(typeof localStorage<"u"?localStorage.getItem("popmelt-source-id"):null)??(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).slice(2));nt.sourceId=vl;try{typeof localStorage<"u"&&localStorage.setItem("popmelt-source-id",vl)}catch{}function Xs(){return vl}var bl={isConnected:!1,status:"disconnected",jobResponses:{},jobThinking:{},activeJobIds:[],activeJobThreads:{},currentResponse:"",currentThinking:"",events:[],activeJobId:null,lastCompletedJobId:null,lastResponseText:null,lastThreadId:null,lastErrorByJob:{},pendingQuestions:[],incrementalResolutions:[],capabilitiesVersion:0};nt.store??(nt.store={...bl}),nt.listeners??(nt.listeners=new Set);var Dr=nt.activeEs??null,xl=nt.activeBridgeUrl??null,io=null,Jn=nt.connectionGeneration??0,Ma=new Set,hi=new Map,Po={},wl=new Set,jo=new Map;function $n(e,t){if(!e)return!1;if(wl.has(e))return!0;if(Ma.has(e)){let r=hi.get(e);return r||(r=[],hi.set(e,r)),r.push({type:t.type??"",data:t}),!0}let n=Po[e];return n!==void 0&&typeof t.seq=="number"&&t.seq<=n}async function Au(e,t,n,r=new Map){let o=()=>n!==(nt.connectionGeneration??0);for(let l of t){if(o())return;jo.set(l,r.get(l)??jo.get(l)),Ma.add(l),hi.set(l,[])}let{mergeBackfillHistory:i,selectBackfillTerminalEvent:a}=await import("./bridge-recovery-3IQN3U6D.mjs");o()||await Promise.all(t.map(async l=>{try{let s=await hu(e,l,-1,{retryUnavailable:!0});if(o()||wl.has(l))return;let d=hi.get(l)??[];if(s){ft(u=>{let h={...u.jobResponses,[l]:s.accumulated.response},m={...u.jobThinking,[l]:s.accumulated.thinking},g=i(u.events,l,s.events);return{...u,jobResponses:h,jobThinking:m,currentResponse:l===u.activeJobId?s.accumulated.response:u.currentResponse,currentThinking:l===u.activeJobId?s.accumulated.thinking:u.currentThinking,events:g}}),Po[l]=s.currentSeq;let c=[...s.events].reverse().find(u=>u.type==="job_started"||u.type==="job_parked");c?.type==="job_parked"&&Ki("job_parked",c,l);let p=a(s.events,s.jobActive,r.get(l));p&&Ki(p.type,p,l);for(let u of d)typeof u.data.seq=="number"&&u.data.seq<=s.currentSeq||Ki(u.type,u.data,l)}else{let c=!1;for(let u of d)Ki(u.type,u.data,l),(u.type==="done"||u.type==="error")&&(c=!0);let p=r.get(l);!c&&p&&Ki(p.type,p,l)}jo.delete(l)}finally{o()||(Ma.delete(l),hi.delete(l))}}))}function Ki(e,t,n){if(e==="job_parked")ft(r=>{let o=r.activeJobIds.filter(i=>i!==n);return{...r,activeJobIds:o,activeJobId:o.at(-1)??null,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}});else if(e==="job_started")ft(r=>({...r,status:"streaming",activeJobId:n,activeJobIds:[...new Set([...r.activeJobIds,n])],activeJobThreads:typeof t.threadId=="string"?{...r.activeJobThreads,[n]:t.threadId}:r.activeJobThreads,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}));else if(e==="delta"){let r=t.text||"";ft(o=>({...o,jobResponses:{...o.jobResponses,[n]:(o.jobResponses[n]||"")+r},currentResponse:n===o.activeJobId?o.currentResponse+r:o.currentResponse,events:[...o.events,{type:"delta",data:t,timestamp:Date.now()}]}))}else if(e==="thinking"){let r=t.text||"";ft(o=>({...o,jobThinking:{...o.jobThinking,[n]:(o.jobThinking[n]||"")+r},currentThinking:n===o.activeJobId?o.currentThinking+r:o.currentThinking,events:[...o.events,{type:"thinking",data:t,timestamp:Date.now()}]}))}else if(e==="status")ft(r=>({...r,events:[...r.events,{type:"status",data:t,timestamp:Date.now()}]}));else if(e==="done")delete Po[n],ft(r=>{let o=r.activeJobIds.filter(d=>d!==n),i={...r.jobResponses},a={...r.jobThinking},l=i[n];delete i[n],delete a[n];let s=n===r.activeJobId?o.length>0?o[o.length-1]:null:r.activeJobId;return{...r,activeJobIds:o,activeJobId:s,jobResponses:i,jobThinking:a,lastCompletedJobId:n,lastResponseText:t.responseText||l||r.currentResponse||null,lastThreadId:t.threadId??null,...n===r.activeJobId?{currentResponse:s&&i[s]||"",currentThinking:s&&a[s]||""}:{},events:[...r.events,{type:"done",data:t,timestamp:Date.now()}]}});else if(e==="error"){delete Po[n];let r=t.message??"";ft(o=>{let i=o.activeJobIds.filter(l=>l!==n),a=i.length>0?o.status:"error";return{...o,status:a,activeJobIds:i,lastCompletedJobId:n,lastErrorByJob:r?{...o.lastErrorByJob,[n]:r}:o.lastErrorByJob,events:[...o.events,{type:"error",data:t,timestamp:Date.now()}]}})}else ft(e==="question"?r=>{let o=typeof t.threadId=="string"?t.threadId:"",i=typeof t.question=="string"?t.question:"",a=Array.isArray(t.annotationIds)?t.annotationIds.filter(s=>typeof s=="string"):void 0,l=r.pendingQuestions.some(s=>s.jobId===n);return{...r,pendingQuestions:i&&o&&!l?[...r.pendingQuestions,{jobId:n,threadId:o,question:i,annotationIds:a,timestamp:Date.now()}]:r.pendingQuestions,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}}:r=>({...r,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}))}var qn=nt.discoveredBridgeUrl??null,Ln=nt.discoveredBridgeProjectId??null,zo=null,Vi=null;function Mu(e,t=!1){let n=e??null;if(!(!t&&(nt.expectedProjectId??null)===n)){Dr&&(Dr.close(),Dr=null,nt.activeEs=null),io&&(clearTimeout(io),io=null),xl=null,nt.activeBridgeUrl=null,qn=null,Ln=null,nt.discoveredBridgeUrl=null,nt.discoveredBridgeProjectId=null,zo=null,Vi=null,Ma.clear(),hi.clear(),wl.clear(),jo.clear();for(let r of Object.keys(Po))delete Po[r];nt.expectedProjectId=n,Jn=(nt.connectionGeneration??Jn)+1,nt.connectionGeneration=Jn,ft(()=>({...bl}))}}function _g(){nt.listeners?.size||Mu(null,!0)}async function Ru(e,t){if(qn&&(t?Ln===t:!Ln))return qn;if(!t&&Ln&&(qn=null,Ln=null,nt.discoveredBridgeUrl=qn,nt.discoveredBridgeProjectId=Ln),t&&Ln&&Ln!==t&&(qn=null,Ln=null,nt.discoveredBridgeUrl=qn,nt.discoveredBridgeProjectId=Ln),zo&&Vi===(t??null))return zo;let n=Jn;return Vi=t??null,zo=sg(e,t).then(r=>n!==Jn?null:(qn=r?.url??null,Ln=r?.projectId??t??null,nt.discoveredBridgeUrl=qn,nt.discoveredBridgeProjectId=Ln,zo=null,Vi=null,qn)).catch(()=>(n!==Jn||(zo=null,Vi=null),null)),zo}function Fg(){return qn}async function Wg(e,t){qn=null,Ln=null,nt.discoveredBridgeUrl=null,nt.discoveredBridgeProjectId=null,zo=null,Vi=null;let n=Jn,r=await Ru(e,t);return r&&n===Jn&&Ks(r),r}function Ra(){return Cu(nt,{...bl})}function Bg(e){return Ng(nt,e)}function ft(e){Og(nt,{...bl},t=>{let n=e(t),r=new Set(n.activeJobIds),o=n.activeJobId&&r.has(n.activeJobId)?n.activeJobId:n.activeJobIds.at(-1)??null;return{...n,activeJobId:o,activeJobThreads:Object.keys(n.activeJobThreads).some(i=>!r.has(i))?Object.fromEntries(Object.entries(n.activeJobThreads).filter(([i])=>r.has(i))):n.activeJobThreads,status:n.status==="streaming"&&r.size===0?"idle":n.status}})}function Jg(){return typeof window<"u"?window.__POPMELT_PROJECT_ID__??null:null}function Ks(e){if(Dr&&Dr.readyState!==EventSource.CLOSED&&xl===e)return;Dr&&(Dr.close(),Dr=null,nt.activeEs=null),io&&(clearTimeout(io),io=null),xl=e,nt.activeBridgeUrl=xl,Jn=(nt.connectionGeneration??Jn)+1;let t=Jn;nt.connectionGeneration=Jn;let n=new URLSearchParams({sourceId:vl}),r=Jg();r&&n.set("projectId",r);let o=dg(`${e}/events?${n.toString()}`);Dr=o,nt.activeEs=Dr;let i=!1,a=()=>t!==(nt.connectionGeneration??0),l=()=>i||a();Ma.clear(),hi.clear();let s=5e3,d=()=>{a()||io||(io=setTimeout(()=>{io=null,!a()&&Ca(e).then(p=>{a()||(p&&(!r||p.projectId===r)?Ks(e):(s=Math.min(s*2,3e4),d()))})},s))},c=()=>{l()||(i=!0,o.close(),ft(p=>({...p,isConnected:!1,status:"disconnected"})),d())};o.addEventListener("connected",()=>{l()||Ca(e).then(async p=>{if(l())return;if(!p||r&&p.projectId!==r){c();return}let u=[...p?.activeJobs??(p?.activeJob?[p.activeJob]:[]),...p?.queuedJobs?.filter(j=>j.parked)??[]],h=p?.recentJobs??[],{planBridgeReconnectRecovery:m}=await import("./bridge-recovery-3IQN3U6D.mjs");if(l())return;let g=m(Ra().activeJobIds,u,h),{serverActiveIds:x,terminalJobs:S}=g,z=S.map(j=>j.id),H=new Map(jo);for(let j of S)H.set(j.id,j.status==="error"?{type:"error",jobId:j.id,message:j.error??"The agent run failed.",threadId:j.threadId,annotationIds:j.annotationIds}:{type:"done",jobId:j.id,success:!0,threadId:j.threadId,annotationIds:j.annotationIds});ft(j=>{let Z={...j.lastErrorByJob};for(let N of S)N?.status==="error"&&N.error&&(Z[N.id]=N.error);let k=m(j.activeJobIds,u,h).reconciledActiveIds,V={};for(let N of u)N.threadId&&(V[N.id]=N.threadId);return{...j,isConnected:!0,status:k.length>0?"streaming":z.length>0||j.status==="disconnected"?"idle":j.status,activeJobId:k.length>0?k[k.length-1]:null,activeJobIds:k,activeJobThreads:V,lastErrorByJob:Z,workspaceGeneration:p?.workspaceGeneration}});let w=[...new Set([...x,...z,...jo.keys()])];w.length>0&&Au(e,w,t,H).catch(c)}).catch(c)}),o.addEventListener("job_parked",p=>{if(l())return;let u=JSON.parse(p.data);$n(u.jobId,u)||Ki("job_parked",u,u.jobId)}),o.addEventListener("thread_changed",p=>{if(l())return;let u=JSON.parse(p.data);ft(h=>({...h,events:[...h.events,{type:"thread_changed",data:u,timestamp:Date.now()}]}))}),o.addEventListener("job_started",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if($n(h,u))return;let m=u.threadId;ft(g=>({...g,status:"streaming",activeJobId:h,activeJobIds:g.activeJobIds.includes(h)?g.activeJobIds:[...g.activeJobIds,h],activeJobThreads:m?{...g.activeJobThreads,[h]:m}:g.activeJobThreads,jobResponses:{...g.jobResponses,[h]:g.jobResponses[h]??""},jobThinking:{...g.jobThinking,[h]:g.jobThinking[h]??""},currentResponse:g.jobResponses[h]??"",currentThinking:g.jobThinking[h]??"",lastResponseText:null,lastThreadId:null,events:[...g.events,{type:"job_started",data:u,timestamp:Date.now()}]}))}),o.addEventListener("delta",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if($n(h,u))return;let m=u.text||"";ft(g=>({...g,jobResponses:h?{...g.jobResponses,[h]:(g.jobResponses[h]||"")+m}:g.jobResponses,currentResponse:!h||h===g.activeJobId?g.currentResponse+m:g.currentResponse,events:[...g.events,{type:"delta",data:u,timestamp:Date.now()}]}))}),o.addEventListener("thinking",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if($n(h,u))return;let m=u.text||"";ft(g=>({...g,jobThinking:h?{...g.jobThinking,[h]:(g.jobThinking[h]||"")+m}:g.jobThinking,currentThinking:!h||h===g.activeJobId?g.currentThinking+m:g.currentThinking,events:[...g.events,{type:"thinking",data:u,timestamp:Date.now()}]}))}),o.addEventListener("status",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||ft(m=>({...m,events:[...m.events,{type:"status",data:u,timestamp:Date.now()}]}))}),o.addEventListener("orientation",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||ft(m=>({...m,events:[...m.events,{type:"orientation",data:u,timestamp:Date.now()}]}))}),o.addEventListener("approval",p=>{if(l())return;let u=JSON.parse(p.data);$n(u.jobId,u)||ft(h=>({...h,events:[...h.events,{type:"approval",data:u,timestamp:Date.now()}]}))}),o.addEventListener("imprint_used",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||ft(m=>({...m,events:[...m.events,{type:"imprint_used",data:u,timestamp:Date.now()}]}))}),o.addEventListener("tool_use",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||ft(m=>({...m,events:[...m.events,{type:"tool_use",data:u,timestamp:Date.now()}]}))});for(let p of["image_generation","image_ready"])o.addEventListener(p,u=>{if(l())return;let h=JSON.parse(u.data),m=h.jobId;$n(m,h)||ft(g=>({...g,events:[...g.events,{type:p,data:h,timestamp:Date.now()}]}))});o.addEventListener("done",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||(h&&delete Po[h],ft(m=>{let g=h?m.activeJobIds.filter(j=>j!==h):m.activeJobIds,x={...m.jobResponses},S={...m.jobThinking},z={...m.activeJobThreads},H=h?x[h]:void 0;h&&(delete x[h],delete S[h],delete z[h]);let w=h===m.activeJobId?g.length>0?g[g.length-1]:null:m.activeJobId;return{...m,activeJobIds:g,activeJobId:w,jobResponses:x,jobThinking:S,lastCompletedJobId:h??m.activeJobId,lastResponseText:u.responseText||H||m.currentResponse||null,lastThreadId:u.threadId??null,...h===m.activeJobId?{currentResponse:w&&x[w]||"",currentThinking:w&&S[w]||""}:{},events:[...m.events,{type:"done",data:u,timestamp:Date.now()}]}}))}),o.addEventListener("question",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;$n(h,u)||ft(m=>({...m,pendingQuestions:[...m.pendingQuestions,{jobId:u.jobId,threadId:u.threadId,question:u.question,annotationIds:u.annotationIds,timestamp:Date.now()}],events:[...m.events,{type:"question",data:u,timestamp:Date.now()}]}))}),o.addEventListener("capabilities_changed",()=>{l()||ft(p=>({...p,capabilitiesVersion:p.capabilitiesVersion+1}))}),o.addEventListener("workspace_cleared",p=>{if(l())return;let u=JSON.parse(p.data);typeof u.workspaceGeneration!="number"||!Number.isInteger(u.workspaceGeneration)||u.workspaceGeneration<0||ft(h=>{for(let m of[...h.activeJobIds,...jo.keys()])wl.add(m);return jo.clear(),{...h,workspaceGeneration:u.workspaceGeneration,status:"idle",activeJobId:null,activeJobIds:[],activeJobThreads:{},jobResponses:{},jobThinking:{},currentResponse:"",currentThinking:"",events:[],lastCompletedJobId:null,lastResponseText:null,lastThreadId:null,lastErrorByJob:{},pendingQuestions:[],incrementalResolutions:[]}})}),o.addEventListener("queue_drained",()=>{if(l())return;let p=[...Ra().activeJobIds];if(p.length===0){ft(u=>({...u,status:u.status==="error"?"error":"idle",incrementalResolutions:[]}));return}Au(e,p,t).then(()=>{l()||ft(u=>({...u,status:u.activeJobIds.length>0?u.status:u.status==="error"?"error":"idle",incrementalResolutions:u.activeJobIds.length>0?u.incrementalResolutions:[]}))}).catch(c)}),o.addEventListener("error",p=>{if(!l()){if(o.readyState===EventSource.CLOSED)c();else if(p instanceof MessageEvent){let u=JSON.parse(p.data),h=u.jobId??null;if($n(h??void 0,u))return;h&&delete Po[h];let m=u.message??"";ft(g=>{let x=h?g.activeJobIds.filter(z=>z!==h):g.activeJobIds,S=x.length>0?g.status:"error";return{...g,status:S,activeJobIds:x,lastCompletedJobId:h??g.activeJobId,lastErrorByJob:h&&m?{...g.lastErrorByJob,[h]:m}:g.lastErrorByJob,events:[...g.events,{type:"error",data:u,timestamp:Date.now()}]}})}}}),o.onerror=()=>{l()||o.readyState===EventSource.CLOSED&&ft(p=>({...p,isConnected:!1,status:"disconnected"}))}}function qg(e="http://localhost:1111",t=!0,n){let r=kg(Bg,Ra,Ra);O(()=>{if(Mu(n),!t)return;let a=!1;return Ru(e,n).then(l=>{!l||a||Ca(l).then(s=>{!a&&s&&(!n||s.projectId===n)&&Ks(l)})}),()=>{a=!0}},[e,t,n]);let o=J(()=>{ft(()=>({...Ra(),events:[],currentResponse:"",currentThinking:"",jobResponses:{},jobThinking:{},lastResponseText:null,lastThreadId:null,lastErrorByJob:{},incrementalResolutions:[]}))},[]),i=J(a=>{ft(l=>({...l,pendingQuestions:l.pendingQuestions.filter(s=>s.threadId!==a)}))},[]);return{...r,clearEvents:o,dismissQuestion:i}}function $u(e,t,n,r,o){let i=`devtools-model-id:${r}`,[a,l]=P(()=>typeof window>"u"?"":localStorage.getItem(i)??""),s=o?.(a)??!1,d=s?-1:e.findIndex(u=>u.id===a),c=d>=0?d:0,p=J(u=>{l(u),localStorage.setItem(i,u)},[i]);return O(()=>{n&&a&&(s||t&&d<0&&e.some(u=>u.id))&&p("")},[n,t,a,d,e,p,s]),{index:c,select:p}}function Ug(e,t,n){let r=e.flatMap(({requestedAt:a,resolvedAt:l})=>Number.isFinite(a)&&Number.isFinite(l)?[[Math.max(t,a),Math.min(n,l)]]:[]).sort((a,l)=>a[0]-l[0]),o=t,i=0;for(let[a,l]of r)i+=Math.max(0,l-Math.max(o,a)),o=Math.max(o,l);return i}function Lu(e){let t=new Map,n=new Set;for(let r of e)if(r.type==="approval"){let o=r.data.approval;t.set(o.id,o)}else(r.type==="done"||r.type==="error")&&n.add(String(r.data.jobId));return new Set([...t.values()].filter(r=>r.status==="pending"&&!n.has(r.jobId)).map(r=>r.jobId))}function Pu(e){let t=new MutationObserver(n=>{let r=n.filter(o=>document.body.contains(o.target)||o.target===document.documentElement&&[...o.addedNodes,...o.removedNodes].some(i=>i instanceof Element&&i.tagName==="BODY"));r.length&&e(r)});return t.observe(document.documentElement,{childList:!0,subtree:!0}),t}function Yg(e,t,n,r=8*1024*1024){let o=d=>JSON.stringify({id:e,clientId:t,result:d}),i=d=>new TextEncoder().encode(d).length<=r,a=o(n);if(i(a))return a;let l=Array.isArray(n.images)?n.images:[],s=[l.filter(d=>d.kind==="annotated-viewport"),l.filter(d=>d.kind!=="annotated-viewport"),[]];for(let d of s){let c=o({...n,images:d,visualEvidence:{status:"partial",reason:"response_size_limit",omitted:l.filter(p=>!d.includes(p)).map(p=>p.kind)}});if(i(c))return c}return o({status:"context_too_large",targetKey:n.targetKey,images:[],warning:"Context exceeds the response limit even without images."})}function Xg(e,t,n){let r=B(n);r.current=n;let[o,i]=P([]),a=h=>i(h?[h]:[]),l=B(null),s=B(null),d=B(null),c=J(()=>d.current?.(),[]),p=J(h=>{l.current=h,s.current?.(h)},[]),u=B(null);return O(()=>{if(!e)return;u.current?.url!==t&&(u.current={url:t,clientId:crypto.randomUUID(),sequence:0,sending:!1});let h=u.current,m={clientId:h.clientId,sequence:0,page:location.origin+location.pathname,title:document.title,active:!0,windowFocused:document.hasFocus(),lastInteractionAt:0,blurredAt:0,hover:null,pinned:null,history:[]},g=null,x=new WeakMap,S=new Map,z,H=!1,w,j=0,Z=()=>{let _=location.origin+location.pathname;m.page!==_&&(m.page=_,m.title=document.title,m.hover=null,m.pinned=null,m.history=[],m.recent=null,m.selected=null,S.clear(),g=null,m.lastInteractionAt=0),m.sequence=++h.sequence,h.pendingBody=JSON.stringify(m),!h.sending&&(h.sending=!0,(async()=>{for(;h.pendingBody;){let R=h.pendingBody;h.pendingBody=void 0;try{await Yt(`${t}/focus`,{method:"POST",headers:{"Content-Type":"application/json"},body:R,signal:AbortSignal.timeout(3e3)})}catch{}}h.sending=!1})())},k=(_,R)=>{x.has(_)||x.set(_,crypto.randomUUID());let D=vn(_),L=bn(_),E=getComputedStyle(_),te={...R?{subject:R}:{},key:x.get(_),capturedAt:Date.now(),selector:D.selector,tagName:D.tagName,text:D.textContent?.slice(0,200),component:D.reactComponent,source:D.reactSource,rect:{x:L.x,y:L.y,width:L.width,height:L.height},styles:Object.fromEntries(["color","background-color","font-size","font-family","display","padding","border-radius"].map(re=>[re,E.getPropertyValue(re)]))};if(S.set(te.key,{element:_,target:te}),S.size>32){let re=[...S.keys()].find(ee=>ee!==m.pinned?.key);re&&S.delete(re)}return te},V=_=>{let R=_?.element??null,D=_?.selection==="selected",L=m.selected??m.hover;R===g&&!!m.selected===D&&L?.subject?.key===_?.subject?.key||(g=R,clearTimeout(z),z=setTimeout(()=>{if(H)return;let E=R?.isConnected&&!Aa(R,"input, textarea, select, [contenteditable], [data-popmelt-private], [data-popmelt-canvas-block], [data-devtools]")?k(R,_?.subject):null;m.selected=D?E:null,m.hover=D?null:E,D&&(m.recent=null),m.hover&&(m.history=[...m.history,m.hover].slice(-8)),m.windowFocused&&(m.recent=null),Z()},R&&!D?120:0))};s.current=V,d.current=()=>{H||document.visibilityState!=="visible"||(m.lastInteractionAt=Date.now(),m.windowFocused=document.hasFocus(),!w&&(w=setTimeout(()=>{w=void 0,j=Date.now(),Z()},Math.max(0,250-(Date.now()-j)))))},V(l.current);let N=()=>{m.windowFocused=document.hasFocus(),m.blurredAt=m.windowFocused?0:Date.now(),m.recent=m.windowFocused?null:m.hover,Z()},Y=()=>{m.active=document.visibilityState==="visible",m.active?V(l.current):(clearTimeout(z),m.hover=null,m.history=[],m.recent=null,m.selected=null,S.clear(),g=null,m.lastInteractionAt=0),Z()};document.addEventListener("visibilitychange",Y),window.addEventListener("focus",N),window.addEventListener("blur",N);let q=setInterval(Z,1e4),ie=!1,I,Q=new Set,$=setInterval(async()=>{if(!(H||ie||document.visibilityState!=="visible")){ie=!0;try{let _=await Yt(`${t}/focus/requests?clientId=${m.clientId}`,{signal:AbortSignal.timeout(3e3)});if(!_.ok)return;let R=await _.json();for(let D of R){if(Q.has(D.id)||H||D.expiresAt<Date.now())continue;Q.add(D.id),Q.size>64&&Q.delete(Q.values().next().value);let L=S.get(D.targetKey),E={status:"target_unavailable"};if(D.tasteProposal){let{tasteProposalSession:te}=await import("./taste-proposal-session-XU4N7RUV.mjs");if(H||D.expiresAt<Date.now())continue;let re=document.activeElement;for(;re?.shadowRoot?.activeElement;)re=re.shadowRoot.activeElement;E=re?.matches("input, textarea, select, [contenteditable]")&&Aa(re,"[data-taste-editor]")&&D.tasteProposal.action!=="inspect"?{status:"busy",reason:"The human is editing a proposal field. Retry after editing ends."}:te.command(D.tasteProposal)}else if(D.workspace){let{collectWorkspaceSnapshot:te,workspaceAttentionTarget:re}=await import("./workspace-snapshot-EJQHHDQ4.mjs");if(H||D.expiresAt<Date.now())continue;E=te(r.current.state,D.workspace);let ee=D.workspace.entryId?[D.workspace.entryId]:"entries"in E?E.entries.map(U=>U.id):[],oe=[...new Set(ee.map(U=>re(r.current.state,U,r.current.registry)).filter(U=>!!U))];i(oe);for(let U of oe)U instanceof HTMLElement&&U.hasAttribute("data-popmelt-thread-header")&&vg(U,U);if(oe.length&&(clearTimeout(I),I=setTimeout(()=>a(null),Math.max(0,D.expiresAt-Date.now())),await new Promise(U=>requestAnimationFrame(()=>setTimeout(U,0))),H))break;E.attention=D.workspace.entryId?oe.length?"shown":re(r.current.state,D.workspace.entryId,r.current.registry,!0)?"target_offscreen":"target_missing_hidden_or_ambiguous":{shown:oe.length,requested:ee.length}}else if(L?.element.isConnected&&m.page===location.origin+location.pathname&&!Aa(L.element,"[data-popmelt-private], input, textarea, select, [contenteditable]"))try{let te=D.attentionOnly?null:(await import("./focus-inspection-2FPCQIN2.mjs")).inspectFocusElement;if(H||D.expiresAt<Date.now()||!L.element.isConnected||m.page!==location.origin+location.pathname)continue;if(a(L.element),clearTimeout(I),I=setTimeout(()=>a(null),Math.max(0,D.expiresAt-Date.now())),await new Promise(re=>requestAnimationFrame(()=>setTimeout(re,0))),H)break;E=te?await te(L.element,L.target,D.screenshot,r.current):{status:"ok",attention:"shown"}}catch{E={status:"capture_failed"}}if(H||document.visibilityState!=="visible")break;(await Yt(`${t}/focus/response`,{method:"POST",headers:{"Content-Type":"application/json"},body:Yg(D.id,m.clientId,E),signal:AbortSignal.timeout(3e3)})).ok||await Yt(`${t}/focus/response`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:D.id,clientId:m.clientId,result:{status:"response_rejected"}}),signal:AbortSignal.timeout(3e3)}),clearTimeout(I),a(null)}}catch{}finally{clearTimeout(I),H||a(null),ie=!1}}},1e3);return Y(),()=>{H=!0,clearTimeout(z),clearTimeout(w),clearInterval(q),clearInterval($),clearTimeout(I),a(null),document.removeEventListener("visibilitychange",Y),window.removeEventListener("focus",N),window.removeEventListener("blur",N),s.current=null,d.current=null,S.clear(),m.hover=null,m.selected=null,m.history=[],m.active=!1,Z()}},[e,t]),{onCanvasFocusChange:p,onCanvasActivity:c,inspectingElement:e?o[0]??null:null,inspectingElements:e?o:[]}}function Kg(e,t,n,r){let[o,i]=P(null),[a,l]=P(null),s=B(0),d=B(Promise.resolve(!0)),c=J(()=>{s.current=Date.now()},[]),p=J(h=>{s.current=Date.now(),i(h)},[]),u=J(h=>l(m=>JSON.stringify(m)===JSON.stringify(h)?m:h),[]);return O(()=>{if(!e||!r)return;let h=o?.element;if(h&&Aa(h,"[data-private], [data-sensitive]"))return;let m=a?.targets??(h?[{selector:o?.subject?lu(o.subject):Lo(h),...o?.subject?{subject:o.subject}:{}}]:[]);if(!m.length)return;let g={pathname:window.location.pathname,ownerId:t,color:n,targets:m,activity:"looking",...a?{threadId:a.threadId}:{}},x=!1,S=null,z=!1,H=(N,Y,q)=>{let ie=d.current.then(()=>N!=="finish"&&(x||S!==Y)?!1:e(N,Y,q));return d.current=ie.catch(()=>!1),ie},w=()=>{let N=S;S=null,N&&H("finish",N).catch(()=>{})},j=async()=>{if(x||z)return;if(!(document.visibilityState!=="hidden"&&document.hasFocus()&&g.pathname===window.location.pathname&&(a||h?.isConnected&&(o?.selection==="selected"||Date.now()-s.current<5e3)))){w();return}z=!0;let N=S?"renew":"start",Y=S??crypto.randomUUID();S=Y;try{!await H(N,Y,g)&&S===Y&&(S=null),x&&w()}catch{S===Y&&(S=null)}finally{z=!1}},Z=setTimeout(j,120),k=setInterval(j,1e3),V=()=>w();return window.addEventListener("blur",V),window.addEventListener("focus",j),document.addEventListener("visibilitychange",j),()=>{x=!0,clearTimeout(Z),clearInterval(k),w(),window.removeEventListener("blur",V),window.removeEventListener("focus",j),document.removeEventListener("visibilitychange",j)}},[e,r,t,n,o,a]),{onFocus:p,onActivity:c,onThread:u}}var Sl="data-popmelt-preview-target",ju="script,iframe,object,embed,link,meta,base,style,template";function Vg({root:e,targets:t,revision:n,width:r,height:o,cleanClone:i}){let a=e.cloneNode(!0),l=[e,...e.querySelectorAll("*")],s=[a,...a.querySelectorAll("*")],d=new Set,c=new Map;for(let[u,h]of t){if(!u||!l.includes(h))throw new Error("Target is outside the preview root");if(c.has(h))throw new Error("Target has multiple identities");c.set(h,u)}l.forEach((u,h)=>{let m=s[h];(u.shadowRoot||u.matches("canvas,video"))&&d.add("Shadow DOM, canvas and video state are not mirrored");for(let x of[...m.attributes])(/^on/i.test(x.name)||["src","srcset","href","xlink:href","action","formaction","autofocus","contenteditable",Sl].includes(x.name))&&m.removeAttribute(x.name);u instanceof HTMLInputElement&&(u.type==="password"||u.type==="file"?m.removeAttribute("value"):m.setAttribute("value",u.value),m.toggleAttribute("checked",u.checked)),u instanceof HTMLTextAreaElement&&(m.textContent=u.value),u instanceof HTMLOptionElement&&m.toggleAttribute("selected",u.selected);let g=c.get(u);g&&m.setAttribute(Sl,g),i?.(u,m)});for(let u of a.querySelectorAll(ju))u.remove();for(let u of a.querySelectorAll("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-root], popmelt-root"))u.remove();if(a.matches(ju))throw new Error("Unsupported preview root");let p="";for(let u of e.ownerDocument.styleSheets)if(!(u.ownerNode instanceof Element&&u.ownerNode.closest("[data-devtools], [data-popmelt-top-layer-host]")))try{p+=[...u.cssRules].map(h=>h.cssText).join(`
3
3
  `)+`
4
- `}catch{d.add("An inaccessible stylesheet was omitted")}return d.add("Static snapshot: no scripts, external assets, event handlers or application runtime"),{revision:n,html:e.tagName==="BODY"?a.innerHTML:a.outerHTML,...e.tagName==="BODY"?{bodyAttributes:Object.fromEntries([...a.attributes].map(u=>[u.name,u.value]))}:{},css:p,width:r,height:o,warnings:[...d]}}function zu(e,t){let n=[...e.querySelectorAll(`[${Sl}]`)].filter(r=>r.getAttribute(Sl)===t);return n.length===1?n[0]:null}var Gg=class{constructor(e){this.generation=0,this.cancelPending=null,this.current=null,this.disposed=!1,this.frame=e.ownerDocument.createElement("iframe"),this.frame.setAttribute("sandbox","allow-same-origin"),this.frame.title="Peer plane preview",this.frame.style.cssText="border:0;display:block;pointer-events:none;",this.frame.tabIndex=-1,e.append(this.frame)}async render(e,t,n){if(this.disposed)throw new Error("Preview surface was disposed");this.cancelPending?.();let r=++this.generation;this.current=null,this.frame.width=String(e.width),this.frame.height=String(e.height);let o=this.frame.ownerDocument.implementation.createHTMLDocument("Peer preview"),i=o.createElement("meta");i.httpEquiv="Content-Security-Policy",i.content="default-src 'none'; style-src 'unsafe-inline'; form-action 'none'; base-uri 'none'; script-src 'none'",o.head.prepend(i);let a=o.createElement("style");a.textContent=e.css.replace(/<\/style/gi,"<\\/style"),o.head.append(a),o.body.innerHTML=e.html;for(let[s,d]of Object.entries(e.bodyAttributes??{}))o.body.setAttribute(s,d);let l=o.createElement("style");return l.textContent="*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}",o.head.append(l),o.documentElement.dataset.previewGeneration=String(r),new Promise(s=>{let d=h=>{clearTimeout(u),this.frame.removeEventListener("load",p),this.cancelPending===c&&(this.cancelPending=null),s(h)},c=()=>d(!1),p=()=>{if(r!==this.generation||this.frame.contentDocument?.documentElement.dataset.previewGeneration!==String(r))return;let h=this.frame.contentDocument;n?.(h);for(let m of t.artifacts)m.kind==="style"&&zu(h,m.targetKey)?.style.setProperty(m.property,m.value,"important");this.current={baseline:e,plane:{...t}},d(!0)},u=setTimeout(c,5e3);this.cancelPending=c,this.frame.addEventListener("load",p),queueMicrotask(()=>{!this.disposed&&r===this.generation&&(this.frame.srcdoc="<!doctype html>"+o.documentElement.outerHTML)})})}inspect(e,t){let n=this.current,r=this.frame.contentDocument;if(!n||!r)return null;let o=zu(r,e);if(!o)return null;let i=this.frame.contentWindow.getComputedStyle(o),a=o.getBoundingClientRect();return{planeId:n.plane.id,planeRevision:n.plane.revision,sourceRevision:n.baseline.revision,targetKey:e,styles:Object.fromEntries(t.map(l=>[l,i.getPropertyValue(l)])),rect:{x:a.x,y:a.y,width:a.width,height:a.height}}}dispose(){this.disposed=!0,++this.generation,this.cancelPending?.(),this.current=null,this.frame.remove()}};function Qg(e,t){return{id:e,ownerId:t,revision:0,artifacts:[],undo:[],redo:[],attention:null}}function Vs(e){return ll(e).flatMap(t=>t==="color"?[...Wc]:[t])}function Zg(e,t){if(e===void 0)return{families:Bi.map(n=>({family:n,label:Cs(n)}))};if(!Bi.includes(e))throw new Error("Unknown omnidial family");if(!t)return{family:e,subproperties:Vs(e)};if(!Vs(e).includes(t))throw new Error("Unknown omnidial subproperty");return{family:e,subproperty:t,...e==="transform"&&t==="translate"?{composedToken:"translate-x-<xStep>-y-<yStep>",axisSteps:pi(e,t)}:{},tokens:pi(e,t).map(n=>({token:al(e,n,t),value:Wi(e,n,t)}))}}function ey(e,t){if(t!==void 0&&!Bi.includes(t))throw new Error("Unknown omnidial family");let n=/^translate-x-(-?\d+)-y-(-?\d+)$/.exec(e);if(n&&(!t||t==="transform")){let o=pi("transform","translate"),i=o.find(l=>String(l)===n[1]),a=o.find(l=>String(l)===n[2]);if(i!==void 0&&a!==void 0)return{family:"transform",subproperty:"translate",step:i,axisSteps:{x:i,y:a}}}let r=[];for(let o of t?[t]:Bi)for(let i of Vs(o))for(let a of pi(o,i))al(o,a,i)===e&&r.push({family:o,subproperty:i,step:a});if(r.length>1)throw new Error("Ambiguous omnidial token; include its family (for example stack or grid)");if(!r.length)throw new Error("Unknown omnidial token; discover available tokens or use an explicit custom property/value");return r[0]}function Du(e,t,n,r){let o=e.ownerDocument.defaultView.getComputedStyle(e),i=Ac(t,r),a=Wi(t,n,r),l=Rc(t),s=$c(t,r,n),d=t==="border"&&!ui(t,r)&&typeof n=="number"&&n>0?Lc(r):null,c={family:t,subproperty:Fc(t,r),step:n},p=[{property:i,original:o.getPropertyValue(i).trim()||"0px",modified:a,token:al(t,n,r),sticker:c}];l&&p.unshift({property:"display",original:o.getPropertyValue("display").trim()||"block",modified:l,token:l,sticker:c});for(let u of s)p.push({property:u.property,original:o.getPropertyValue(u.property).trim(),modified:u.value,token:u.token,sticker:c});if(d){let u=o.getPropertyValue(d).trim();(!u||u==="none")&&p.push({property:d,original:u||"none",modified:"solid",token:al(t,n,r),sticker:c})}return{alreadyApplied:Mc(t,n,r,u=>o.getPropertyValue(u)),changes:p}}function Hu(e,t,n){let r=e.ownerDocument.defaultView.getComputedStyle(e),o="translate",i=`${Number(t)*4}px ${Number(n)*4}px`,a={family:"transform",subproperty:"translate",step:t,axisSteps:{x:t,y:n}};return{alreadyApplied:r.getPropertyValue(o).trim()===i,changes:[{property:o,original:r.getPropertyValue(o).trim()||"none",modified:i,token:`translate-x-${t}-y-${n}`,sticker:a}]}}function ty(e,t){for(let n of t.changes)it(e,n.property,n.modified)}var ny=new Set(["text","transform","opacity"]),ry=new Set(["padding","margin","border","radius","color"]);function oy(e){return e instanceof SVGSVGElement&&!(e.parentElement instanceof SVGElement)}function iy(e){return e!=="text-align"}function Il(e,t,n){return jr(e)?e instanceof HTMLElement?!0:t==="text"&&!iy(n)?!1:ny.has(t)||oy(e)&&ry.has(t):!1}function $a(e){return[...new Set([...e?.annotations.flatMap(t=>t.linkedSelector?[t.linkedSelector]:[])??[],...e?.styleModifications.map(t=>t.selector)??[],...e?.textModifications.map(t=>t.selector)??[]])]}function ay(e,t){return Object.keys(t).filter(n=>e[n]!==void 0&&e[n]!==t[n])}function Nu(e,t){return Object.keys(e).length===Object.keys(t).length&&Object.keys(t).every(n=>e[n]===t[n])}function Gs(e,t,n,r){let o={...e};for(let i of r){if(n[i]===void 0){delete o[i];continue}o[i]=t[i]??e[i]??n[i]}return o}function ly(e){let t=e.ownerDocument.defaultView.getComputedStyle(e),n=Array.from(t).filter(i=>!i.startsWith("--")).map(i=>`${i}:${t.getPropertyValue(i)}`).join(";"),r=e.outerHTML+n,o=2166136261;for(let i=0;i<r.length;i++)o=Math.imul(o^r.charCodeAt(i),16777619);return`target-v2:${(o>>>0).toString(16)}`}var lr=()=>location.origin+location.pathname;function kl(e){let t=document.querySelectorAll(e),n=t[0];if(t.length!==1||!(n instanceof HTMLElement||n instanceof SVGElement)||n.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-canvas-block]"))throw new Error("Target must resolve to exactly one app element");if(n.matches("input,textarea,select,[contenteditable],script,style")||n.closest("[data-private], [data-sensitive]"))throw new Error("Private/editable controls are outside the peer preview");return n}var Ou=class{constructor(){this.sources={},this.changed=[],this.container=document.createElement("div"),this.container.dataset.popmeltPeerSurface="",this.container.setAttribute("aria-hidden","true"),this.container.style.cssText="position:fixed;left:-100000px;top:0;pointer-events:none;",document.body.append(this.container),this.surface=new Gg(this.container)}async render(e,t,n,r=!1){if(t.domModifications.length||t.spacingTokenChanges.length)throw new Error("Independent previews do not yet support staged structure or spacing-token edits; your draft is preserved");let o=e.state??pl,i=new Set([...n?[n]:[],...$a(o)]),a=new Map;for(let c of i)a.set(c,kl(c));let l=new Map;for(let c of t.textModifications){let p=document.querySelector(c.selector);p&&l.set(p,[...l.get(p)??[],c])}let s=Vg({root:document.body,targets:a,revision:lr(),width:innerWidth,height:innerHeight,cleanClone:(c,p)=>{if(!r){qm(c,p);for(let u of l.get(c)??[]){let h=p;for(let m of u.textNodePath)h=h?.childNodes[m];h?.nodeType===Node.TEXT_NODE&&(h.nodeValue=u.original)}}}}),d=Qg(e.identity.id,e.identity.id);if(d.revision=e.revision,r||(d.artifacts=o.styleModifications.flatMap(c=>c.changes.map(p=>({kind:"style",id:c.selector+p.property,targetKey:c.selector,property:p.property,value:p.modified})))),!await this.surface.render(s,d,c=>{this.sources=Object.fromEntries([...i].map(p=>[p,ly(c.querySelector(`[data-popmelt-preview-target="${CSS.escape(p)}"]`))])),this.changed=ay(e.basis??{},this.sources)}))throw new Error("Preview superseded or unavailable");return this.surface.frame.contentWindow?.scrollTo(scrollX,scrollY),s.warnings}async execute(e,t){let{action:n}=e,r=structuredClone(e.peer);if(n.type==="prepare-send"){if(!$a(r.state).length)throw new Error("There are no peer changes to send");if(await this.render(r,t),!e.observedSources||Object.keys(this.sources).some(s=>e.observedSources[s]!==this.sources[s]))throw new Error("Source changed since the last preview. Take another look, then send again.");return this.changed.length&&r.revision++,r.basis={...this.sources},delete r.pendingRevision,{peer:r,sources:this.sources}}if(n.type==="check-source"){let s={...r,state:{...structuredClone(pl),annotations:Object.keys(n.sources).map((d,c)=>({id:`source-${c}`,type:"text",text:"",points:[],strokeWidth:1,color:r.color,timestamp:0,linkedSelector:d}))}};if(await this.render(s,t),!Nu(n.sources,this.sources))throw new Error("Source changed since Send. Preview the current source and send again.");return{peer:r,evidence:{status:"source-current"}}}if(n.type==="tokens")return{peer:r,evidence:Zg(n.family,n.subproperty)};let o=r.state??{...structuredClone(pl),isAnnotating:!0,activeColor:r.color},i=o,a,l=s=>{i=Lm(i,s)};if(n.type==="send")throw new Error("Send requires the implementation bridge");if(n.type==="rebase")await this.render(r,t),r.basis={...this.sources},r.revision++,delete r.pendingRevision,a={status:"rebased",note:"Draft preserved against current source; Send requires a new approval if in Suggest."};else if(n.type==="undo"||n.type==="redo"){l({type:n.type==="undo"?"UNDO":"REDO"}),await this.render({...r,state:i},t);let s=[...new Set([...$a(o),...$a(i)])].filter(d=>{let c=p=>JSON.stringify([p.annotations.filter(u=>u.linkedSelector===d),p.styleModifications.filter(u=>u.selector===d)]);return c(o)!==c(i)});r.basis=Gs(r.basis??{},e.observedSources??{},this.sources,s)}else if(n.type==="attention"&&!n.selector)r.attention=null;else if(n.type==="clear"){let s=n.kind!=="style"&&o.annotations.some(c=>c.linkedSelector===n.selector),d=n.kind!=="comment"&&o.styleModifications.some(c=>c.selector===n.selector);if(!s&&!d)return{peer:r,evidence:{status:"nothing-to-clear"}};i={...o,annotations:n.kind==="style"?o.annotations:o.annotations.filter(c=>c.linkedSelector!==n.selector),styleModifications:n.kind==="comment"?o.styleModifications:o.styleModifications.filter(c=>c.selector!==n.selector),undoStack:[...o.undoStack,{annotations:o.annotations,styleModifications:o.styleModifications,textModifications:o.textModifications,domModifications:o.domModifications,spacingTokenChanges:o.spacingTokenChanges,spacingTokenMods:o.spacingTokenMods}],redoStack:[]},await this.render({...r,state:i},t),r.basis=Gs(r.basis??{},e.observedSources??{},this.sources,[n.selector])}else if("selector"in n&&n.selector){let s=kl(n.selector),d=vn(s),c=n.selector;if(n.type==="inspect"){let p=await this.render(r,t,c,n.plane==="host");a={...this.surface.inspect(c,n.properties??[]),element:d,warnings:p,view:n.plane??"own",url:lr(),changedSourceTargets:n.plane==="host"?void 0:this.changed}}else if(n.type==="style")if("token"in n){let p=ey(n.token,n.family);if(!Il(s,p.family,p.subproperty))throw new Error("This omnidial token does not support the target");await this.render(r,t,c);let u=this.surface.frame.contentDocument?.querySelector(c);if(!u)throw new Error("Could not inspect original style");let h=p.axisSteps?Hu(u,p.axisSteps.x,p.axisSteps.y):Du(u,p.family,p.step,p.subproperty);h.alreadyApplied||l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:h.changes}}),a={token:n.token,selection:p,alreadyApplied:h.alreadyApplied}}else{if(!CSS.supports(n.property,n.value))throw new Error("Unsupported CSS property/value");await this.render(r,t,c);let p=this.surface.inspect(c,[n.property])?.styles[n.property];if(p===void 0)throw new Error("Could not inspect original style");l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:[{property:n.property,original:p,modified:n.value}]}})}else if(n.type==="comment"){await this.render(r,t,c);let p=s.getBoundingClientRect();l({type:"ADD_TEXT",payload:{id:`peer-note-${e.id}`,point:{x:p.x+scrollX,y:p.y+scrollY-26},text:n.text,linkedSelector:c,elements:[{...d,selector:c}]}})}r.attention=null,(n.type==="comment"||n.type==="style")&&(r.basis=Gs(r.basis??{},e.observedSources??{},this.sources,[c]))}if(i!==o){if(i.annotations.length+i.styleModifications.length>100)throw new Error("Peer draft is full; submit or undo before adding more");i={...i,undoStack:i.undoStack.slice(-50),redoStack:i.redoStack.slice(-50)},r.state=i,r.revision++,r.url=lr(),delete r.pendingRevision}return{peer:r,evidence:a,...["inspect","style","comment","clear","undo","redo","rebase"].includes(n.type)&&!(n.type==="inspect"&&n.plane==="host")?{sources:this.sources}:{}}}dispose(){this.surface.dispose(),this.container.remove()}};async function sy(e,t,n){let r=!0,o,i=new Set,a=async c=>{let p=new AbortController;i.add(p);let u=setTimeout(()=>p.abort(),1500);try{return await e(c,p.signal)}catch{return!1}finally{clearTimeout(u),i.delete(p)}},l=()=>{r=!1,clearTimeout(o);for(let c of i)c.abort()},s=()=>{l(),a("finish")},d=async()=>{if(!r)return;let c=await a("renew");r&&c&&(o=setTimeout(()=>{d()},1e3))};n.addEventListener("abort",s,{once:!0});try{if(n.aborted)throw new Error("Canvas disconnected before action");let c=await a("start");if(n.aborted)throw new Error("Canvas disconnected before action");return r&&c&&(o=setTimeout(()=>{d()},1e3)),await t()}finally{l(),n.removeEventListener("abort",s),await a("finish")}}function dy(e){let t=`popmelt-peer-seen:${e}`,[n,r]=P({key:"",revisions:{}});return O(()=>{let o={};try{let i=JSON.parse(localStorage.getItem(t)??"{}");i&&typeof i=="object"&&!Array.isArray(i)&&(o=Object.fromEntries(Object.entries(i).filter(([,a])=>Number.isSafeInteger(a)&&a>=0)))}catch{}r({key:t,revisions:o})},[t]),{markSeen:J((o,i)=>{r(a=>{if(a.key!==t||(a.revisions[o]??0)>=i)return a;let l={key:t,revisions:{...a.revisions,[o]:i}};try{localStorage.setItem(t,JSON.stringify(l.revisions))}catch{}return l})},[t]),isUnseen:(o,i)=>n.key===t&&i>(n.revisions[o]??0)}}function cy(e,t){let n,r=l=>(l instanceof Element?l:l.parentElement)?.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-root], popmelt-root"),o=()=>{n===void 0&&(n=setTimeout(()=>{n=void 0,t()},400))},i=new MutationObserver(l=>{document.hidden||!e.length||l.some(s=>{if(r(s.target)||s.type==="childList"&&[...s.addedNodes,...s.removedNodes].every(c=>r(c)))return!1;let d=s.target instanceof Element?s.target:s.target.parentElement;return d?.closest("style,head")?!0:e.some(c=>{let p=document.querySelector(c);return!p||p.contains(s.target)||d?.contains(p)})})&&o()});i.observe(document.documentElement,{subtree:!0,attributes:!0,childList:!0,characterData:!0}),window.addEventListener("resize",o);let a=()=>{document.hidden||o()};return document.addEventListener("visibilitychange",a),()=>{i.disconnect(),clearTimeout(n),window.removeEventListener("resize",o),document.removeEventListener("visibilitychange",a)}}function _u(e){if(!e)return 0;let t=Vh(e.annotations);return yc({annotations:e.annotations.filter(n=>!n.captured&&!t.has(n)),styleModifications:e.styleModifications.filter(n=>!n.captured),textModifications:e.textModifications.filter(n=>!n.captured)}).count}function uy(e,t,n,r,o){let[i,a]=P([]),[l,s]=P([]),d=Ah(l,e&&r.isAnnotating),c=Mh(e&&r.isAnnotating),{viewedId:p,isPeeking:u}=c,[h,m]=P(),[g,x]=P(),[S,z]=P([]),H=B(null),{markSeen:w,isUnseen:j}=dy(n),Z=we(()=>new Map(i.map(U=>[U.identity.id,_u(U.state)])),[i]),{annotations:k,styleModifications:V,textModifications:N}=r,Y=we(()=>_u({annotations:k,styleModifications:V,textModifications:N}),[k,V,N]),[q,ie]=P(null),I=B(null),Q=B({human:r,settings:o});Q.current={human:r,settings:o};let $=B({clientId:crypto.randomUUID()}),_=B(async()=>{throw new Error("Canvas is disconnected")}),R=e?i.find(U=>U.identity.id===p):void 0,D=i.find(U=>U.identity.id===c.selectedId)?.state,L=we(()=>Rh(D),[D]);O(()=>{if(!e||!n)return;$.current.token||($.current={clientId:crypto.randomUUID()});let U=!1,fe,me=-1,K=-1,Te=new AbortController,Me="",Ee=!1,Ge=new Ou,X=new Map,Ne=Pe=>{U||typeof Pe.presenceVersion!="number"||Pe.presenceVersion<=K||!Array.isArray(Pe.presence)||(K=Pe.presenceVersion,s(Pe.presence))},ve=async(Pe,ze={},ce=AbortSignal.any([Te.signal,AbortSignal.timeout(5e4)]))=>{let ot=$.current.token,at=await Yt(`${t}/peers/${Pe}`,{method:"POST",headers:{"Content-Type":"application/json","X-Popmelt-Project-Id":n},body:JSON.stringify({...$.current,...ze}),signal:ce}),Be=await at.json();if(Pe!=="host"&&ot!==$.current.token)throw new Error("Canvas session changed during request");if(!at.ok||Be.error)throw new Error(Be.error??`Peer request failed (${at.status})`);return Be};_.current=ve;async function _e(Pe){if(Pe.url&&Pe.url!==lr())throw new Error("Canvas navigated before the operation could run");if(Pe.action.type!=="send"){let kt=sm(Pe.action);return kt?(kl(kt.selector),sy(async(st,Xe)=>{let Lt=await ve("activity",{id:Pe.id,phase:st},Xe);return Ne(Lt),Lt.accepted===!0},()=>Ge.execute(Pe,Q.current.human),Te.signal)):Ge.execute(Pe,Q.current.human)}if(!Pe.grant)throw new Error("No host-approved Send grant");let ze=structuredClone(Pe.peer);if(ze.url!==lr())throw new Error("Return to the proposal\u2019s page before sending");let ce=ze.state;if(!ce||!ce.annotations.length&&!ce.styleModifications.length)throw new Error("There are no peer changes to send");await Ge.render(ze,Q.current.human);let ot={...Ge.sources};if(!Pe.observedSources||Object.keys(ot).some(kt=>Pe.observedSources[kt]!==ot[kt]))throw new Error("Source changed since the last preview. Take another look, then send again.");let at=Ge.surface.frame.contentDocument;if(!at)throw new Error("Peer preview is unavailable");let[Be]=await Oi(at.body,null,[],{viewportOnly:!0});if(!Be)throw new Error("Could not capture the peer preview");if(await Ge.render(ze,Q.current.human),!Nu(ot,Ge.sources))throw new Error("Source changed while preparing Send. Take another look, then send again.");await ve("source",{grant:Pe.grant,sources:ot});let Se=cc(ce.annotations,ce.styleModifications,void 0,void 0,ce.textModifications),{provider:Je,model:Ft,agentSettings:vt}=Q.current.settings,$t=await mu(Be,JSON.stringify(Se),t,ze.color,Je,Ft,void 0,void 0,vt,void 0,void 0,void 0,Pe.grant);return ze.state={...structuredClone(pl),isAnnotating:!0,activeColor:ze.color},ze.revision++,ze.basis={},delete ze.pendingRevision,ze.lastJob={jobId:$t.jobId,threadId:$t.threadId},{peer:ze,evidence:{status:"submitted",...$t}}}async function qe(){try{if(!$.current.token||Me!==lr()){let ze=await ve("host",{url:lr()});if(U)return;$.current.token=String(ze.token),Me=lr()}let Pe=await ve("poll",{version:me,presenceVersion:K});if(U)return;Ne(Pe),Pe.peers&&(a(Pe.peers),Ee=Pe.peers.length>0,me=Number(Pe.version));for(let ze of Pe.requests){let ce=X.get(ze.id);if(!ce){try{ce=await _e(ze)}catch(ot){ce={error:ot instanceof Error?ot.message:String(ot)}}X.set(ze.id,ce),X.size>100&&X.delete(X.keys().next().value)}await ve("response",{id:ze.id,result:ce})}}catch(Pe){!U&&Pe instanceof Error&&Pe.message.includes("Host capability")&&($.current.token=void 0,me=-1,K=-1,U||s([]))}finally{U||(fe=setTimeout(()=>{qe()},document.hidden||!Ee?2e3:600))}}return qe(),()=>{U=!0,Te.abort(),clearTimeout(fe),Ge.dispose(),a([]),s([]),_.current=async()=>{throw new Error("Canvas is disconnected")}}},[e,t,n]),O(()=>{if(x(void 0),z([]),H.current=null,!R||!r.isAnnotating||!I.current){ie(null);return}let U=new Ou;I.current.append(U.container),ie(null),U.container.removeAttribute("aria-hidden"),U.container.style.cssText="position:absolute;inset:0;pointer-events:none;";let fe=!1;R.url&&R.url!==lr()&&x("This draft belongs to another page. Return to it to preview.");let me=!1,K=!1,Te=()=>{if(!fe){if(me){K=!0;return}me=!0,U.render(R,Q.current.human).then(()=>{fe||(x(void 0),z(U.changed),H.current={id:R.identity.id,revision:R.revision,values:{...U.sources}},ie(U.surface.frame),w(R.identity.id,R.revision))}).catch(X=>{fe||(H.current=null,ie(null),x(X.message))}).finally(()=>{me=!1,K&&(K=!1,Te())})}},Me=!R.url||R.url===lr();Me&&Te();let Ee=Me?cy($a(R.state),Te):()=>{},Ge=()=>U.surface.frame.contentWindow?.scrollTo(scrollX,scrollY);return window.addEventListener("scroll",Ge,{passive:!0}),()=>{fe=!0,Ee(),window.removeEventListener("scroll",Ge),U.dispose()}},[R,r.isAnnotating,w]);let E=async U=>{try{return await U(),m(void 0),!0}catch(fe){return m(fe instanceof Error?fe.message:String(fe)),!1}},te=e&&i.length?{peers:[{identity:{id:"host",name:"You",kind:"human",relationship:"host"},permission:"direct",color:r.activeColor,stagedCount:Y},...i.map(U=>({...U,stagedCount:Z.get(U.identity.id)??0,unseenActivity:j(U.identity.id,U.revision)}))],viewedPeerId:p,selectedPeerId:c.selectedId,onPeek:c.peek,onPeekEnd:c.leave,onPreview:U=>{c.select(U),m(void 0)},onPermissionChange:(U,fe)=>E(()=>_.current("permission",{peerId:U,permission:fe}))}:null,re=R?.pendingRevision!==void 0?()=>E(()=>{let U=H.current;if(!U||U.id!==p||U.revision!==R.revision)throw new Error("Wait for this draft\u2019s preview before sending.");return _.current("approve",{peerId:p,revision:R.pendingRevision,sources:U.values})}):void 0,ee=!!(R&&r.isAnnotating),oe=e&&(h??(ee?g:void 0));return O(()=>{if(!ee)return;let U=fe=>{fe.composedPath().some(me=>me instanceof Element&&me.hasAttribute("data-devtools"))||(fe.metaKey||fe.ctrlKey)&&fe.key==="Enter"||(fe.key.length===1||["Backspace","Delete","Enter"].includes(fe.key))&&(fe.preventDefault(),fe.stopPropagation())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[ee]),{toolbar:te,selectedId:c.selectedId,threadAnnotationNumbers:L,activePreview:ee,isPeeking:u,viewed:R,approve:re,overlay:M(ut,{children:[ee&&f("div",{ref:I,"data-devtools":"peer-preview","data-peer-revision":R?.revision,"data-pending-revision":R?.pendingRevision,"data-popmelt-peer-surface":!0,style:{position:"fixed",inset:0,zIndex:1e4,background:"#111",pointerEvents:"auto"}}),d.map(({presence:U,engaged:fe})=>{if(u)return null;let me=i.find(Te=>Te.identity.id===U.peerId);if(!me||U.clientId!==$.current.clientId||U.url!==lr()||ee&&me.identity.id!==p)return null;let K=null;try{K=ee?q?.contentDocument?.querySelector(U.selector)??null:kl(U.selector)}catch{}return f(qc,{element:K,engaged:fe,label:`${me.identity.name} is looking at this element`},`${me.identity.id}:${U.operationId}`)}),!u&&ee&&R&&q?.contentDocument&&f($h,{peer:R,targetDocument:q.contentDocument,onApprove:re?()=>{re()}:void 0}),ee&&R&&p===c.selectedId&&f("div",{"data-devtools":"peer-plane-border","data-plane-owner":R.identity.id,"aria-hidden":"true",style:{position:"fixed",inset:0,border:`2px solid ${R.color}`,boxSizing:"border-box",pointerEvents:"none",zIndex:10002}}),ee&&R&&p===c.selectedId&&f(Lh,{name:R.identity.name,isOwnPlane:R.identity.id==="host",color:R.color,changed:S.length>0}),oe&&f("div",{"data-devtools":"peer-error",role:"status",style:{position:"fixed",bottom:100,right:24,maxWidth:360,padding:12,background:"#222",color:"#ddd",borderRadius:12,fontFamily:Ns,fontSize:12,lineHeight:1.4,zIndex:10002},children:oe})]})}}function py(e,t,n,r,o,i,a){let[l,s]=P(),d=B({navigation:e,selectedId:t});O(()=>{if(!e||!n||l?.navigation===e)return;let c=e.read(),p=o.current,u=!1;if(!c.threadId||c.selectedId!==t){s({navigation:e});return}return i(c.threadId).then(h=>{if(!u){if(p===o.current&&e.read()===c)if(h>=200&&h<300)a(c.threadId);else if(h===403||h===404||h===410)e.rememberThread(t,null);else{s({navigation:e,unresolvedRevision:p});return}s({navigation:e})}}).catch(()=>{u||s({navigation:e,unresolvedRevision:p})}),()=>{u=!0}},[e,t,n,l,o,i,a]),O(()=>{let c=d.current.navigation!==e||d.current.selectedId!==t;d.current={navigation:e,selectedId:t},!(!e||l?.navigation!==e||c)&&(l.unresolvedRevision===o.current&&!r||e.rememberThread(t,r))},[e,t,r,l,o])}var fy=hl(()=>import("./ParticipantRuntime-AKVKVNO2.mjs")),hy=hl(()=>import("./PreviewRuntime-JAZLAGQE.mjs"));function my({children:e,projectId:t,adapters:n,multiplayer:r=!1}){let[o,i]=P(!1);if(O(()=>{i(!0)},[]),!o)return null;let a=window.__POPMELT_PARTICIPANTS__;if(!r)return gu()?null:a?f("p",{role:"status","data-devtools":"participant-disabled",children:"Multiplayer is disabled. Enable the multiplayer option in your Popmelt integration to use this participant page."}):e;if(a)try{ug(a,t)}catch(l){return f("p",{role:"alert","data-devtools":"participant-error",children:l.message})}return gu()?a?f(ml,{fallback:null,children:f(hy,{config:a,adapters:n})}):null:a?f(ml,{fallback:null,children:f(fy,{config:a,children:Ig(e,{bridgeUrl:a.url,projectId:a.projectId})},a.projectId)}):e}function gy(e,t,n,r){let o=B(e);o.current=e;let[i,a]=P([]),l=B(null),[s,d]=P(null),[c,p]=P(null),u=i.filter(x=>x.scope===e),h=x=>a(S=>S.filter(z=>z.id!==x)),m=(x,S)=>{let z=Symbol(x);p(null);let H=t(x).then(()=>!0,()=>(o.current===e&&(S(),p({scope:e,message:"Could not dismiss thread. Please try again."})),h(z),!1));a(w=>[...w.filter(j=>j.scope===e),{id:z,threadId:x,rollback:S,saved:H,scope:e,undoHead:r}])},g=async()=>{let x=u.at(-1);if(!(!x||l.current===e)){l.current=e,d(e),p(null);try{if(!await x.saved||o.current!==e||(await n(x.threadId),o.current!==e))return;x.rollback(),h(x.id)}catch{o.current===e&&p({scope:e,message:"Could not restore thread. Try Undo again."})}finally{l.current===e&&(l.current=null,d(null))}}};return{dismiss:m,undo:g,tryUndo:()=>{let x=u.at(-1);return!x||x.undoHead!==r?!1:(g(),!0)},busy:s===e,count:u.length,error:c?.scope===e?c.message:null}}function yy({enabled:e,active:t,configuration:n=!0,adapters:r}){let[o,i]=P(!1),[a,l]=P(null),s=we(()=>pg(),[]),{recognition:d,selector:c,root:p,observe:u,store:h,imageHasher:m,onError:g}=typeof n=="object"?n:{},x=r.some(w=>w.surfaceKind==="image"||w.id==="see:image"),S=e&&n!==!1&&!x,z=t||o,H=z?d:void 0;return O(()=>{e?t&&i(!0):i(!1)},[e,t]),O(()=>{if(!S)return;let w=fg({recognition:H?{cacheKey:H.cacheKey,configurationKey:H.configurationKey,detect:j=>H.detect(j),reconcile:(...j)=>H.reconcile(...j)}:void 0,hydrateOnly:!z,selector:c,root:p,observe:u,store:h??s,imageHasher:m,onError:g});return l(w),()=>{l(null),w.destroy()}},[S,H,z,c,p,u,h,s,m,g]),we(()=>S&&a?[a,...r]:r,[S,a,r])}function vy({enabled:e,configuration:t=!0,adapters:n}){let[r,o]=P(null),i=we(()=>hg(),[]),{segmentation:a,tracking:l,selector:s,root:d,observe:c,store:p,onError:u}=typeof t=="object"?t:{},h=n.some(g=>g.surfaceKind==="video"||g.id==="see:video"),m=e&&t!==!1&&!h;return O(()=>{if(!m)return;let g=mg({tracking:l,segmentation:a,selector:s,root:d,observe:c,store:p??i,onError:u});return o(g),()=>{o(null),g.destroy()}},[m,l,a,s,d,c,p,i,u]),we(()=>m&&r?[r,...n]:n,[m,r,n])}function Fu(e,t){return JSON.stringify([e,t.adapter,t.key])}async function Wu(e,t,n,r){for(let o of t){if(!o.target)continue;let i=Fu(n,o.target);if(!r.has(i))try{r.set(i,await e.captureFeedback(o.target))}catch{r.set(i,null)}}}function by(e,t,n){let r=new Map;for(let o of e.annotations){let i=t.find(l=>l.id===o.id),a=(i?.groupId?t.filter(l=>l.groupId===i.groupId):t.filter(l=>l.id===o.id)).flatMap(l=>n.get(l.id)??[]);a.length&&r.set(o.id,a)}return r}function xy(e,t,n,r){for(let o of e.annotations){if(!o.target)continue;let i=n.get(Fu(o.pathname||r,o.target));if(!i){o.subjectFeedback={warning:"Live object unavailable; the following object context is the draft-time snapshot, not a refreshed detection. No object crop is attached."};continue}if(o.elements=[i.elementInfo],o.subjectFeedback=i.warning?{warning:i.warning}:void 0,i.crop){let a=t.get(o.id)??[];o.subjectFeedback={...o.subjectFeedback,cropImageIndex:a.length},t.set(o.id,[...a,i.crop])}}}function wy(e){let t=e?.requestItems?.flatMap(r=>r.kind==="annotation"&&r.text.trim()?[r.text.trim()]:[]);if(t?.length)return t.join("; ");let n=e?.requestItems?.flatMap(r=>r.kind==="changes"?[`${r.elementLabel} [${r.changes.join(", ")}]`]:[]);return n?.length?n.join("; "):e?.requestText?.trim()||void 0}function Sy(e,t){if(!e?.frames?.length)return[];let n=new Map;for(let r of e.steps){let o=r.visuals?.afterFrameId;o&&!n.has(o)&&n.set(o,r.action?.label?`After ${r.action.label}`:"Resulting state")}return e.frames.flatMap((r,o)=>{let i=t[r.imageIndex];return i?[{id:r.id,imageIndex:r.imageIndex,label:o===0?"Initial state":n.get(r.id)??"State",url:i}]:[]})}function Bu(e){let t=e.instruction?.trim();return t?e.attachments?.some(n=>n.name?.trim()===t)?null:t:null}function Iy(e,t){let n=e?.tagName?.toLowerCase(),r=e?.id?`#${e.id}`:"",o=e?.className?`.${e.className.trim().split(/\s+/).slice(0,2).join(".")}`:"",i=n?`${n}${r}${o}`:t;return e?.reactComponent?`<${e.reactComponent}> ${i}`:i}function ky(e){let t=e.elements?.[0]?.reactComponent||e.elements?.[0]?.tagName||e.linkedSelector,n=e.type&&e.type!=="annotation"?`${e.type} annotation`:"Annotation";return t?`${n} on ${t}`:n}function Ty(e){let t=e.annotations.map(o=>{let i=o.interactionEpisode?.steps.length??0;return{kind:"annotation",annotationId:o.id,pathname:o.pathname,text:Bu(o)??ky(o),...i>0?{interactionEpisodeStepCount:i}:{}}}),n=new Map,r=o=>{let i=`${o.pathname??""}:${o.durableSelector??o.selector}`,a=n.get(i);if(a){a.changes.push(o.text),o.annotationNumber!==void 0&&(a.annotationNumber===void 0||o.annotationNumber<a.annotationNumber)&&(a.annotationNumber=o.annotationNumber);return}let l={kind:"changes",elementKey:i,elementLabel:Iy(o.element,o.selector),...o.annotationNumber!==void 0?{annotationNumber:o.annotationNumber}:{},pathname:o.pathname,changes:[o.text]};n.set(i,l),t.push(l)};for(let o of e.styleModifications??[])for(let i of o.changes)r({...o,text:`${i.property}: ${i.original||"unset"} \u2192 ${i.modified||"unset"}${i.token?` (${i.token})`:""}`});for(let o of e.textModifications??[])r({...o,text:`Text: ${o.original||"empty"} \u2192 ${o.modified||"empty"}`});for(let o of e.domModifications??[])r({...o,text:o.operation==="copy"?"Copied element":"Moved element"});return e.spacingTokenChanges?.length&&t.push({kind:"changes",elementKey:"spacing-tokens",elementLabel:"Spacing tokens",changes:e.spacingTokenChanges.map(o=>`${o.tokenName}: ${o.originalPx}px \u2192 ${o.newPx}px`)}),t}function Ey(e){let t=e.annotations.flatMap(r=>{let o=Bu(r);return o?[{instruction:o,pathname:r.pathname}]:[]});if(t.length===0)return;if(new Set(t.map(r=>r.pathname).filter(Boolean)).size<=1)return t.map(r=>r.instruction).join(`
4
+ `}catch{d.add("An inaccessible stylesheet was omitted")}return d.add("Static snapshot: no scripts, external assets, event handlers or application runtime"),{revision:n,html:e.tagName==="BODY"?a.innerHTML:a.outerHTML,...e.tagName==="BODY"?{bodyAttributes:Object.fromEntries([...a.attributes].map(u=>[u.name,u.value]))}:{},css:p,width:r,height:o,warnings:[...d]}}function zu(e,t){let n=[...e.querySelectorAll(`[${Sl}]`)].filter(r=>r.getAttribute(Sl)===t);return n.length===1?n[0]:null}var Gg=class{constructor(e){this.generation=0,this.cancelPending=null,this.current=null,this.disposed=!1,this.frame=e.ownerDocument.createElement("iframe"),this.frame.setAttribute("sandbox","allow-same-origin"),this.frame.title="Peer plane preview",this.frame.style.cssText="border:0;display:block;pointer-events:none;",this.frame.tabIndex=-1,e.append(this.frame)}async render(e,t,n){if(this.disposed)throw new Error("Preview surface was disposed");this.cancelPending?.();let r=++this.generation;this.current=null,this.frame.width=String(e.width),this.frame.height=String(e.height);let o=this.frame.ownerDocument.implementation.createHTMLDocument("Peer preview"),i=o.createElement("meta");i.httpEquiv="Content-Security-Policy",i.content="default-src 'none'; style-src 'unsafe-inline'; form-action 'none'; base-uri 'none'; script-src 'none'",o.head.prepend(i);let a=o.createElement("style");a.textContent=e.css.replace(/<\/style/gi,"<\\/style"),o.head.append(a),o.body.innerHTML=e.html;for(let[s,d]of Object.entries(e.bodyAttributes??{}))o.body.setAttribute(s,d);let l=o.createElement("style");return l.textContent="*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}",o.head.append(l),o.documentElement.dataset.previewGeneration=String(r),new Promise(s=>{let d=h=>{clearTimeout(u),this.frame.removeEventListener("load",p),this.cancelPending===c&&(this.cancelPending=null),s(h)},c=()=>d(!1),p=()=>{if(r!==this.generation||this.frame.contentDocument?.documentElement.dataset.previewGeneration!==String(r))return;let h=this.frame.contentDocument;n?.(h);for(let m of t.artifacts)m.kind==="style"&&zu(h,m.targetKey)?.style.setProperty(m.property,m.value,"important");this.current={baseline:e,plane:{...t}},d(!0)},u=setTimeout(c,5e3);this.cancelPending=c,this.frame.addEventListener("load",p),queueMicrotask(()=>{!this.disposed&&r===this.generation&&(this.frame.srcdoc="<!doctype html>"+o.documentElement.outerHTML)})})}inspect(e,t){let n=this.current,r=this.frame.contentDocument;if(!n||!r)return null;let o=zu(r,e);if(!o)return null;let i=this.frame.contentWindow.getComputedStyle(o),a=o.getBoundingClientRect();return{planeId:n.plane.id,planeRevision:n.plane.revision,sourceRevision:n.baseline.revision,targetKey:e,styles:Object.fromEntries(t.map(l=>[l,i.getPropertyValue(l)])),rect:{x:a.x,y:a.y,width:a.width,height:a.height}}}dispose(){this.disposed=!0,++this.generation,this.cancelPending?.(),this.current=null,this.frame.remove()}};function Qg(e,t){return{id:e,ownerId:t,revision:0,artifacts:[],undo:[],redo:[],attention:null}}function Vs(e){return ll(e).flatMap(t=>t==="color"?[...Wc]:[t])}function Zg(e,t){if(e===void 0)return{families:Bi.map(n=>({family:n,label:Cs(n)}))};if(!Bi.includes(e))throw new Error("Unknown omnidial family");if(!t)return{family:e,subproperties:Vs(e)};if(!Vs(e).includes(t))throw new Error("Unknown omnidial subproperty");return{family:e,subproperty:t,...e==="transform"&&t==="translate"?{composedToken:"translate-x-<xStep>-y-<yStep>",axisSteps:pi(e,t)}:{},tokens:pi(e,t).map(n=>({token:al(e,n,t),value:Wi(e,n,t)}))}}function ey(e,t){if(t!==void 0&&!Bi.includes(t))throw new Error("Unknown omnidial family");let n=/^translate-x-(-?\d+)-y-(-?\d+)$/.exec(e);if(n&&(!t||t==="transform")){let o=pi("transform","translate"),i=o.find(l=>String(l)===n[1]),a=o.find(l=>String(l)===n[2]);if(i!==void 0&&a!==void 0)return{family:"transform",subproperty:"translate",step:i,axisSteps:{x:i,y:a}}}let r=[];for(let o of t?[t]:Bi)for(let i of Vs(o))for(let a of pi(o,i))al(o,a,i)===e&&r.push({family:o,subproperty:i,step:a});if(r.length>1)throw new Error("Ambiguous omnidial token; include its family (for example stack or grid)");if(!r.length)throw new Error("Unknown omnidial token; discover available tokens or use an explicit custom property/value");return r[0]}function Du(e,t,n,r){let o=e.ownerDocument.defaultView.getComputedStyle(e),i=Ac(t,r),a=Wi(t,n,r),l=Rc(t),s=$c(t,r,n),d=t==="border"&&!ui(t,r)&&typeof n=="number"&&n>0?Lc(r):null,c={family:t,subproperty:Fc(t,r),step:n},p=[{property:i,original:o.getPropertyValue(i).trim()||"0px",modified:a,token:al(t,n,r),sticker:c}];l&&p.unshift({property:"display",original:o.getPropertyValue("display").trim()||"block",modified:l,token:l,sticker:c});for(let u of s)p.push({property:u.property,original:o.getPropertyValue(u.property).trim(),modified:u.value,token:u.token,sticker:c});if(d){let u=o.getPropertyValue(d).trim();(!u||u==="none")&&p.push({property:d,original:u||"none",modified:"solid",token:al(t,n,r),sticker:c})}return{alreadyApplied:Mc(t,n,r,u=>o.getPropertyValue(u)),changes:p}}function Hu(e,t,n){let r=e.ownerDocument.defaultView.getComputedStyle(e),o="translate",i=`${Number(t)*4}px ${Number(n)*4}px`,a={family:"transform",subproperty:"translate",step:t,axisSteps:{x:t,y:n}};return{alreadyApplied:r.getPropertyValue(o).trim()===i,changes:[{property:o,original:r.getPropertyValue(o).trim()||"none",modified:i,token:`translate-x-${t}-y-${n}`,sticker:a}]}}function ty(e,t){for(let n of t.changes)it(e,n.property,n.modified)}var ny=new Set(["text","transform","opacity"]),ry=new Set(["padding","margin","border","radius","color"]);function oy(e){return e instanceof SVGSVGElement&&!(e.parentElement instanceof SVGElement)}function iy(e){return e!=="text-align"}function Il(e,t,n){return jr(e)?e instanceof HTMLElement?!0:t==="text"&&!iy(n)?!1:ny.has(t)||oy(e)&&ry.has(t):!1}function $a(e){return[...new Set([...e?.annotations.flatMap(t=>t.linkedSelector?[t.linkedSelector]:[])??[],...e?.styleModifications.map(t=>t.selector)??[],...e?.textModifications.map(t=>t.selector)??[]])]}function ay(e,t){return Object.keys(t).filter(n=>e[n]!==void 0&&e[n]!==t[n])}function Nu(e,t){return Object.keys(e).length===Object.keys(t).length&&Object.keys(t).every(n=>e[n]===t[n])}function Gs(e,t,n,r){let o={...e};for(let i of r){if(n[i]===void 0){delete o[i];continue}o[i]=t[i]??e[i]??n[i]}return o}function ly(e){let t=e.ownerDocument.defaultView.getComputedStyle(e),n=Array.from(t).filter(i=>!i.startsWith("--")).map(i=>`${i}:${t.getPropertyValue(i)}`).join(";"),r=e.outerHTML+n,o=2166136261;for(let i=0;i<r.length;i++)o=Math.imul(o^r.charCodeAt(i),16777619);return`target-v2:${(o>>>0).toString(16)}`}var lr=()=>location.origin+location.pathname;function kl(e){let t=document.querySelectorAll(e),n=t[0];if(t.length!==1||!(n instanceof HTMLElement||n instanceof SVGElement)||n.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-canvas-block]"))throw new Error("Target must resolve to exactly one app element");if(n.matches("input,textarea,select,[contenteditable],script,style")||n.closest("[data-private], [data-sensitive]"))throw new Error("Private/editable controls are outside the peer preview");return n}var Ou=class{constructor(){this.sources={},this.changed=[],this.container=document.createElement("div"),this.container.dataset.popmeltPeerSurface="",this.container.setAttribute("aria-hidden","true"),this.container.style.cssText="position:fixed;left:-100000px;top:0;pointer-events:none;",document.body.append(this.container),this.surface=new Gg(this.container)}async render(e,t,n,r=!1){if(t.domModifications.length||t.spacingTokenChanges.length)throw new Error("Independent previews do not yet support staged structure or spacing-token edits; your draft is preserved");let o=e.state??pl,i=new Set([...n?[n]:[],...$a(o)]),a=new Map;for(let c of i)a.set(c,kl(c));let l=new Map;for(let c of t.textModifications){let p=document.querySelector(c.selector);p&&l.set(p,[...l.get(p)??[],c])}let s=Vg({root:document.body,targets:a,revision:lr(),width:innerWidth,height:innerHeight,cleanClone:(c,p)=>{if(!r){qm(c,p);for(let u of l.get(c)??[]){let h=p;for(let m of u.textNodePath)h=h?.childNodes[m];h?.nodeType===Node.TEXT_NODE&&(h.nodeValue=u.original)}}}}),d=Qg(e.identity.id,e.identity.id);if(d.revision=e.revision,r||(d.artifacts=o.styleModifications.flatMap(c=>c.changes.map(p=>({kind:"style",id:c.selector+p.property,targetKey:c.selector,property:p.property,value:p.modified})))),!await this.surface.render(s,d,c=>{this.sources=Object.fromEntries([...i].map(p=>[p,ly(c.querySelector(`[data-popmelt-preview-target="${CSS.escape(p)}"]`))])),this.changed=ay(e.basis??{},this.sources)}))throw new Error("Preview superseded or unavailable");return this.surface.frame.contentWindow?.scrollTo(scrollX,scrollY),s.warnings}async execute(e,t){let{action:n}=e,r=structuredClone(e.peer);if(n.type==="prepare-send"){if(!$a(r.state).length)throw new Error("There are no peer changes to send");if(await this.render(r,t),!e.observedSources||Object.keys(this.sources).some(s=>e.observedSources[s]!==this.sources[s]))throw new Error("Source changed since the last preview. Take another look, then send again.");return this.changed.length&&r.revision++,r.basis={...this.sources},delete r.pendingRevision,{peer:r,sources:this.sources}}if(n.type==="check-source"){let s={...r,state:{...structuredClone(pl),annotations:Object.keys(n.sources).map((d,c)=>({id:`source-${c}`,type:"text",text:"",points:[],strokeWidth:1,color:r.color,timestamp:0,linkedSelector:d}))}};if(await this.render(s,t),!Nu(n.sources,this.sources))throw new Error("Source changed since Send. Preview the current source and send again.");return{peer:r,evidence:{status:"source-current"}}}if(n.type==="tokens")return{peer:r,evidence:Zg(n.family,n.subproperty)};let o=r.state??{...structuredClone(pl),isAnnotating:!0,activeColor:r.color},i=o,a,l=s=>{i=Lm(i,s)};if(n.type==="send")throw new Error("Send requires the implementation bridge");if(n.type==="rebase")await this.render(r,t),r.basis={...this.sources},r.revision++,delete r.pendingRevision,a={status:"rebased",note:"Draft preserved against current source; Send requires a new approval if in Suggest."};else if(n.type==="undo"||n.type==="redo"){l({type:n.type==="undo"?"UNDO":"REDO"}),await this.render({...r,state:i},t);let s=[...new Set([...$a(o),...$a(i)])].filter(d=>{let c=p=>JSON.stringify([p.annotations.filter(u=>u.linkedSelector===d),p.styleModifications.filter(u=>u.selector===d)]);return c(o)!==c(i)});r.basis=Gs(r.basis??{},e.observedSources??{},this.sources,s)}else if(n.type==="attention"&&!n.selector)r.attention=null;else if(n.type==="clear"){let s=n.kind!=="style"&&o.annotations.some(c=>c.linkedSelector===n.selector),d=n.kind!=="comment"&&o.styleModifications.some(c=>c.selector===n.selector);if(!s&&!d)return{peer:r,evidence:{status:"nothing-to-clear"}};i={...o,annotations:n.kind==="style"?o.annotations:o.annotations.filter(c=>c.linkedSelector!==n.selector),styleModifications:n.kind==="comment"?o.styleModifications:o.styleModifications.filter(c=>c.selector!==n.selector),undoStack:[...o.undoStack,{annotations:o.annotations,styleModifications:o.styleModifications,textModifications:o.textModifications,domModifications:o.domModifications,spacingTokenChanges:o.spacingTokenChanges,spacingTokenMods:o.spacingTokenMods}],redoStack:[]},await this.render({...r,state:i},t),r.basis=Gs(r.basis??{},e.observedSources??{},this.sources,[n.selector])}else if("selector"in n&&n.selector){let s=kl(n.selector),d=vn(s),c=n.selector;if(n.type==="inspect"){let p=await this.render(r,t,c,n.plane==="host");a={...this.surface.inspect(c,n.properties??[]),element:d,warnings:p,view:n.plane??"own",url:lr(),changedSourceTargets:n.plane==="host"?void 0:this.changed}}else if(n.type==="style")if("token"in n){let p=ey(n.token,n.family);if(!Il(s,p.family,p.subproperty))throw new Error("This omnidial token does not support the target");await this.render(r,t,c);let u=this.surface.frame.contentDocument?.querySelector(c);if(!u)throw new Error("Could not inspect original style");let h=p.axisSteps?Hu(u,p.axisSteps.x,p.axisSteps.y):Du(u,p.family,p.step,p.subproperty);h.alreadyApplied||l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:h.changes}}),a={token:n.token,selection:p,alreadyApplied:h.alreadyApplied}}else{if(!CSS.supports(n.property,n.value))throw new Error("Unsupported CSS property/value");await this.render(r,t,c);let p=this.surface.inspect(c,[n.property])?.styles[n.property];if(p===void 0)throw new Error("Could not inspect original style");l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:[{property:n.property,original:p,modified:n.value}]}})}else if(n.type==="comment"){await this.render(r,t,c);let p=s.getBoundingClientRect();l({type:"ADD_TEXT",payload:{id:`peer-note-${e.id}`,point:{x:p.x+scrollX,y:p.y+scrollY-26},text:n.text,linkedSelector:c,elements:[{...d,selector:c}]}})}r.attention=null,(n.type==="comment"||n.type==="style")&&(r.basis=Gs(r.basis??{},e.observedSources??{},this.sources,[c]))}if(i!==o){if(i.annotations.length+i.styleModifications.length>100)throw new Error("Peer draft is full; submit or undo before adding more");i={...i,undoStack:i.undoStack.slice(-50),redoStack:i.redoStack.slice(-50)},r.state=i,r.revision++,r.url=lr(),delete r.pendingRevision}return{peer:r,evidence:a,...["inspect","style","comment","clear","undo","redo","rebase"].includes(n.type)&&!(n.type==="inspect"&&n.plane==="host")?{sources:this.sources}:{}}}dispose(){this.surface.dispose(),this.container.remove()}};async function sy(e,t,n){let r=!0,o,i=new Set,a=async c=>{let p=new AbortController;i.add(p);let u=setTimeout(()=>p.abort(),1500);try{return await e(c,p.signal)}catch{return!1}finally{clearTimeout(u),i.delete(p)}},l=()=>{r=!1,clearTimeout(o);for(let c of i)c.abort()},s=()=>{l(),a("finish")},d=async()=>{if(!r)return;let c=await a("renew");r&&c&&(o=setTimeout(()=>{d()},1e3))};n.addEventListener("abort",s,{once:!0});try{if(n.aborted)throw new Error("Canvas disconnected before action");let c=await a("start");if(n.aborted)throw new Error("Canvas disconnected before action");return r&&c&&(o=setTimeout(()=>{d()},1e3)),await t()}finally{l(),n.removeEventListener("abort",s),await a("finish")}}function dy(e){let t=`popmelt-peer-seen:${e}`,[n,r]=P({key:"",revisions:{}});return O(()=>{let o={};try{let i=JSON.parse(localStorage.getItem(t)??"{}");i&&typeof i=="object"&&!Array.isArray(i)&&(o=Object.fromEntries(Object.entries(i).filter(([,a])=>Number.isSafeInteger(a)&&a>=0)))}catch{}r({key:t,revisions:o})},[t]),{markSeen:J((o,i)=>{r(a=>{if(a.key!==t||(a.revisions[o]??0)>=i)return a;let l={key:t,revisions:{...a.revisions,[o]:i}};try{localStorage.setItem(t,JSON.stringify(l.revisions))}catch{}return l})},[t]),isUnseen:(o,i)=>n.key===t&&i>(n.revisions[o]??0)}}function cy(e,t){let n,r=l=>(l instanceof Element?l:l.parentElement)?.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-root], popmelt-root"),o=()=>{n===void 0&&(n=setTimeout(()=>{n=void 0,t()},400))},i=new MutationObserver(l=>{document.hidden||!e.length||l.some(s=>{if(r(s.target)||s.type==="childList"&&[...s.addedNodes,...s.removedNodes].every(c=>r(c)))return!1;let d=s.target instanceof Element?s.target:s.target.parentElement;return d?.closest("style,head")?!0:e.some(c=>{let p=document.querySelector(c);return!p||p.contains(s.target)||d?.contains(p)})})&&o()});i.observe(document.documentElement,{subtree:!0,attributes:!0,childList:!0,characterData:!0}),window.addEventListener("resize",o);let a=()=>{document.hidden||o()};return document.addEventListener("visibilitychange",a),()=>{i.disconnect(),clearTimeout(n),window.removeEventListener("resize",o),document.removeEventListener("visibilitychange",a)}}function _u(e){if(!e)return 0;let t=Vh(e.annotations);return yc({annotations:e.annotations.filter(n=>!n.captured&&!t.has(n)),styleModifications:e.styleModifications.filter(n=>!n.captured),textModifications:e.textModifications.filter(n=>!n.captured)}).count}function uy(e,t,n,r,o){let[i,a]=P([]),[l,s]=P([]),d=Ah(l,e&&r.isAnnotating),c=Mh(e&&r.isAnnotating),{viewedId:p,isPeeking:u}=c,[h,m]=P(),[g,x]=P(),[S,z]=P([]),H=B(null),{markSeen:w,isUnseen:j}=dy(n),Z=we(()=>new Map(i.map(U=>[U.identity.id,_u(U.state)])),[i]),{annotations:k,styleModifications:V,textModifications:N}=r,Y=we(()=>_u({annotations:k,styleModifications:V,textModifications:N}),[k,V,N]),[q,ie]=P(null),I=B(null),Q=B({human:r,settings:o});Q.current={human:r,settings:o};let $=B({clientId:crypto.randomUUID()}),_=B(async()=>{throw new Error("Canvas is disconnected")}),R=e?i.find(U=>U.identity.id===p):void 0,D=i.find(U=>U.identity.id===c.selectedId)?.state,L=we(()=>Rh(D),[D]);O(()=>{if(!e||!n)return;$.current.token||($.current={clientId:crypto.randomUUID()});let U=!1,fe,me=-1,K=-1,Te=new AbortController,Me="",Ee=!1,Ge=new Ou,X=new Map,Ne=Pe=>{U||typeof Pe.presenceVersion!="number"||Pe.presenceVersion<=K||!Array.isArray(Pe.presence)||(K=Pe.presenceVersion,s(Pe.presence))},ve=async(Pe,ze={},ce=AbortSignal.any([Te.signal,AbortSignal.timeout(5e4)]))=>{let ot=$.current.token,at=await Yt(`${t}/peers/${Pe}`,{method:"POST",headers:{"Content-Type":"application/json","X-Popmelt-Project-Id":n},body:JSON.stringify({...$.current,...ze}),signal:ce}),Be=await at.json();if(Pe!=="host"&&ot!==$.current.token)throw new Error("Canvas session changed during request");if(!at.ok||Be.error)throw new Error(Be.error??`Peer request failed (${at.status})`);return Be};_.current=ve;async function _e(Pe){if(Pe.url&&Pe.url!==lr())throw new Error("Canvas navigated before the operation could run");if(Pe.action.type!=="send"){let kt=sm(Pe.action);return kt?(kl(kt.selector),sy(async(st,Xe)=>{let Lt=await ve("activity",{id:Pe.id,phase:st},Xe);return Ne(Lt),Lt.accepted===!0},()=>Ge.execute(Pe,Q.current.human),Te.signal)):Ge.execute(Pe,Q.current.human)}if(!Pe.grant)throw new Error("No host-approved Send grant");let ze=structuredClone(Pe.peer);if(ze.url!==lr())throw new Error("Return to the proposal\u2019s page before sending");let ce=ze.state;if(!ce||!ce.annotations.length&&!ce.styleModifications.length)throw new Error("There are no peer changes to send");await Ge.render(ze,Q.current.human);let ot={...Ge.sources};if(!Pe.observedSources||Object.keys(ot).some(kt=>Pe.observedSources[kt]!==ot[kt]))throw new Error("Source changed since the last preview. Take another look, then send again.");let at=Ge.surface.frame.contentDocument;if(!at)throw new Error("Peer preview is unavailable");let[Be]=await Oi(at.body,null,[],{viewportOnly:!0});if(!Be)throw new Error("Could not capture the peer preview");if(await Ge.render(ze,Q.current.human),!Nu(ot,Ge.sources))throw new Error("Source changed while preparing Send. Take another look, then send again.");await ve("source",{grant:Pe.grant,sources:ot});let Se=cc(ce.annotations,ce.styleModifications,void 0,void 0,ce.textModifications),{provider:Je,model:Ft,agentSettings:vt}=Q.current.settings,$t=await mu(Be,JSON.stringify(Se),t,ze.color,Je,Ft,void 0,void 0,vt,void 0,void 0,void 0,Pe.grant);return ze.state={...structuredClone(pl),isAnnotating:!0,activeColor:ze.color},ze.revision++,ze.basis={},delete ze.pendingRevision,ze.lastJob={jobId:$t.jobId,threadId:$t.threadId},{peer:ze,evidence:{status:"submitted",...$t}}}async function qe(){try{if(!$.current.token||Me!==lr()){let ze=await ve("host",{url:lr()});if(U)return;$.current.token=String(ze.token),Me=lr()}let Pe=await ve("poll",{version:me,presenceVersion:K});if(U)return;Ne(Pe),Pe.peers&&(a(Pe.peers),Ee=Pe.peers.length>0,me=Number(Pe.version));for(let ze of Pe.requests){let ce=X.get(ze.id);if(!ce){try{ce=await _e(ze)}catch(ot){ce={error:ot instanceof Error?ot.message:String(ot)}}X.set(ze.id,ce),X.size>100&&X.delete(X.keys().next().value)}await ve("response",{id:ze.id,result:ce})}}catch(Pe){!U&&Pe instanceof Error&&Pe.message.includes("Host capability")&&($.current.token=void 0,me=-1,K=-1,U||s([]))}finally{U||(fe=setTimeout(()=>{qe()},document.hidden||!Ee?2e3:600))}}return qe(),()=>{U=!0,Te.abort(),clearTimeout(fe),Ge.dispose(),a([]),s([]),_.current=async()=>{throw new Error("Canvas is disconnected")}}},[e,t,n]),O(()=>{if(x(void 0),z([]),H.current=null,!R||!r.isAnnotating||!I.current){ie(null);return}let U=new Ou;I.current.append(U.container),ie(null),U.container.removeAttribute("aria-hidden"),U.container.style.cssText="position:absolute;inset:0;pointer-events:none;";let fe=!1;R.url&&R.url!==lr()&&x("This draft belongs to another page. Return to it to preview.");let me=!1,K=!1,Te=()=>{if(!fe){if(me){K=!0;return}me=!0,U.render(R,Q.current.human).then(()=>{fe||(x(void 0),z(U.changed),H.current={id:R.identity.id,revision:R.revision,values:{...U.sources}},ie(U.surface.frame),w(R.identity.id,R.revision))}).catch(X=>{fe||(H.current=null,ie(null),x(X.message))}).finally(()=>{me=!1,K&&(K=!1,Te())})}},Me=!R.url||R.url===lr();Me&&Te();let Ee=Me?cy($a(R.state),Te):()=>{},Ge=()=>U.surface.frame.contentWindow?.scrollTo(scrollX,scrollY);return window.addEventListener("scroll",Ge,{passive:!0}),()=>{fe=!0,Ee(),window.removeEventListener("scroll",Ge),U.dispose()}},[R,r.isAnnotating,w]);let E=async U=>{try{return await U(),m(void 0),!0}catch(fe){return m(fe instanceof Error?fe.message:String(fe)),!1}},te=e&&i.length?{peers:[{identity:{id:"host",name:"You",kind:"human",relationship:"host"},permission:"direct",color:r.activeColor,stagedCount:Y},...i.map(U=>({...U,stagedCount:Z.get(U.identity.id)??0,unseenActivity:j(U.identity.id,U.revision)}))],viewedPeerId:p,selectedPeerId:c.selectedId,onPeek:c.peek,onPeekEnd:c.leave,onPreview:U=>{c.select(U),m(void 0)},onPermissionChange:(U,fe)=>E(()=>_.current("permission",{peerId:U,permission:fe}))}:null,re=R?.pendingRevision!==void 0?()=>E(()=>{let U=H.current;if(!U||U.id!==p||U.revision!==R.revision)throw new Error("Wait for this draft\u2019s preview before sending.");return _.current("approve",{peerId:p,revision:R.pendingRevision,sources:U.values})}):void 0,ee=!!(R&&r.isAnnotating),oe=e&&(h??(ee?g:void 0));return O(()=>{if(!ee)return;let U=fe=>{fe.composedPath().some(me=>me instanceof Element&&me.hasAttribute("data-devtools"))||(fe.metaKey||fe.ctrlKey)&&fe.key==="Enter"||(fe.key.length===1||["Backspace","Delete","Enter"].includes(fe.key))&&(fe.preventDefault(),fe.stopPropagation())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[ee]),{toolbar:te,selectedId:c.selectedId,threadAnnotationNumbers:L,activePreview:ee,isPeeking:u,viewed:R,approve:re,overlay:M(ut,{children:[ee&&f("div",{ref:I,"data-devtools":"peer-preview","data-peer-revision":R?.revision,"data-pending-revision":R?.pendingRevision,"data-popmelt-peer-surface":!0,style:{position:"fixed",inset:0,zIndex:1e4,background:"#111",pointerEvents:"auto"}}),d.map(({presence:U,engaged:fe})=>{if(u)return null;let me=i.find(Te=>Te.identity.id===U.peerId);if(!me||U.clientId!==$.current.clientId||U.url!==lr()||ee&&me.identity.id!==p)return null;let K=null;try{K=ee?q?.contentDocument?.querySelector(U.selector)??null:kl(U.selector)}catch{}return f(qc,{element:K,engaged:fe,label:`${me.identity.name} is looking at this element`},`${me.identity.id}:${U.operationId}`)}),!u&&ee&&R&&q?.contentDocument&&f($h,{peer:R,targetDocument:q.contentDocument,onApprove:re?()=>{re()}:void 0}),ee&&R&&p===c.selectedId&&f("div",{"data-devtools":"peer-plane-border","data-plane-owner":R.identity.id,"aria-hidden":"true",style:{position:"fixed",inset:0,border:`2px solid ${R.color}`,boxSizing:"border-box",pointerEvents:"none",zIndex:10002}}),ee&&R&&p===c.selectedId&&f(Lh,{name:R.identity.name,isOwnPlane:R.identity.id==="host",color:R.color,changed:S.length>0}),oe&&f("div",{"data-devtools":"peer-error",role:"status",style:{position:"fixed",bottom:100,right:24,maxWidth:360,padding:12,background:"#222",color:"#ddd",borderRadius:12,fontFamily:Ns,fontSize:12,lineHeight:1.4,zIndex:10002},children:oe})]})}}function py(e,t,n,r,o,i,a){let[l,s]=P(),d=B({navigation:e,selectedId:t});O(()=>{if(!e||!n||l?.navigation===e)return;let c=e.read(),p=o.current,u=!1;if(!c.threadId||c.selectedId!==t){s({navigation:e});return}return i(c.threadId).then(h=>{if(!u){if(p===o.current&&e.read()===c)if(h>=200&&h<300)a(c.threadId);else if(h===403||h===404||h===410)e.rememberThread(t,null);else{s({navigation:e,unresolvedRevision:p});return}s({navigation:e})}}).catch(()=>{u||s({navigation:e,unresolvedRevision:p})}),()=>{u=!0}},[e,t,n,l,o,i,a]),O(()=>{let c=d.current.navigation!==e||d.current.selectedId!==t;d.current={navigation:e,selectedId:t},!(!e||l?.navigation!==e||c)&&(l.unresolvedRevision===o.current&&!r||e.rememberThread(t,r))},[e,t,r,l,o])}var fy=hl(()=>import("./ParticipantRuntime-XGBQEJLU.mjs")),hy=hl(()=>import("./PreviewRuntime-JAZLAGQE.mjs"));function my({children:e,projectId:t,adapters:n,multiplayer:r=!1}){let[o,i]=P(!1);if(O(()=>{i(!0)},[]),!o)return null;let a=window.__POPMELT_PARTICIPANTS__;if(!r)return gu()?null:a?f("p",{role:"status","data-devtools":"participant-disabled",children:"Multiplayer is disabled. Enable the multiplayer option in your Popmelt integration to use this participant page."}):e;if(a)try{ug(a,t)}catch(l){return f("p",{role:"alert","data-devtools":"participant-error",children:l.message})}return gu()?a?f(ml,{fallback:null,children:f(hy,{config:a,adapters:n})}):null:a?f(ml,{fallback:null,children:f(fy,{config:a,children:Ig(e,{bridgeUrl:a.url,projectId:a.projectId})},a.projectId)}):e}function gy(e,t,n,r){let o=B(e);o.current=e;let[i,a]=P([]),l=B(null),[s,d]=P(null),[c,p]=P(null),u=i.filter(x=>x.scope===e),h=x=>a(S=>S.filter(z=>z.id!==x)),m=(x,S)=>{let z=Symbol(x);p(null);let H=t(x).then(()=>!0,()=>(o.current===e&&(S(),p({scope:e,message:"Could not dismiss thread. Please try again."})),h(z),!1));a(w=>[...w.filter(j=>j.scope===e),{id:z,threadId:x,rollback:S,saved:H,scope:e,undoHead:r}])},g=async()=>{let x=u.at(-1);if(!(!x||l.current===e)){l.current=e,d(e),p(null);try{if(!await x.saved||o.current!==e||(await n(x.threadId),o.current!==e))return;x.rollback(),h(x.id)}catch{o.current===e&&p({scope:e,message:"Could not restore thread. Try Undo again."})}finally{l.current===e&&(l.current=null,d(null))}}};return{dismiss:m,undo:g,tryUndo:()=>{let x=u.at(-1);return!x||x.undoHead!==r?!1:(g(),!0)},busy:s===e,count:u.length,error:c?.scope===e?c.message:null}}function yy({enabled:e,active:t,configuration:n=!0,adapters:r}){let[o,i]=P(!1),[a,l]=P(null),s=we(()=>pg(),[]),{recognition:d,selector:c,root:p,observe:u,store:h,imageHasher:m,onError:g}=typeof n=="object"?n:{},x=r.some(w=>w.surfaceKind==="image"||w.id==="see:image"),S=e&&n!==!1&&!x,z=t||o,H=z?d:void 0;return O(()=>{e?t&&i(!0):i(!1)},[e,t]),O(()=>{if(!S)return;let w=fg({recognition:H?{cacheKey:H.cacheKey,configurationKey:H.configurationKey,detect:j=>H.detect(j),reconcile:(...j)=>H.reconcile(...j)}:void 0,hydrateOnly:!z,selector:c,root:p,observe:u,store:h??s,imageHasher:m,onError:g});return l(w),()=>{l(null),w.destroy()}},[S,H,z,c,p,u,h,s,m,g]),we(()=>S&&a?[a,...r]:r,[S,a,r])}function vy({enabled:e,configuration:t=!0,adapters:n}){let[r,o]=P(null),i=we(()=>hg(),[]),{segmentation:a,tracking:l,selector:s,root:d,observe:c,store:p,onError:u}=typeof t=="object"?t:{},h=n.some(g=>g.surfaceKind==="video"||g.id==="see:video"),m=e&&t!==!1&&!h;return O(()=>{if(!m)return;let g=mg({tracking:l,segmentation:a,selector:s,root:d,observe:c,store:p??i,onError:u});return o(g),()=>{o(null),g.destroy()}},[m,l,a,s,d,c,p,i,u]),we(()=>m&&r?[r,...n]:n,[m,r,n])}function Fu(e,t){return JSON.stringify([e,t.adapter,t.key])}async function Wu(e,t,n,r){for(let o of t){if(!o.target)continue;let i=Fu(n,o.target);if(!r.has(i))try{r.set(i,await e.captureFeedback(o.target))}catch{r.set(i,null)}}}function by(e,t,n){let r=new Map;for(let o of e.annotations){let i=t.find(l=>l.id===o.id),a=(i?.groupId?t.filter(l=>l.groupId===i.groupId):t.filter(l=>l.id===o.id)).flatMap(l=>n.get(l.id)??[]);a.length&&r.set(o.id,a)}return r}function xy(e,t,n,r){for(let o of e.annotations){if(!o.target)continue;let i=n.get(Fu(o.pathname||r,o.target));if(!i){o.subjectFeedback={warning:"Live object unavailable; the following object context is the draft-time snapshot, not a refreshed detection. No object crop is attached."};continue}if(o.elements=[i.elementInfo],o.subjectFeedback=i.warning?{warning:i.warning}:void 0,i.crop){let a=t.get(o.id)??[];o.subjectFeedback={...o.subjectFeedback,cropImageIndex:a.length},t.set(o.id,[...a,i.crop])}}}function wy(e){let t=e?.requestItems?.flatMap(r=>r.kind==="annotation"&&r.text.trim()?[r.text.trim()]:[]);if(t?.length)return t.join("; ");let n=e?.requestItems?.flatMap(r=>r.kind==="changes"?[`${r.elementLabel} [${r.changes.join(", ")}]`]:[]);return n?.length?n.join("; "):e?.requestText?.trim()||void 0}function Sy(e,t){if(!e?.frames?.length)return[];let n=new Map;for(let r of e.steps){let o=r.visuals?.afterFrameId;o&&!n.has(o)&&n.set(o,r.action?.label?`After ${r.action.label}`:"Resulting state")}return e.frames.flatMap((r,o)=>{let i=t[r.imageIndex];return i?[{id:r.id,imageIndex:r.imageIndex,label:o===0?"Initial state":n.get(r.id)??"State",url:i}]:[]})}function Bu(e){let t=e.instruction?.trim();return t?e.attachments?.some(n=>n.name?.trim()===t)?null:t:null}function Iy(e,t){let n=e?.tagName?.toLowerCase(),r=e?.id?`#${e.id}`:"",o=e?.className?`.${e.className.trim().split(/\s+/).slice(0,2).join(".")}`:"",i=n?`${n}${r}${o}`:t;return e?.reactComponent?`<${e.reactComponent}> ${i}`:i}function ky(e){let t=e.elements?.[0]?.reactComponent||e.elements?.[0]?.tagName||e.linkedSelector,n=e.type&&e.type!=="annotation"?`${e.type} annotation`:"Annotation";return t?`${n} on ${t}`:n}function Ty(e){let t=e.annotations.map(o=>{let i=o.interactionEpisode?.steps.length??0;return{kind:"annotation",annotationId:o.id,pathname:o.pathname,text:Bu(o)??ky(o),...i>0?{interactionEpisodeStepCount:i}:{}}}),n=new Map,r=o=>{let i=`${o.pathname??""}:${o.durableSelector??o.selector}`,a=n.get(i);if(a){a.changes.push(o.text),o.annotationNumber!==void 0&&(a.annotationNumber===void 0||o.annotationNumber<a.annotationNumber)&&(a.annotationNumber=o.annotationNumber);return}let l={kind:"changes",elementKey:i,elementLabel:Iy(o.element,o.selector),...o.annotationNumber!==void 0?{annotationNumber:o.annotationNumber}:{},pathname:o.pathname,changes:[o.text]};n.set(i,l),t.push(l)};for(let o of e.styleModifications??[])for(let i of o.changes)r({...o,text:`${i.property}: ${i.original||"unset"} \u2192 ${i.modified||"unset"}${i.token?` (${i.token})`:""}`});for(let o of e.textModifications??[])r({...o,text:`Text: ${o.original||"empty"} \u2192 ${o.modified||"empty"}`});for(let o of e.domModifications??[])r({...o,text:o.operation==="copy"?"Copied element":"Moved element"});return e.spacingTokenChanges?.length&&t.push({kind:"changes",elementKey:"spacing-tokens",elementLabel:"Spacing tokens",changes:e.spacingTokenChanges.map(o=>`${o.tokenName}: ${o.originalPx}px \u2192 ${o.newPx}px`)}),t}function Ey(e){let t=e.annotations.flatMap(r=>{let o=Bu(r);return o?[{instruction:o,pathname:r.pathname}]:[]});if(t.length===0)return;if(new Set(t.map(r=>r.pathname).filter(Boolean)).size<=1)return t.map(r=>r.instruction).join(`
5
5
 
6
6
  `);let n=new Map;for(let r of t){let o=r.pathname||"(unknown)",i=n.get(o)??[];i.push(r.instruction),n.set(o,i)}return[...n.entries()].map(([r,o])=>`\`${r}\`
7
7
  ${o.map(i=>`- ${i}`).join(`
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{A as l,d as b,l as I,m as w,y as k}from"./chunk-OFHBVUTT.mjs";import{readFile as h,realpath as P,mkdir as x,writeFile as E}from"fs/promises";import{createHash as S}from"crypto";import{join as m,resolve as O}from"path";function N(t,e){let r=S("sha256").update(e).digest("hex");return m(t,".popmelt","participant-agents",r+".json")}async function M(t,e){if(e.storeId!==t.storeId)return{ok:!1,body:{status:"writable_store_required"}};if(typeof e.threadId!="string"||!e.threadId||typeof e.text!="string"||!e.text.trim()||e.text.length>8e3)return{ok:!1,body:{status:"invalid_note"}};let r;try{r=await v(t,t.sessionId,!0)}catch(a){if(a.code!=="ENOENT")throw a;return{ok:!1,body:{status:"participant_invitation_required"}}}if(!r)return{ok:!1,body:{status:"enrolled_bridge_required"}};let o=await l(r.endpoint,"/participants/thread-note",{...r.request,method:"POST",signal:AbortSignal.timeout(3e4),body:JSON.stringify({storeId:t.storeId,threadId:e.threadId,reply:e.text,sessionId:t.sessionId,requestId:e.requestId})});return{ok:o.response.ok,body:o.body}}async function v(t,e,r=!1){let o=await h(m(t.projectRoot,".popmelt","participant-bridge.json"),"utf8").then(JSON.parse).catch(c=>{if(c.code!=="ENOENT"||!t.bridgePort)throw c;return{projectId:t.projectId,port:t.bridgePort}});if(o.projectId!==t.projectId||!Number.isInteger(o.port)||o.port<1||o.port>65535)return null;let a={redirect:"error",signal:AbortSignal.timeout(3e3)},p=await l(o,"/status",a);if(!p.response.ok||p.body?.projectId!==t.projectId)return null;let i=N(t.projectRoot,e),n;try{n=JSON.parse(await h(i,"utf8"))}catch(c){if(c.code!=="ENOENT"||!r)throw c;let d=await P(t.projectRoot),u=b(e);if(w(d)!==t.projectId||!u)return null;let s=JSON.parse(await h(m(d,".popmelt","participant-host.json"),"utf8"));if(!(await l(o,"/participants/agent-join",{...a,method:"POST",headers:{"X-Popmelt-Participant-Id":s.participantId,"X-Popmelt-Participant-Token":s.token},body:JSON.stringify({sessionId:e,name:u,headless:!0})})).response.ok)return null;n=JSON.parse(await h(i,"utf8"))}return{endpoint:o,request:{...a,headers:{"X-Popmelt-Participant-Id":n.participantId,"X-Popmelt-Participant-Token":n.token}}}}async function F(t,e,r){let o=[t,...t.mountedStores].find(c=>c.storeId===e.storeId);if(!o||r&&o!==t)return{ok:!1,body:{status:"store_unavailable"}};if(r&&(typeof e.threadId!="string"||!e.threadId))return{ok:!1,body:{status:"thread_required"}};let a=await v(o,t.sessionId,r).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!a)return{ok:!1,body:{status:"enrolled_bridge_required",message:"Join this project as a Popmelt peer and check that its bridge is running."}};let{endpoint:p,request:i}=a,n=await l(p,r?t.sessionId.startsWith("claude:")?"/participants/link-claude-chat":"/participants/link-codex-chat":"/participants/check-claude-notes",{...i,method:"POST",body:JSON.stringify({sessionId:t.sessionId,...r?{threadId:e.threadId}:{}})});return{ok:n.response.ok,body:n.body}}async function _(t,e,r){if(!r.projectRoot)throw new Error("Participant connections require the active project root");let o=await P(r.projectRoot);if(w(o)!==t.projectId)throw new Error("Participant project does not match");let a=m(o,".popmelt"),p=S("sha256").update(e).digest("hex"),i=async(s,f,g)=>{let j=await l(t,"/participants/"+s,{method:"POST",redirect:"error",headers:{"X-Popmelt-Participant-Id":f.participantId,"X-Popmelt-Participant-Token":f.token},body:JSON.stringify(g),signal:AbortSignal.timeout(9e4)}),y=j.body;if(!j.response.ok||y.error)throw new Error(y.error??"Participant connection unavailable");return y},n,c;try{n=JSON.parse(await h(N(o,e),"utf8"))}catch(s){if(s.code!=="ENOENT")throw s;if(!r.name)return{status:"participant_invitation_required"};let f=JSON.parse(await h(m(a,"participant-host.json"),"utf8")),g=await i("agent-join",f,{sessionId:e,name:r.name});n=g.credential,c=g.participant}if(!r.action){let s=await i("agent-connect",n,{});return{status:"participant_connected",participantId:n.participantId,participant:s.participant??c}}let d=await i("agent-act",n,{action:I(r.action)}),u=d.evidence;if(u?.frame?.image){let s=u.frame.image;if(!/^data:image\/jpeg;base64,[A-Za-z0-9+/=]+$/.test(s)||s.length>7e5)throw new Error("Invalid participant preview");let f=m(a,"artifacts","participant-previews");await x(f,{recursive:!0,mode:448});let g=m(f,p+".jpg");return await E(g,Buffer.from(s.slice(s.indexOf(",")+1),"base64"),{mode:384}),{status:"participant_connected",participant:d.participant,evidence:{...u,frame:{imagePath:g,targets:u.frame.targets}}}}return{status:"participant_connected",participant:d.participant,evidence:d.evidence}}async function C(t,e,r={}){if(k())return{status:"already_managed_by_bridge"};if((await l(t,"/status",{redirect:"error",signal:AbortSignal.timeout(3e3)})).body?.participantSessions)return _(t,e,r);let a=async(c,d)=>{let u=await l(t,`/peers/${c}`,{method:"POST",body:JSON.stringify(d),signal:AbortSignal.timeout(5e4)}),s=u.body;if(!u.response.ok||s?.error)throw new Error(s?.error??"Peer connection unavailable");return s},p=await a("join",{sessionId:e,name:r.name}),i=r.action?await a("act",{token:p.token,clientId:r.clientId,action:I(r.action)}):p,n=i.peer;return{...i.status?{status:i.status}:{},...n?{peer:{...n,state:n.state?{annotations:n.state.annotations,styleModifications:n.state.styleModifications,textModifications:n.state.textModifications,undoDepth:n.state.undoStack.length,redoDepth:n.state.redoStack.length}:null}}:{},...i.evidence?{evidence:i.evidence}:{},clients:p.clients}}async function D(t){let e=c=>{let d=t.indexOf(c);return d>=0?t[d+1]:void 0},r=e("--session");if(!r)throw new Error("Usage: popmelt peer --session <stable-agent-session> [--project-root <active-project>] [--name <your-name>] [--client <canvas-id>] [--action <JSON>]");let o=await P(O(e("--project-root")??process.cwd())),a=JSON.parse(await h(m(o,".popmelt","bridge.lock"),"utf8")),p=w(o),i=await l({port:a.port,projectId:p},"/status",{signal:AbortSignal.timeout(3e3)});if(!i.response.ok||i.body.projectRoot!==o&&!(i.body.participantSessions&&i.body.projectId===p))throw new Error("No matching running project bridge");let n=e("--action");console.log(JSON.stringify(await C({port:a.port,projectId:p},r,{name:e("--name"),projectRoot:o,clientId:e("--client"),action:n?JSON.parse(n):void 0}),null,2))}export{N as a,M as b,v as c,F as d,C as e,D as f};
2
+ import{A as l,d as b,l as I,m as w,y as k}from"./chunk-PCP5ENOU.mjs";import{readFile as h,realpath as P,mkdir as x,writeFile as E}from"fs/promises";import{createHash as S}from"crypto";import{join as m,resolve as O}from"path";function N(t,e){let r=S("sha256").update(e).digest("hex");return m(t,".popmelt","participant-agents",r+".json")}async function M(t,e){if(e.storeId!==t.storeId)return{ok:!1,body:{status:"writable_store_required"}};if(typeof e.threadId!="string"||!e.threadId||typeof e.text!="string"||!e.text.trim()||e.text.length>8e3)return{ok:!1,body:{status:"invalid_note"}};let r;try{r=await v(t,t.sessionId,!0)}catch(a){if(a.code!=="ENOENT")throw a;return{ok:!1,body:{status:"participant_invitation_required"}}}if(!r)return{ok:!1,body:{status:"enrolled_bridge_required"}};let o=await l(r.endpoint,"/participants/thread-note",{...r.request,method:"POST",signal:AbortSignal.timeout(3e4),body:JSON.stringify({storeId:t.storeId,threadId:e.threadId,reply:e.text,sessionId:t.sessionId,requestId:e.requestId})});return{ok:o.response.ok,body:o.body}}async function v(t,e,r=!1){let o=await h(m(t.projectRoot,".popmelt","participant-bridge.json"),"utf8").then(JSON.parse).catch(c=>{if(c.code!=="ENOENT"||!t.bridgePort)throw c;return{projectId:t.projectId,port:t.bridgePort}});if(o.projectId!==t.projectId||!Number.isInteger(o.port)||o.port<1||o.port>65535)return null;let a={redirect:"error",signal:AbortSignal.timeout(3e3)},p=await l(o,"/status",a);if(!p.response.ok||p.body?.projectId!==t.projectId)return null;let i=N(t.projectRoot,e),n;try{n=JSON.parse(await h(i,"utf8"))}catch(c){if(c.code!=="ENOENT"||!r)throw c;let d=await P(t.projectRoot),u=b(e);if(w(d)!==t.projectId||!u)return null;let s=JSON.parse(await h(m(d,".popmelt","participant-host.json"),"utf8"));if(!(await l(o,"/participants/agent-join",{...a,method:"POST",headers:{"X-Popmelt-Participant-Id":s.participantId,"X-Popmelt-Participant-Token":s.token},body:JSON.stringify({sessionId:e,name:u,headless:!0})})).response.ok)return null;n=JSON.parse(await h(i,"utf8"))}return{endpoint:o,request:{...a,headers:{"X-Popmelt-Participant-Id":n.participantId,"X-Popmelt-Participant-Token":n.token}}}}async function F(t,e,r){let o=[t,...t.mountedStores].find(c=>c.storeId===e.storeId);if(!o||r&&o!==t)return{ok:!1,body:{status:"store_unavailable"}};if(r&&(typeof e.threadId!="string"||!e.threadId))return{ok:!1,body:{status:"thread_required"}};let a=await v(o,t.sessionId,r).catch(c=>{if(c.code==="ENOENT")return null;throw c});if(!a)return{ok:!1,body:{status:"enrolled_bridge_required",message:"Join this project as a Popmelt peer and check that its bridge is running."}};let{endpoint:p,request:i}=a,n=await l(p,r?t.sessionId.startsWith("claude:")?"/participants/link-claude-chat":"/participants/link-codex-chat":"/participants/check-claude-notes",{...i,method:"POST",body:JSON.stringify({sessionId:t.sessionId,...r?{threadId:e.threadId}:{}})});return{ok:n.response.ok,body:n.body}}async function _(t,e,r){if(!r.projectRoot)throw new Error("Participant connections require the active project root");let o=await P(r.projectRoot);if(w(o)!==t.projectId)throw new Error("Participant project does not match");let a=m(o,".popmelt"),p=S("sha256").update(e).digest("hex"),i=async(s,f,g)=>{let j=await l(t,"/participants/"+s,{method:"POST",redirect:"error",headers:{"X-Popmelt-Participant-Id":f.participantId,"X-Popmelt-Participant-Token":f.token},body:JSON.stringify(g),signal:AbortSignal.timeout(9e4)}),y=j.body;if(!j.response.ok||y.error)throw new Error(y.error??"Participant connection unavailable");return y},n,c;try{n=JSON.parse(await h(N(o,e),"utf8"))}catch(s){if(s.code!=="ENOENT")throw s;if(!r.name)return{status:"participant_invitation_required"};let f=JSON.parse(await h(m(a,"participant-host.json"),"utf8")),g=await i("agent-join",f,{sessionId:e,name:r.name});n=g.credential,c=g.participant}if(!r.action){let s=await i("agent-connect",n,{});return{status:"participant_connected",participantId:n.participantId,participant:s.participant??c}}let d=await i("agent-act",n,{action:I(r.action)}),u=d.evidence;if(u?.frame?.image){let s=u.frame.image;if(!/^data:image\/jpeg;base64,[A-Za-z0-9+/=]+$/.test(s)||s.length>7e5)throw new Error("Invalid participant preview");let f=m(a,"artifacts","participant-previews");await x(f,{recursive:!0,mode:448});let g=m(f,p+".jpg");return await E(g,Buffer.from(s.slice(s.indexOf(",")+1),"base64"),{mode:384}),{status:"participant_connected",participant:d.participant,evidence:{...u,frame:{imagePath:g,targets:u.frame.targets}}}}return{status:"participant_connected",participant:d.participant,evidence:d.evidence}}async function C(t,e,r={}){if(k())return{status:"already_managed_by_bridge"};if((await l(t,"/status",{redirect:"error",signal:AbortSignal.timeout(3e3)})).body?.participantSessions)return _(t,e,r);let a=async(c,d)=>{let u=await l(t,`/peers/${c}`,{method:"POST",body:JSON.stringify(d),signal:AbortSignal.timeout(5e4)}),s=u.body;if(!u.response.ok||s?.error)throw new Error(s?.error??"Peer connection unavailable");return s},p=await a("join",{sessionId:e,name:r.name}),i=r.action?await a("act",{token:p.token,clientId:r.clientId,action:I(r.action)}):p,n=i.peer;return{...i.status?{status:i.status}:{},...n?{peer:{...n,state:n.state?{annotations:n.state.annotations,styleModifications:n.state.styleModifications,textModifications:n.state.textModifications,undoDepth:n.state.undoStack.length,redoDepth:n.state.redoStack.length}:null}}:{},...i.evidence?{evidence:i.evidence}:{},clients:p.clients}}async function D(t){let e=c=>{let d=t.indexOf(c);return d>=0?t[d+1]:void 0},r=e("--session");if(!r)throw new Error("Usage: popmelt peer --session <stable-agent-session> [--project-root <active-project>] [--name <your-name>] [--client <canvas-id>] [--action <JSON>]");let o=await P(O(e("--project-root")??process.cwd())),a=JSON.parse(await h(m(o,".popmelt","bridge.lock"),"utf8")),p=w(o),i=await l({port:a.port,projectId:p},"/status",{signal:AbortSignal.timeout(3e3)});if(!i.response.ok||i.body.projectRoot!==o&&!(i.body.participantSessions&&i.body.projectId===p))throw new Error("No matching running project bridge");let n=e("--action");console.log(JSON.stringify(await C({port:a.port,projectId:p},r,{name:e("--name"),projectRoot:o,clientId:e("--client"),action:n?JSON.parse(n):void 0}),null,2))}export{N as a,M as b,v as c,F as d,C as e,D as f};
@@ -11,7 +11,7 @@ import{readFile as Ec,readdir as wI,realpath as vI,stat as bI}from"fs/promises";
11
11
  `),a=Dr(r),c=xd(i,o),d=[s,a,c].filter(Boolean).join(`
12
12
  `);return{additionalContext:d,contextBudget:{protocolEstimatedTokens:to(s),memoryEstimatedTokens:to(a),imprintEstimatedTokens:to(c),totalEstimatedTokens:to(d)}}}function xd(n,e){return n?Nr(n,{requestText:e,delivery:"ambient"}):["","## Continuous imprinting","","An imprint is provisional, advisory shared understanding; accepted product decisions always win. Ordinary completion, implementation, praise, silence, and ambiguity are not learning.","Before finishing, ask one level above the exact task whether human-supplied evidence established a reusable intention, rationale, relationship, or applicability boundary that would change a future decision. The default is no Imprint action.","Call `popmelt_assess_turn` only when reusable understanding changed. Before mutating, require all six: reusable, novel, durable, atomic, scoped, and supported by the human anywhere in the thread. If overlap with project knowledge is plausible, expand context before adding so the result can be consolidated or related instead of duplicated.",'For a genuinely new root, pass `assessmentText` as `<resolution>{"annotations":[],"imprint":{"decision":"mutate","summary":{"kind":"added","title":"<short title>","detail":"<what changed>"},"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one atomic claim>","rationale":"<human-supported reason>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]},"rootReason":"<why no existing explanation is related>"}]}}</resolution>`.','Include `appliedExplanationIds:["new-1"]` and a `grounding` question only when completed implementation or another observable action genuinely tested the new explanation; otherwise omit them.',"When context expansion surfaces related explanations, follow its complete relationship, application, correction, and topology contract. Do not print a machine-readable resolution envelope in the visible response."].join(`
13
13
  `)}function Vr(n){if(!n)return;if(n.decision==="recognize")return[n.explanationId];let e=[...new Set([...n.usedExplanationIds??[],...n.appliedExplanationIds??[]])];return e.length?e:void 0}function rh(n,e){let t=e.flatMap((r,i)=>{let o=n[i];return o?[{packetId:`ambient:${r}`,proposalId:r,claim:o.claim.trim(),proposedKind:o.proposedKind,authority:"unaccepted",presentation:"advisory",subjectLabels:["Project"],evidenceCount:1,expansionRefs:[{kind:"proposal",id:r}]}]:[]});return t.length>0?{source:"journal",packets:t,truncated:!1,estimatedTokens:0}:void 0}var no=class{constructor(e){this.options=e;this.turns=new Map;let t={storeId:e.storeId,projectRoot:e.projectRoot,projectId:e.projectId};this.knowledgeViewReader=e.knowledgeViewReader??new eo(t,{memory:e.memoryService,imprint:e.imprintService})}knowledgeDiagnostics(){return this.knowledgeViewReader.diagnostics()}key(e,t){return`${e}:${t}`}async findThread(e){return this.options.threadStore.findContinuationThread([wd(e)])}async prepare(e){if(e.executionOwner===Tn)return{status:"managed_by_bridge",protocolVersion:kn};let t=this.key(e.sessionId,e.turnId),r=this.turns.get(t);if(r){let m=Id(r.sessionId,r.threadId,r.jobId,r.memoryContext,r.imprintContext,r.prompt);return{status:"already_prepared",protocolVersion:kn,threadId:r.threadId,jobId:r.jobId,...m}}let i=await this.findThread(e.sessionId);i||(i=await this.options.threadStore.createThread(`thread-${Zf()}`,[wd(e.sessionId)]));let o=nh(e.sessionId,e.turnId),s=i.messages.find(m=>m.jobId===o&&m.role==="human"),a=vd(e.prompt,Wt(e.sessionId)),c=s?.memoryReview??await this.knowledgeViewReader.memoryContext(e.knowledgeView,a,[]),d=s?.imprintContext??await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.prompt,pendingGroundingExplanationIds:i.messages.flatMap(m=>m.role==="assistant"&&m.imprintSummary?.grounding&&!m.imprintSummary.resolvedAction?[m.imprintSummary.grounding.explanationId]:[])});s||await this.options.threadStore.appendMessage(i.id,{role:"human",timestamp:Date.now(),jobId:o,requestText:e.prompt,feedbackSummary:e.prompt,sessionId:e.sessionId,...c?{memoryReview:c}:{},...d?{imprintContext:d}:{}});let u={sessionId:e.sessionId,turnId:e.turnId,threadId:i.id,jobId:o,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:c,imprintContext:d,events:[]};this.turns.set(t,u);let p=Id(e.sessionId,i.id,o,c,d,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:kn,threadId:i.id,jobId:o,...p}}async recordEvent(e){if(e.executionOwner===Tn)return{status:"ignored"};let t=this.turns.get(this.key(e.sessionId,e.turnId));return t?e.toolUseId&&t.events.some(r=>r.toolUseId===e.toolUseId)?{status:"recorded"}:(t.events.push({toolName:e.toolName,toolUseId:e.toolUseId,toolInput:e.toolInput,toolResponse:e.toolResponse,occurredAt:Date.now()}),{status:"recorded"}):{status:"turn_not_prepared"}}async assess(e){let t=[...this.turns.values()].find(d=>d.threadId===e.threadId&&d.jobId===e.jobId);if(!t)return{status:"turn_not_found"};let r=await this.options.threadStore.getThread(t.threadId);if(r?.messages.some(d=>d.role==="assistant"&&d.jobId===t.jobId))return{status:"turn_completed"};if(t.assessmentEvaluation?.receipt.status==="committed")return t.assessmentEvaluation.receipt;t.assessment={assessmentText:e.assessmentText,semanticCandidates:e.semanticCandidates.slice(0,8)};let i=t.assessment.semanticCandidates.length?{status:"queued_for_turn_completion",count:t.assessment.semanticCandidates.length}:void 0,o=bd(t.events,this.options.projectRoot,Wt(t.sessionId)).length>0,s=Ji(t.imprintContext,r?.messages.find(d=>d.role==="human"&&d.jobId===t.jobId)?.imprintExpandedContext),a=Or(t.assessment.assessmentText,{context:s,requestText:t.prompt,applicationOccurred:o}),c;if(a.error)c={receipt:{status:"rejected",reason:a.error},imprintAssessment:{state:a.error.includes("missing")?"missing":"invalid",reason:a.error}};else if(a.draft?.decision==="none")this.options.imprintService.recordNoop(a.draft.reason),c={receipt:{status:"assessed",outcome:"no_change",reason:a.draft.reason,...i?{semanticCandidates:i}:{}},imprintAssessment:{state:"none",reason:a.draft.reason},imprintUsedExplanationIds:Vr(a.draft),imprintAppliedExplanationIds:a.draft.appliedExplanationIds};else if(a.draft?.decision==="recognize")c={receipt:{status:"assessed",outcome:"recognized",...i?{semanticCandidates:i}:{}},imprintAssessment:{state:"none",reason:"recognized existing grounded understanding"},imprintUsedExplanationIds:Vr(a.draft)};else if(a.draft?.decision==="mutate"||a.draft?.decision==="apply")try{let d=await this.options.imprintService.capture(a.draft,{threadId:t.threadId,jobId:t.jobId,concreteModel:await this.options.loadConcreteModel?.()??null,pendingGroundingExplanationIds:s?.pendingGroundingExplanationIds,applicationOccurred:o,storeId:this.options.storeId,context:s});if(d)await this.options.memoryService.recordImprintEvidence({summary:d,threadId:t.threadId,jobId:t.jobId,qualifiedExplanationMemoryIds:Object.fromEntries((s?.explanations??[]).flatMap(u=>u.storeId&&u.memoryId?[[`${u.storeId}:${u.id}`,u.memoryId]]:[]))}).catch(()=>{}),c={receipt:{status:"committed",transactionId:d.transactionId,changes:d.changes,...i?{semanticCandidates:i}:{}},imprintSummary:d,imprintAssessment:{state:"mutated"},imprintUsedExplanationIds:Vr(a.draft),imprintAppliedExplanationIds:a.draft.appliedExplanationIds};else{let u="imprint mutation failed admission or produced no durable change";c={receipt:{status:"rejected",reason:u},imprintAssessment:{state:"invalid",reason:u},imprintUsedExplanationIds:Vr(a.draft),imprintAppliedExplanationIds:a.draft.appliedExplanationIds}}}catch(d){let u=d instanceof Error?d.message:"imprint mutation failed";c={receipt:{status:"rejected",reason:u},imprintAssessment:{state:"invalid",reason:u},imprintUsedExplanationIds:Vr(a.draft),imprintAppliedExplanationIds:a.draft.appliedExplanationIds}}else{let d="imprint assessment is missing";c={receipt:{status:"rejected",reason:d},imprintAssessment:{state:"missing",reason:d}}}return t.assessmentEvaluation=c,(c.imprintAssessment.state==="missing"||c.imprintAssessment.state==="invalid")&&this.options.imprintService.recordAssessmentFailure(c.imprintAssessment.state),c.receipt}async complete(e){if(e.executionOwner===Tn)return{status:"managed_by_bridge",protocolVersion:kn};let t=this.turns.get(this.key(e.sessionId,e.turnId));if(!t)return{status:"turn_not_prepared",protocolVersion:kn};let i=(await this.options.threadStore.getThread(t.threadId))?.messages.find(h=>h.role==="assistant"&&h.jobId===t.jobId);if(i)return e.lastAssistantMessage&&e.lastAssistantMessage!==i.responseText&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{responseText:e.lastAssistantMessage}),{status:"already_completed",protocolVersion:kn,threadId:t.threadId,jobId:t.jobId};let o=bd(t.events,this.options.projectRoot,Wt(e.sessionId)),s=o.length>0,a=t.assessmentEvaluation?.imprintSummary,c=t.assessmentEvaluation?.imprintAssessment??{state:"not_applicable"},d=t.assessmentEvaluation?.imprintUsedExplanationIds,u=t.assessmentEvaluation?.imprintAppliedExplanationIds,p=s?"completed":"no_change",m=Gr({changedFiles:o}),v={role:"assistant",timestamp:Date.now(),jobId:t.jobId,responseText:e.lastAssistantMessage??"",sessionId:e.sessionId,toolsUsed:t.events.map(h=>h.toolName),turn:{phase:"complete",orientation:[],result:m},result:m,provider:Wt(e.sessionId),model:e.model,imprintSummary:a,imprintUsedExplanationIds:d,imprintAppliedExplanationIds:u};await this.options.threadStore.appendMessage(t.threadId,v);let b=await this.options.memoryService.captureCompletedJob({jobId:t.jobId,threadId:t.threadId,createdAt:t.createdAt,completedAt:Date.now(),requestSummary:t.prompt,responseSummary:e.lastAssistantMessage,outcome:p,execution:{provider:Wt(e.sessionId),model:e.model,sessionId:e.sessionId},subjectHints:[],filePaths:o,resolutions:s?[{status:"resolved",summary:`Changed ${o.join(", ")}`}]:[],semanticCandidates:t.assessment?.semanticCandidates,governingDecisionIds:t.memoryContext?.acceptedTruth?.decisions.map(h=>h.id),imprintAssessment:c}),f=rh(t.assessment?.semanticCandidates??[],b.proposalIds);return f&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{memoryReview:f}),{status:"completed",protocolVersion:kn,threadId:t.threadId,jobId:t.jobId}}async expandContext(e){let t=[...this.turns.values()].filter(d=>!!e.sessionId&&d.sessionId===e.sessionId&&(!(e.threadId||e.jobId)||d.threadId===e.threadId&&d.jobId===e.jobId)),r=(await Promise.all(t.map(async d=>{let u=await this.options.threadStore.getThread(d.threadId);return u?.messages.some(p=>p.role==="human"&&p.jobId===d.jobId&&p.sessionId===e.sessionId)&&!u.messages.some(p=>p.role==="assistant"&&p.jobId===d.jobId)?d:void 0}))).filter(d=>!!d),i=r.length===1?r[0]:void 0,o=vd(e.query),s=await this.knowledgeViewReader.memoryContext(e.knowledgeView,o,e.subjectHints??[]),a=await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.query,subjectHints:e.subjectHints}),c=!!(i&&a&&await this.options.threadStore.registerAmbientImprintContext(i.threadId,i.jobId,i.sessionId,a));return{memoryContext:s,imprintContext:a,assessmentContext:c&&i?{status:"registered",threadId:i.threadId,jobId:i.jobId}:{status:"not_registered",reason:a?"No matching open turn. Supply this session\u2019s exact threadId and jobId; completed turns cannot receive context.":"No Imprint references returned."},formattedContext:[Dr(s),xd(a,e.query)].filter(Boolean).join(`
14
- `)}}};function ro(n,e=process.env.POPMELT_EXPERIMENTAL_EVENT_TRANSPORT){let t=n??e??"websocket";if(t==="sse"||t==="websocket")return t;throw new Error("POPMELT_EXPERIMENTAL_EVENT_TRANSPORT must be sse or websocket")}import{spawn as oI}from"child_process";import{closeSync as sI,openSync as aI}from"fs";import{appendFile as cI,mkdir as dI,readFile as lI,realpath as pI}from"fs/promises";import{dirname as uI,join as Pc}from"path";import{fileURLToPath as mI}from"url";var Sd={name:"@popmelt.com/core",version:"0.30.0",description:"A tiny, powerful design layer for humans and AI",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,packageManager:"pnpm@9.12.0",engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint . && node scripts/check-eslint-suppressions.mjs","pack:smoke":"node scripts/pack-smoke.mjs","peer:smoke":"node scripts/peer-compat-smoke.mjs","vue:smoke":"pnpm run build && node scripts/vue-install-smoke.mjs","nuxt:smoke":"pnpm run build && node scripts/nuxt-install-smoke.mjs","astro:smoke":"pnpm run build && node scripts/framework-install-smoke.mjs astro","svelte:smoke":"pnpm run build && node scripts/framework-install-smoke.mjs svelte && node scripts/framework-install-smoke.mjs sveltekit",prepublishOnly:"pnpm run verify",test:"vitest run","test:coverage":"vitest run --coverage.enabled","test:browser":"pnpm run build && tsc --noEmit -p tsconfig.browser.json && vitest run --config vitest.browser.config.ts","test:browser:mutation":"node e2e/check-lifecycle-mutation.mjs","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run format && pnpm run lint && pnpm run test:coverage && pnpm run build && pnpm run pack:smoke"},exports:{".":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./browser":{types:"./dist/browser.d.mts",import:"./dist/browser.mjs"},"./server":{types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./next":{types:"./dist/plugin-next.d.mts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./vite/client":{types:"./dist/vite-client.d.ts"},"./astro":{types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"},"./nuxt":{types:"./dist/plugin-nuxt.d.mts",import:"./dist/plugin-nuxt.mjs",default:"./dist/plugin-nuxt.mjs"},"./media":{types:"./dist/media.d.mts",import:"./dist/media.mjs"},"./three":{types:"./dist/adapter-three.d.mts",import:"./dist/adapter-three.mjs"},"./react-three-fiber":{types:"./dist/adapter-react-three-fiber.d.mts",import:"./dist/adapter-react-three-fiber.mjs"}},files:["dist","codex-plugin","claude-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.3"},optionalDependencies:{"@napi-rs/keyring":"2.1.0"},peerDependencies:{nuxt:">=4.5.2 <5","lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0","@react-three/fiber":">=8.0.0",three:">=0.150.0"},peerDependenciesMeta:{nuxt:{optional:!0},next:{optional:!0},"@react-three/fiber":{optional:!0},three:{optional:!0}},devDependencies:{nuxt:"4.6.3","@kit/eslint-config":"workspace:^","@react-three/fiber":"9.7.0","@tanstack/react-router":"1.120.5","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/three":"^0.185.4","@types/ws":"8.18.1","@vitejs/plugin-react":"^5.1.1","@vitejs/plugin-vue":"6.0.8","@vitest/coverage-v8":"4.1.12",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.5.28",prettier:"3.5.3",react:"19.1.0","react-dom":"19.1.0",three:"^0.185.1",tsup:"^8.5.1",typescript:"^5.8.3",vite:"7.3.7",vitest:"4.1.12",vue:"3.5.44","vue-router":"5.3.1"},pnpm:{overrides:{"postcss@<8.5.23":"8.5.23","source-map-js@<1.2.2":"1.2.2","esbuild@<0.28.1":"0.28.1","sharp@<0.35.5":"0.35.5"}}};var Ft=Sd.version;import{spawn as oh}from"child_process";import{createInterface as sh}from"readline";async function io(n,e){let t=oh(process.env.CODEX_APP_RUNTIME_CLI_PATH||"codex",["app-server","--stdio"],{stdio:["pipe","pipe","ignore"]}),r=sh({input:t.stdout});try{return await new Promise((i,o)=>{let s=()=>o(new Error("Codex did not confirm "+n)),a=setTimeout(()=>{s(),t.kill()},1e4);t.once("close",()=>{clearTimeout(a),s()}),t.once("error",s),t.stdin.on("error",s);let c=d=>t.stdin.write(JSON.stringify(d)+`
14
+ `)}}};function ro(n,e=process.env.POPMELT_EXPERIMENTAL_EVENT_TRANSPORT){let t=n??e??"websocket";if(t==="sse"||t==="websocket")return t;throw new Error("POPMELT_EXPERIMENTAL_EVENT_TRANSPORT must be sse or websocket")}import{spawn as oI}from"child_process";import{closeSync as sI,openSync as aI}from"fs";import{appendFile as cI,mkdir as dI,readFile as lI,realpath as pI}from"fs/promises";import{dirname as uI,join as Pc}from"path";import{fileURLToPath as mI}from"url";var Sd={name:"@popmelt.com/core",version:"0.30.1",description:"A tiny, powerful design layer for humans and AI",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,packageManager:"pnpm@9.12.0",engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint . && node scripts/check-eslint-suppressions.mjs","pack:smoke":"node scripts/pack-smoke.mjs","peer:smoke":"node scripts/peer-compat-smoke.mjs","vue:smoke":"pnpm run build && node scripts/vue-install-smoke.mjs","nuxt:smoke":"pnpm run build && node scripts/nuxt-install-smoke.mjs","astro:smoke":"pnpm run build && node scripts/framework-install-smoke.mjs astro","svelte:smoke":"pnpm run build && node scripts/framework-install-smoke.mjs svelte && node scripts/framework-install-smoke.mjs sveltekit",prepublishOnly:"pnpm run verify",test:"vitest run","test:coverage":"vitest run --coverage.enabled","test:browser":"pnpm run build && tsc --noEmit -p tsconfig.browser.json && vitest run --config vitest.browser.config.ts","test:browser:mutation":"node e2e/check-lifecycle-mutation.mjs","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run format && pnpm run lint && pnpm run test:coverage && pnpm run build && pnpm run pack:smoke"},exports:{".":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./browser":{types:"./dist/browser.d.mts",import:"./dist/browser.mjs"},"./server":{types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./next":{types:"./dist/plugin-next.d.mts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./vite/client":{types:"./dist/vite-client.d.ts"},"./astro":{types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"},"./nuxt":{types:"./dist/plugin-nuxt.d.mts",import:"./dist/plugin-nuxt.mjs",default:"./dist/plugin-nuxt.mjs"},"./media":{types:"./dist/media.d.mts",import:"./dist/media.mjs"},"./three":{types:"./dist/adapter-three.d.mts",import:"./dist/adapter-three.mjs"},"./react-three-fiber":{types:"./dist/adapter-react-three-fiber.d.mts",import:"./dist/adapter-react-three-fiber.mjs"}},files:["dist","codex-plugin","claude-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.3"},optionalDependencies:{"@napi-rs/keyring":"2.1.0"},peerDependencies:{nuxt:">=4.5.2 <5","lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0","@react-three/fiber":">=8.0.0",three:">=0.150.0"},peerDependenciesMeta:{nuxt:{optional:!0},next:{optional:!0},"@react-three/fiber":{optional:!0},three:{optional:!0}},devDependencies:{nuxt:"4.6.3","@kit/eslint-config":"workspace:^","@react-three/fiber":"9.7.0","@tanstack/react-router":"1.120.5","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/three":"^0.185.4","@types/ws":"8.18.1","@vitejs/plugin-react":"^5.1.1","@vitejs/plugin-vue":"6.0.8","@vitest/coverage-v8":"4.1.12",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.5.28",prettier:"3.5.3",react:"19.1.0","react-dom":"19.1.0",three:"^0.185.1",tsup:"^8.5.1",typescript:"^5.8.3",vite:"7.3.7",vitest:"4.1.12",vue:"3.5.44","vue-router":"5.3.1"},pnpm:{overrides:{"postcss@<8.5.23":"8.5.23","source-map-js@<1.2.2":"1.2.2","esbuild@<0.28.1":"0.28.1","sharp@<0.35.5":"0.35.5"}}};var Ft=Sd.version;import{spawn as oh}from"child_process";import{createInterface as sh}from"readline";async function io(n,e){let t=oh(process.env.CODEX_APP_RUNTIME_CLI_PATH||"codex",["app-server","--stdio"],{stdio:["pipe","pipe","ignore"]}),r=sh({input:t.stdout});try{return await new Promise((i,o)=>{let s=()=>o(new Error("Codex did not confirm "+n)),a=setTimeout(()=>{s(),t.kill()},1e4);t.once("close",()=>{clearTimeout(a),s()}),t.once("error",s),t.stdin.on("error",s);let c=d=>t.stdin.write(JSON.stringify(d)+`
15
15
  `);r.on("line",d=>{let u;try{u=JSON.parse(d)}catch{return}if(u.error&&(u.id===1||u.id===2)){s();return}u.id===1&&u.result?(c({method:"initialized"}),c({id:2,method:n,params:e})):u.id===2&&u.result&&i(u.result)}),c({id:1,method:"initialize",params:{clientInfo:{name:"popmelt-canvas-notes",version:"1"},capabilities:{experimentalApi:!0}}})})}finally{r.close(),t.kill()}}async function kd({threadId:n,clientUserMessageId:e,input:t}){let{queuedSubmission:r}=await io("thread/queue/add",{threadId:n,clientUserMessageId:e,input:t});if(r?.clientUserMessageId!==e)throw new Error("Codex returned an unexpected canvas note ID")}async function Vx(n,e){let t=new Set,r=null;do{let i=await io("thread/items/list",{threadId:n,turnId:e,limit:64,sortDirection:"asc",cursor:r});for(let{turnId:o,item:s}of i.data)o===e&&s.type==="userMessage"&&s.clientId&&t.add(s.clientId);r=i.nextCursor}while(r);return[...t]}async function Td(n,e){return(await io("thread/queue/list",{threadId:n,limit:100})).data.some(i=>i.clientUserMessageId===e)?!0:(await io("thread/items/list",{threadId:n,sortDirection:"desc",limit:100})).data.some(({item:i})=>i.type==="userMessage"&&i.clientId===e)}import{readFile as Ih}from"fs/promises";import{join as xh}from"path";import{randomUUID as _d}from"crypto";function Qn(n){let e=n?.requestItems?.flatMap(r=>r.kind==="annotation"&&r.text.trim()?[r.text.trim()]:[]);if(e?.length)return e.join("; ");let t=n?.requestItems?.flatMap(r=>r.kind==="changes"?[`${r.elementLabel} [${r.changes.join(", ")}]`]:[]);return t?.length?t.join("; "):n?.requestText?.trim()||void 0}function Pd(n){let e=n.instruction?.trim();return e?n.attachments?.some(r=>r.name?.trim()===e)?null:e:null}function qs(n,e){let t=n?.tagName?.toLowerCase(),r=n?.id?`#${n.id}`:"",i=n?.className?`.${n.className.trim().split(/\s+/).slice(0,2).join(".")}`:"",o=t?`${t}${r}${i}`:e;return n?.reactComponent?`<${n.reactComponent}> ${o}`:o}function ah(n){let e=n.elements?.[0]?.reactComponent||n.elements?.[0]?.tagName||n.linkedSelector,t=n.type&&n.type!=="annotation"?`${n.type} annotation`:"Annotation";return e?`${t} on ${e}`:t}function Xn(n){let e=n.annotations.map(i=>{let o=i.interactionEpisode?.steps.length??0;return{kind:"annotation",annotationId:i.id,pathname:i.pathname,text:Pd(i)??ah(i),...o>0?{interactionEpisodeStepCount:o}:{}}}),t=new Map,r=i=>{let o=`${i.pathname??""}:${i.durableSelector??i.selector}`,s=t.get(o);if(s){s.changes.push(i.text),i.annotationNumber!==void 0&&(s.annotationNumber===void 0||i.annotationNumber<s.annotationNumber)&&(s.annotationNumber=i.annotationNumber);return}let a={kind:"changes",elementKey:o,elementLabel:qs(i.element,i.selector),...i.annotationNumber!==void 0?{annotationNumber:i.annotationNumber}:{},pathname:i.pathname,changes:[i.text]};t.set(o,a),e.push(a)};for(let i of n.styleModifications??[])for(let o of i.changes)r({...i,text:`${o.property}: ${o.original||"unset"} \u2192 ${o.modified||"unset"}${o.token?` (${o.token})`:""}`});for(let i of n.textModifications??[])r({...i,text:`Text: ${i.original||"empty"} \u2192 ${i.modified||"empty"}`});for(let i of n.domModifications??[])r({...i,text:i.operation==="copy"?"Copied element":"Moved element"});return n.spacingTokenChanges?.length&&e.push({kind:"changes",elementKey:"spacing-tokens",elementLabel:"Spacing tokens",changes:n.spacingTokenChanges.map(i=>`${i.tokenName}: ${i.originalPx}px \u2192 ${i.newPx}px`)}),e}function oo(n){let e=n.annotations.flatMap(i=>{let o=Pd(i);return o?[{instruction:o,pathname:i.pathname}]:[]});if(e.length===0)return;if(new Set(e.map(i=>i.pathname).filter(Boolean)).size<=1)return e.map(i=>i.instruction).join(`
16
16
 
17
17
  `);let r=new Map;for(let i of e){let o=i.pathname||"(unknown)",s=r.get(o)??[];s.push(i.instruction),r.set(o,s)}return[...r.entries()].map(([i,o])=>`\`${i}\`
@@ -1 +1 @@
1
- import{a as o,b as d,c as l,d as s}from"./chunk-ZQTLCQPC.mjs";function g(r){let p=r?.basePath??"/popmelt",e={port:null,projectId:null},n="virtual:popmelt/bridge",i=`\0${n}`;return{name:"popmelt",resolveId(t){if(t===n)return i},load(t){if(t===i)return`export const bridgeUrl = ${JSON.stringify(e.port===null?null:`http://localhost:${e.port}`)}; export const projectId = ${JSON.stringify(e.projectId)};`},async configureServer(t){e=await o(r,t,5173),await d(e,t),t.middlewares.use(l(p,()=>e))},transformIndexHtml(){if(e.port!==null)return[{tag:"script",attrs:{type:"text/javascript"},children:s(e),injectTo:"head-prepend"}]}}}export{g as a};
1
+ import{a as o,b as d,c as l,d as s}from"./chunk-42LISDBE.mjs";function g(r){let p=r?.basePath??"/popmelt",e={port:null,projectId:null},n="virtual:popmelt/bridge",i=`\0${n}`;return{name:"popmelt",resolveId(t){if(t===n)return i},load(t){if(t===i)return`export const bridgeUrl = ${JSON.stringify(e.port===null?null:`http://localhost:${e.port}`)}; export const projectId = ${JSON.stringify(e.projectId)};`},async configureServer(t){e=await o(r,t,5173),await d(e,t),t.middlewares.use(l(p,()=>e))},transformIndexHtml(){if(e.port!==null)return[{tag:"script",attrs:{type:"text/javascript"},children:s(e),injectTo:"head-prepend"}]}}}export{g as a};