openmagic 0.31.9 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var OpenMagicToolbar=(()=>{var Le=`
2
+ "use strict";var OpenMagicToolbar=(()=>{var Ce=`
3
3
  :host {
4
4
  all: initial;
5
5
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
@@ -372,48 +372,48 @@
372
372
  .om-msg:hover .om-copy-btn { opacity: 1; }
373
373
  .om-copy-btn:hover { color: #ccc; background: rgba(0,0,0,0.5); }
374
374
  .om-msg { position: relative; }
375
- `;var _=null,C=new Map,G=[],ge=[],B=!1,Te=!1,ue=null,he=0;function fe(){return Math.random().toString(36).slice(2)+Date.now().toString(36)}function ye(t,e){return Te=!0,new Promise((s,o)=>{let a=!1,i=setTimeout(()=>{a||(a=!0,o(new Error("Handshake timeout")),_?.close())},1e4);try{let r=window.location.hostname||"127.0.0.1",p=window.location.protocol==="https:"?"wss:":"ws:";_=new WebSocket(`${p}//${r}:${t}/__openmagic__/ws`),_.onopen=()=>{let c=fe();_.send(JSON.stringify({id:c,type:"handshake",payload:{token:e}})),C.set(c,m=>{if(m.type==="handshake.ok"){clearTimeout(i),B=!0,he=0;for(let d of ge)_?.send(d);ge=[],a||(a=!0,s())}else m.type==="error"&&(clearTimeout(i),a||(a=!0,o(new Error(m.payload?.message||"Handshake failed"))))})},_.onmessage=c=>{try{let m=JSON.parse(c.data);m.id&&C.has(m.id)&&(C.get(m.id)(m),(m.type==="llm.done"||m.type==="llm.error"||!m.type.startsWith("llm."))&&C.delete(m.id));for(let d of G)d(m)}catch{}},_.onclose=()=>{let c=B;if(B=!1,C.forEach((m,d)=>{m({type:"error",id:d,payload:{message:"Connection lost"}})}),C.clear(),!c&&!a){clearTimeout(i),a=!0,o(new Error("WebSocket closed before handshake"));return}if(c&&Te&&!ue){let m=Math.min(2e3*Math.pow(1.5,he),3e4);he++,ue=setTimeout(()=>{ue=null,ye(t,e).then(()=>{for(let d of G)d({type:"reconnected",payload:{}})}).catch(()=>{})},m)}},_.onerror=()=>{!B&&!a&&(clearTimeout(i),a=!0,o(new Error("WebSocket connection failed")))}}catch(r){clearTimeout(i),a||(a=!0,o(r))}})}function Ce(t){let e=JSON.stringify(t);_&&_.readyState===WebSocket.OPEN&&B?_.send(e):ge.push(e)}function S(t,e){return new Promise((s,o)=>{let a=fe(),i=setTimeout(()=>{C.delete(a),o(new Error("Request timeout"))},3e4);C.set(a,r=>{clearTimeout(i),r.type==="error"?o(new Error(r.payload?.message||"Unknown error")):s(r)}),Ce({id:a,type:t,payload:e})})}function He(t,e,s){return new Promise((o,a)=>{let i=fe(),r=setTimeout(()=>{C.delete(i),a(new Error("Stream timeout"))},12e4);C.set(i,p=>{p.type==="llm.chunk"?s(p.payload?.delta||""):p.type==="llm.done"?(clearTimeout(r),C.delete(i),o(p.payload)):(p.type==="llm.error"||p.type==="error")&&(clearTimeout(r),C.delete(i),a(new Error(p.payload?.message||"Stream error")))}),Ce({id:i,type:t,payload:e})})}function Pe(t){return G.push(t),()=>{G=G.filter(e=>e!==t)}}function be(){return B}var _e=["display","position","width","height","margin","padding","color","background-color","background","font-size","font-weight","font-family","border","border-radius","box-shadow","flex-direction","justify-content","align-items","gap","grid-template-columns","grid-template-rows","overflow","opacity","z-index","text-align","line-height","letter-spacing"];function Re(t){let e=window.getComputedStyle(t),s={};for(let d of _e)s[d]=e.getPropertyValue(d);let o=t.getBoundingClientRect(),a={};if(t.parentElement&&t.parentElement!==document.body){let d=window.getComputedStyle(t.parentElement);for(let x of _e)a[x]=d.getPropertyValue(x)}let i=[];if(t.parentElement){let d=Array.from(t.parentElement.children),x=d.indexOf(t),g=Math.max(0,x-3),l=Math.min(d.length,x+4);g>0&&i.push(`... ${g} elements before ...`);for(let u=g;u<l;u++){let y=d[u],h=y.tagName.toLowerCase(),f=(y.className||"").toString().slice(0,60);y===t?i.push(`[SELECTED] <${h} class="${f}">`):i.push(`<${h} class="${f}">`)}l<d.length&&i.push(`... ${d.length-l} elements after ...`)}let r=at(t),p={};for(let d of Array.from(t.attributes))(d.name.startsWith("aria-")||d.name==="role"||d.name==="tabindex")&&(p[d.name]=d.value);let c=[];for(let d of Array.from(t.attributes))d.name.startsWith("on")&&c.push(d.name);let m=rt(t);return{tagName:t.tagName.toLowerCase(),id:t.id||"",className:t.className||"",textContent:(t.textContent||"").trim().slice(0,200),outerHTML:nt(t),cssSelector:ot(t),xpath:st(t),computedStyles:s,ancestry:et(t),componentHint:tt(t),rect:{x:o.x,y:o.y,width:o.width,height:o.height},parentStyles:a,siblings:i,matchedCssRules:r,viewport:{width:window.innerWidth,height:window.innerHeight},ariaAttributes:p,eventHandlers:c,reactProps:m}}function et(t,e=5){let s=[],o=t.parentElement;for(;o&&o!==document.body&&s.length<e;){let a=o.tagName.toLowerCase(),i=(typeof o.className=="string"?o.className:"").split(/\s+/).filter(r=>r.length>1&&!r.startsWith("_")).slice(0,3).join(".");s.push(i?`${a}.${i}`:a),o=o.parentElement}return s}function tt(t){let e=t;for(;e&&e!==document.body;){let s=e.getAttribute("data-component")||e.getAttribute("data-testid")||e.getAttribute("data-cy");if(s)return s;let o=Object.keys(e);for(let a of o)if(a.startsWith("__reactFiber")||a.startsWith("__reactInternalInstance"))try{let i=e[a],r=i?.type?.name||i?.type?.displayName||i?.return?.type?.name||i?.return?.type?.displayName;if(r&&r!=="div"&&r!=="span"&&r.length>1)return r}catch{}e=e.parentElement}return""}function nt(t){let e=t.cloneNode(!0);e.querySelectorAll("script, style, svg").forEach(a=>a.remove());let o=e.outerHTML;if(o.length>2e3){let a=t.tagName.toLowerCase(),i=Array.from(t.attributes).map(p=>`${p.name}="${p.value}"`).join(" "),r=Array.from(t.children).slice(0,5).map(p=>`<${p.tagName.toLowerCase()} .../>`).join(`
376
- `);o=`<${a} ${i}>
377
- ${r}
375
+ `;var O=null,N=new Map,ee=[],ye=[],J=!1,He=!1,ge=null,fe=0;function be(){return Math.random().toString(36).slice(2)+Date.now().toString(36)}function xe(t,e){return He=!0,new Promise((s,o)=>{let r=!1,l=setTimeout(()=>{r||(r=!0,o(new Error("Handshake timeout")),O?.close())},1e4);try{let i=window.location.hostname||"127.0.0.1",d=window.location.protocol==="https:"?"wss:":"ws:";O=new WebSocket(`${d}//${i}:${t}/__openmagic__/ws`),O.onopen=()=>{let c=be();O.send(JSON.stringify({id:c,type:"handshake",payload:{token:e}})),N.set(c,p=>{if(p.type==="handshake.ok"){clearTimeout(l),J=!0,fe=0;for(let h of ye)O?.send(h);ye=[],r||(r=!0,s())}else p.type==="error"&&(clearTimeout(l),r||(r=!0,o(new Error(p.payload?.message||"Handshake failed"))))})},O.onmessage=c=>{try{let p=JSON.parse(c.data);p.id&&N.has(p.id)&&(N.get(p.id)(p),(p.type==="llm.done"||p.type==="llm.error"||!p.type.startsWith("llm."))&&N.delete(p.id));for(let h of ee)h(p)}catch{}},O.onclose=()=>{let c=J;if(J=!1,N.forEach((p,h)=>{p({type:"error",id:h,payload:{message:"Connection lost"}})}),N.clear(),!c&&!r){clearTimeout(l),r=!0,o(new Error("WebSocket closed before handshake"));return}if(c&&He&&!ge){let p=Math.min(2e3*Math.pow(1.5,fe),3e4);fe++,ge=setTimeout(()=>{ge=null,xe(t,e).then(()=>{for(let h of ee)h({type:"reconnected",payload:{}})}).catch(()=>{})},p)}},O.onerror=()=>{!J&&!r&&(clearTimeout(l),r=!0,o(new Error("WebSocket connection failed")))}}catch(i){clearTimeout(l),r||(r=!0,o(i))}})}function Pe(t){let e=JSON.stringify(t);O&&O.readyState===WebSocket.OPEN&&J?O.send(e):ye.push(e)}function M(t,e){return new Promise((s,o)=>{let r=be(),l=setTimeout(()=>{N.delete(r),o(new Error("Request timeout"))},3e4);N.set(r,i=>{clearTimeout(l),i.type==="error"?o(new Error(i.payload?.message||"Unknown error")):s(i)}),Pe({id:r,type:t,payload:e})})}function Ne(t,e,s){return new Promise((o,r)=>{let l=be(),i=setTimeout(()=>{N.delete(l),r(new Error("Stream timeout"))},12e4);N.set(l,d=>{d.type==="llm.chunk"?s(d.payload?.delta||""):d.type==="llm.done"?(clearTimeout(i),N.delete(l),o(d.payload)):(d.type==="llm.error"||d.type==="error")&&(clearTimeout(i),N.delete(l),r(new Error(d.payload?.message||"Stream error")))}),Pe({id:l,type:t,payload:e})})}function Re(t){return ee.push(t),()=>{ee=ee.filter(e=>e!==t)}}function ve(){return J}var _e=["display","position","width","height","margin","padding","color","background-color","background","font-size","font-weight","font-family","border","border-radius","box-shadow","flex-direction","justify-content","align-items","gap","grid-template-columns","grid-template-rows","overflow","opacity","z-index","text-align","line-height","letter-spacing"];function Ae(t){let e=window.getComputedStyle(t),s={};for(let a of _e)s[a]=e.getPropertyValue(a);let o=t.getBoundingClientRect(),r={};if(t.parentElement&&t.parentElement!==document.body){let a=window.getComputedStyle(t.parentElement);for(let g of _e)r[g]=a.getPropertyValue(g)}let l=[];if(t.parentElement){let a=Array.from(t.parentElement.children),g=a.indexOf(t),m=Math.max(0,g-3),u=Math.min(a.length,g+4);m>0&&l.push(`... ${m} elements before ...`);for(let f=m;f<u;f++){let b=a[f],y=b.tagName.toLowerCase(),v=(b.className||"").toString().slice(0,60);b===t?l.push(`[SELECTED] <${y} class="${v}">`):l.push(`<${y} class="${v}">`)}u<a.length&&l.push(`... ${a.length-u} elements after ...`)}let i=[],d=Array.from(t.children).slice(0,12);for(let a=0;a<d.length;a++){let g=d[a],m=g.getBoundingClientRect(),u=window.getComputedStyle(g),f=null;if(a<d.length-1){let b=d[a+1].getBoundingClientRect();f={vertical:Math.round(b.top-m.bottom),horizontal:Math.round(b.left-m.right)}}i.push({tag:g.tagName.toLowerCase(),className:(g.className||"").toString().slice(0,80),rect:{x:Math.round(m.x),y:Math.round(m.y),width:Math.round(m.width),height:Math.round(m.height)},gapToNext:f,margin:u.margin,padding:u.padding})}let c=rt(t),p=lt(t,c),h={};for(let a of Array.from(t.attributes))(a.name.startsWith("aria-")||a.name==="role"||a.name==="tabindex")&&(h[a.name]=a.value);let x=[];for(let a of Array.from(t.attributes))a.name.startsWith("on")&&x.push(a.name);let w=it(t);return{tagName:t.tagName.toLowerCase(),id:t.id||"",className:t.className||"",textContent:(t.textContent||"").trim().slice(0,200),outerHTML:ot(t),cssSelector:st(t),xpath:at(t),computedStyles:s,ancestry:tt(t),componentHint:nt(t),rect:{x:o.x,y:o.y,width:o.width,height:o.height},parentStyles:r,siblings:l,childrenLayout:i,matchedCssRules:c,resolvedClasses:p,viewport:{width:window.innerWidth,height:window.innerHeight},ariaAttributes:h,eventHandlers:x,reactProps:w}}function tt(t,e=5){let s=[],o=t.parentElement;for(;o&&o!==document.body&&s.length<e;){let r=o.tagName.toLowerCase(),l=(typeof o.className=="string"?o.className:"").split(/\s+/).filter(i=>i.length>1&&!i.startsWith("_")).slice(0,3).join(".");s.push(l?`${r}.${l}`:r),o=o.parentElement}return s}function nt(t){let e=t;for(;e&&e!==document.body;){let s=e.getAttribute("data-component")||e.getAttribute("data-testid")||e.getAttribute("data-cy");if(s)return s;let o=Object.keys(e);for(let r of o)if(r.startsWith("__reactFiber")||r.startsWith("__reactInternalInstance"))try{let l=e[r],i=l?.type?.name||l?.type?.displayName||l?.return?.type?.name||l?.return?.type?.displayName;if(i&&i!=="div"&&i!=="span"&&i.length>1)return i}catch{}e=e.parentElement}return""}function ot(t){let e=t.cloneNode(!0);e.querySelectorAll("script, style, svg").forEach(r=>r.remove());let o=e.outerHTML;if(o.length>2e3){let r=t.tagName.toLowerCase(),l=Array.from(t.attributes).map(d=>`${d.name}="${d.value}"`).join(" "),i=Array.from(t.children).slice(0,5).map(d=>`<${d.tagName.toLowerCase()} .../>`).join(`
376
+ `);o=`<${r} ${l}>
377
+ ${i}
378
378
  ${t.children.length>5?`<!-- +${t.children.length-5} more children -->`:""}
379
- </${a}>`}return o}function ot(t){if(t.id)return`#${CSS.escape(t.id)}`;let e=[],s=t;for(;s&&s!==document.body;){let o=s.tagName.toLowerCase();if(s.id){e.unshift(`#${CSS.escape(s.id)}`);break}if(s.className&&typeof s.className=="string"){let i=s.className.trim().split(/\s+/).filter(r=>!r.startsWith("__")&&r.length<30).slice(0,2).map(r=>CSS.escape(r));i.length>0&&(o+="."+i.join("."))}let a=s.parentElement;if(a){let i=Array.from(a.children).filter(r=>r.tagName===s.tagName);if(i.length>1){let r=i.indexOf(s)+1;o+=`:nth-of-type(${r})`}}e.unshift(o),s=s.parentElement}return e.join(" > ")}function st(t){let e=[],s=t;for(;s&&s!==document;){if(s.nodeType===Node.ELEMENT_NODE){let o=s,a=1,i=o.previousElementSibling;for(;i;)i.tagName===o.tagName&&a++,i=i.previousElementSibling;e.unshift(`${o.tagName.toLowerCase()}[${a}]`)}s=s.parentNode}return"/"+e.join("/")}function at(t){let e=[];try{for(let s of Array.from(document.styleSheets))try{let o=s.cssRules||s.rules;if(!o)continue;for(let a of Array.from(o))if(a instanceof CSSStyleRule)try{if(t.matches(a.selectorText)){let i=a.cssText;i.length>10&&i.length<500&&e.push(i)}}catch{}}catch{}}catch{}return e.slice(0,15)}function rt(t){try{let e=Object.keys(t);for(let s of e)if(s.startsWith("__reactFiber")||s.startsWith("__reactInternalInstance")){let o=t[s];if(!o?.memoizedProps)continue;let a=o.memoizedProps,i={},r=0;for(let[p,c]of Object.entries(a)){if(r>=10)break;if(p==="children")continue;let m=typeof c;m==="string"||m==="number"||m==="boolean"||c===null?(i[p]=c,r++):m==="function"?(i[p]="[function]",r++):Array.isArray(c)&&(i[p]=`[Array(${c.length})]`,r++)}return Object.keys(i).length>0?i:null}}catch{}return null}var H=null;function Ne(t){H||(H=document.createElement("div"),H.style.cssText=`
379
+ </${r}>`}return o}function st(t){if(t.id)return`#${CSS.escape(t.id)}`;let e=[],s=t;for(;s&&s!==document.body;){let o=s.tagName.toLowerCase();if(s.id){e.unshift(`#${CSS.escape(s.id)}`);break}if(s.className&&typeof s.className=="string"){let l=s.className.trim().split(/\s+/).filter(i=>!i.startsWith("__")&&i.length<30).slice(0,2).map(i=>CSS.escape(i));l.length>0&&(o+="."+l.join("."))}let r=s.parentElement;if(r){let l=Array.from(r.children).filter(i=>i.tagName===s.tagName);if(l.length>1){let i=l.indexOf(s)+1;o+=`:nth-of-type(${i})`}}e.unshift(o),s=s.parentElement}return e.join(" > ")}function at(t){let e=[],s=t;for(;s&&s!==document;){if(s.nodeType===Node.ELEMENT_NODE){let o=s,r=1,l=o.previousElementSibling;for(;l;)l.tagName===o.tagName&&r++,l=l.previousElementSibling;e.unshift(`${o.tagName.toLowerCase()}[${r}]`)}s=s.parentNode}return"/"+e.join("/")}function rt(t){let e=[];try{for(let s of Array.from(document.styleSheets))try{let o=s.cssRules||s.rules;if(!o)continue;for(let r of Array.from(o))if(r instanceof CSSStyleRule)try{if(t.matches(r.selectorText)){let l=r.cssText;l.length>10&&l.length<500&&e.push(l)}}catch{}}catch{}}catch{}return e.slice(0,15)}function it(t){try{let e=Object.keys(t);for(let s of e)if(s.startsWith("__reactFiber")||s.startsWith("__reactInternalInstance")){let o=t[s];if(!o?.memoizedProps)continue;let r=o.memoizedProps,l={},i=0;for(let[d,c]of Object.entries(r)){if(i>=10)break;if(d==="children")continue;let p=typeof c;p==="string"||p==="number"||p==="boolean"||c===null?(l[d]=c,i++):p==="function"?(l[d]="[function]",i++):Array.isArray(c)&&(l[d]=`[Array(${c.length})]`,i++)}return Object.keys(l).length>0?l:null}}catch{}return null}function lt(t,e){let s=[],o=(t.className||"").toString().trim().split(/\s+/).filter(Boolean);for(let r of o){let l=CSS.escape(r);for(let i of e)if(i.includes(`.${l}`)&&i.length<200){s.push({className:r,css:i});break}if(s.length>=20)break}return s}var R=null;function Oe(t){R||(R=document.createElement("div"),R.style.cssText=`
380
380
  position: fixed;
381
381
  pointer-events: none;
382
382
  z-index: 2147483646;
383
383
  border: 2px solid #6c5ce7;
384
384
  background: rgba(108, 92, 231, 0.1);
385
385
  transition: all 0.1s ease;
386
- `,H.dataset.openmagic="highlight",document.body.appendChild(H)),H.style.left=`${t.x}px`,H.style.top=`${t.y}px`,H.style.width=`${t.width}px`,H.style.height=`${t.height}px`,H.style.display="block"}function Ae(){H&&(H.style.display="none")}async function Oe(t){try{let e=t||document.body,s=await it(e);if(s)return{data:s}}catch{}try{let e=await lt(t);if(e)return{data:e}}catch(e){return{data:null,error:`Screenshot failed: ${e.message||"unknown error"}. Try using the image attachment button instead.`}}return{data:null,error:"Screenshot capture not available on this page. Try pasting or dragging an image instead."}}async function it(t){let e=t.getBoundingClientRect(),s=Math.min(e.width||window.innerWidth,1920),o=Math.min(e.height||window.innerHeight,1080),a=De(t,0,4);if(!a)return null;let i=`
386
+ `,R.dataset.openmagic="highlight",document.body.appendChild(R)),R.style.left=`${t.x}px`,R.style.top=`${t.y}px`,R.style.width=`${t.width}px`,R.style.height=`${t.height}px`,R.style.display="block"}function De(){R&&(R.style.display="none")}async function Ie(t){try{let e=t||document.body,s=await ct(e);if(s)return{data:s}}catch{}try{let e=await dt(t);if(e)return{data:e}}catch(e){return{data:null,error:`Screenshot failed: ${e.message||"unknown error"}. Try using the image attachment button instead.`}}return{data:null,error:"Screenshot capture not available on this page. Try pasting or dragging an image instead."}}async function ct(t){let e=t.getBoundingClientRect(),s=Math.min(e.width||window.innerWidth,1920),o=Math.min(e.height||window.innerHeight,1080),r=qe(t,0,4);if(!r)return null;let l=`
387
387
  <svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${o}">
388
388
  <foreignObject width="100%" height="100%">
389
389
  <div xmlns="http://www.w3.org/1999/xhtml" style="width:${s}px;height:${o}px;overflow:hidden;">
390
- ${a.outerHTML}
390
+ ${r.outerHTML}
391
391
  </div>
392
392
  </foreignObject>
393
- </svg>`,r=new Blob([i],{type:"image/svg+xml;charset=utf-8"}),p=URL.createObjectURL(r);return new Promise(c=>{let m=new Image,d=document.createElement("canvas"),x=Math.min(window.devicePixelRatio||1,2);d.width=s*x,d.height=o*x,m.onload=()=>{URL.revokeObjectURL(p);let g=d.getContext("2d");if(!g){c(null);return}g.scale(x,x),g.drawImage(m,0,0);try{c(d.toDataURL("image/png",.8))}catch{c(null)}},m.onerror=()=>{URL.revokeObjectURL(p),c(null)},setTimeout(()=>{URL.revokeObjectURL(p),c(null)},5e3),m.src=p})}async function lt(t){let e=t||document.documentElement,s=e.getBoundingClientRect(),o=document.createElement("canvas");o.width=400,o.height=300;let a=o.getContext("2d");return a?(a.fillStyle="#1a1a2e",a.fillRect(0,0,400,300),a.fillStyle="#e0e0e0",a.font="14px system-ui",a.fillText(`Element: <${e.tagName.toLowerCase()}>`,20,30),a.fillStyle="#888",a.font="12px system-ui",a.fillText(`Size: ${Math.round(s.width)}x${Math.round(s.height)}`,20,55),a.fillText(`Classes: ${(e.className||"").toString().slice(0,40)}`,20,75),a.fillText(`Page: ${window.location.pathname}`,20,95),a.fillStyle="#6c5ce7",a.font="11px system-ui",a.fillText("(Full screenshot unavailable \u2014 context sent as metadata)",20,130),o.toDataURL("image/png")):null}function De(t,e,s){if(e>s)return null;try{let o=t.cloneNode(!1);if(o.tagName==="SCRIPT"||o.tagName==="STYLE"||o.tagName==="SVG"||o.tagName==="CANVAS"||o.tagName==="VIDEO"||o.tagName==="IFRAME")return null;let a=window.getComputedStyle(t),i=["display","position","width","height","margin","padding","color","background-color","background","font-size","font-weight","font-family","border","border-radius","flex-direction","justify-content","align-items","gap","grid-template-columns","text-align","overflow"],r="";for(let p of i){let c=a.getPropertyValue(p);c&&c!=="normal"&&c!=="none"&&c!=="auto"&&c!=="0px"&&(r+=`${p}:${c};`)}o.setAttribute("style",r);for(let p=0;p<t.children.length&&p<20;p++){let c=De(t.children[p],e+1,s);c&&o.appendChild(c)}return o}catch{return null}}var ee=[];var Ie=!1;function je(){if(Ie)return;Ie=!0;let t=window.fetch;window.fetch=async function(...o){let a=new Request(...o),i={method:a.method,url:a.url,timestamp:Date.now()};try{let r=await t.apply(this,o);return i.status=r.status,i.duration=Date.now()-i.timestamp,xe(i),r}catch(r){throw i.status=0,i.duration=Date.now()-i.timestamp,xe(i),r}};let e=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(o,a,...i){return this.__om_method=o,this.__om_url=a,this.__om_start=Date.now(),e.apply(this,[o,a,...i])},XMLHttpRequest.prototype.send=function(...o){return this.addEventListener("loadend",()=>{xe({method:this.__om_method||"GET",url:this.__om_url||"",status:this.status,duration:Date.now()-(this.__om_start||Date.now()),timestamp:this.__om_start||Date.now()})}),s.apply(this,o)}}function xe(t){t.url.includes("__openmagic__")||(ee.push(t),ee.length>50&&ee.shift())}function ne(){return[...ee]}var te=[],ct=100,qe=!1;function ze(){if(qe)return;qe=!0;let t=["log","warn","error","info","debug"];for(let e of t){let s=console[e];console[e]=function(...o){te.push({level:e,args:o.map(a=>{try{return typeof a=="object"?JSON.stringify(a).slice(0,500):String(a)}catch{return String(a)}}),timestamp:Date.now()}),te.length>ct&&te.shift(),s.apply(console,o)}}}function oe(){return[...te]}function Be(t,e){return{selectedElement:t?{tagName:t.tagName,id:t.id,className:t.className,textContent:t.textContent,outerHTML:t.outerHTML,cssSelector:t.cssSelector,computedStyles:t.computedStyles}:void 0,screenshot:e||void 0,networkLogs:ne().map(s=>({method:s.method,url:s.url,status:s.status,duration:s.duration,timestamp:s.timestamp})),consoleLogs:oe().map(s=>({level:s.level,args:s.args,timestamp:s.timestamp}))}}var v={sparkle:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.582a.5.5 0 0 1 0 .962L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/></svg>',crosshair:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',camera:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/></svg>',chat:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',settings:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>',send:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>',x:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',externalLink:'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>',check:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>',copy:'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>',grip:'<svg width="7" height="14" viewBox="0 0 8 14" fill="currentColor"><circle cx="2" cy="2" r="1.2"/><circle cx="6" cy="2" r="1.2"/><circle cx="2" cy="7" r="1.2"/><circle cx="6" cy="7" r="1.2"/><circle cx="2" cy="12" r="1.2"/><circle cx="6" cy="12" r="1.2"/></svg>',network:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>',activity:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>',bug:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m8 2 1.88 1.88M14.12 3.88 16 2M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/></svg>',paperclip:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>',image:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>',trash:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>',minus:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/></svg>'},I={openai:{name:"OpenAI",keyUrl:"https://platform.openai.com/api-keys",keyPlaceholder:"sk-...",models:[{id:"gpt-5.4",name:"GPT-5.4"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini"},{id:"gpt-5.2",name:"GPT-5.2 Thinking"},{id:"o3",name:"o3"},{id:"o4-mini",name:"o4-mini"},{id:"gpt-4.1",name:"GPT-4.1"},{id:"gpt-4.1-mini",name:"GPT-4.1 Mini"}]},anthropic:{name:"Anthropic",keyUrl:"https://console.anthropic.com/settings/keys",keyPlaceholder:"sk-ant-...",models:[{id:"claude-opus-4-6",name:"Claude Opus 4.6"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5"}]},google:{name:"Google Gemini",keyUrl:"https://aistudio.google.com/apikey",keyPlaceholder:"AIza...",models:[{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro"},{id:"gemini-3-flash-preview",name:"Gemini 3 Flash"},{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro"},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash"}]},xai:{name:"xAI (Grok)",keyUrl:"https://console.x.ai/team/default/api-keys",keyPlaceholder:"xai-...",models:[{id:"grok-4.20-0309-reasoning",name:"Grok 4.20 Reasoning"},{id:"grok-4-1-fast-non-reasoning",name:"Grok 4.1 Fast"}]},deepseek:{name:"DeepSeek",keyUrl:"https://platform.deepseek.com/api_keys",keyPlaceholder:"sk-...",models:[{id:"deepseek-chat",name:"DeepSeek V3.2"},{id:"deepseek-reasoner",name:"DeepSeek R1"}]},mistral:{name:"Mistral",keyUrl:"https://console.mistral.ai/api-keys",keyPlaceholder:"...",models:[{id:"mistral-large-3-25-12",name:"Mistral Large 3"},{id:"codestral-2508",name:"Codestral"},{id:"devstral-2-25-12",name:"Devstral 2"}]},groq:{name:"Groq",keyUrl:"https://console.groq.com/keys",keyPlaceholder:"gsk_...",models:[{id:"meta-llama/llama-4-scout-17b-16e-instruct",name:"Llama 4 Scout"},{id:"llama-3.3-70b-versatile",name:"Llama 3.3 70B"}]},minimax:{name:"MiniMax",keyUrl:"https://platform.minimax.chat/user-center/basic-information/interface-key",keyPlaceholder:"MiniMax key...",models:[{id:"MiniMax-M2.7",name:"MiniMax M2.7"},{id:"MiniMax-M2.5",name:"MiniMax M2.5"}]},moonshot:{name:"Kimi (Moonshot)",keyUrl:"https://platform.moonshot.cn/console/api-keys",keyPlaceholder:"Moonshot key...",models:[{id:"kimi-k2.5",name:"Kimi K2.5"},{id:"kimi-k2-thinking",name:"Kimi K2 Thinking"}]},qwen:{name:"Qwen (Alibaba)",keyUrl:"https://dashscope.console.aliyun.com/apiKey",keyPlaceholder:"DashScope key...",models:[{id:"qwen3.5-plus",name:"Qwen 3.5 Plus"},{id:"qwen-max",name:"Qwen Max"}]},zhipu:{name:"Zhipu AI (GLM)",keyUrl:"https://open.bigmodel.cn/usercenter/apikeys",keyPlaceholder:"Zhipu key...",models:[{id:"glm-5",name:"GLM-5"},{id:"glm-4.7",name:"GLM-4.7"}]},doubao:{name:"Doubao (ByteDance)",keyUrl:"https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey",keyPlaceholder:"Volcano key...",models:[{id:"doubao-seed-2-0-pro",name:"Doubao Seed 2.0 Pro"},{id:"doubao-seed-2-0-code",name:"Doubao Seed 2.0 Code"}]},ollama:{name:"Ollama (Local)",keyPlaceholder:"not required",local:!0,models:[]},openrouter:{name:"OpenRouter",keyUrl:"https://openrouter.ai/settings/keys",keyPlaceholder:"sk-or-...",models:[]}};function ae(t){let e=new TextEncoder().encode(t),s="";for(let o=0;o<e.length;o+=32768)s+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(s)}function F(t){let e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);return new TextDecoder().decode(s)}var Se="0.31.9",n={connected:!1,panelOpen:!1,activePanel:"",selecting:!1,selectedElement:null,screenshot:null,messages:[],streaming:!1,streamContent:"",provider:"",model:"",hasApiKey:!1,configuredProviders:{},roots:[],updateAvailable:!1,latestVersion:"",saveStatus:"",networkCapture:!1,attachments:[],groundedFiles:[],minimized:!1},k,E,D,Ve,Ee,N;function dt(){try{sessionStorage.setItem("__om_state__",JSON.stringify({messages:n.messages,provider:n.provider,model:n.model,panelOpen:n.panelOpen,activePanel:n.activePanel}))}catch{}}function pt(){try{let t=JSON.parse(sessionStorage.getItem("__om_state__")||"{}");t.messages?.length&&(n.messages=t.messages),t.provider&&(n.provider=t.provider),t.model&&(n.model=t.model),t.panelOpen&&(n.panelOpen=t.panelOpen,n.activePanel=t.activePanel||"")}catch{}}function Fe(){if(document.querySelector("openmagic-toolbar"))return;pt();let t=document.createElement("openmagic-toolbar");t.dataset.openmagic="true",k=t.attachShadow({mode:"closed"});let e=document.createElement("style");e.textContent=Le,k.appendChild(e);let s=document.createElement("div");k.appendChild(s),s.innerHTML=mt(),E=s.querySelector(".om-toolbar"),D=s.querySelector(".om-prompt-input"),Ve=s.querySelector(".om-prompt-context"),Ee=s.querySelector(".om-panel"),N=s.querySelector(".om-panel-body"),document.body.appendChild(t),ut(s),Et();try{let r=JSON.parse(localStorage.getItem("__om_pos__")||"");r?.left&&r?.top&&(E.style.left=r.left,E.style.top=r.top,E.style.right="auto",E.style.bottom="auto")}catch{}je(),ze(),Lt();let a=document.querySelector("script[data-openmagic-token]")?.dataset.openmagicToken||window.__OPENMAGIC_TOKEN__,i=parseInt(window.location.port,10)||(window.location.protocol==="https:"?443:80);a&&ye(i,a).then(()=>(n.connected=!0,re(),S("config.get"))).then(r=>{let p=r.payload?.provider||"",c=r.payload?.model||"";n.provider=n.provider||p,n.model=n.model||c,n.configuredProviders=r.payload?.apiKeys||{},n.hasApiKey=n.configuredProviders[n.provider]||!1,n.roots=r.payload?.roots||[],n.panelOpen&&n.activePanel?q(n.activePanel):(!n.provider||!n.hasApiKey&&!Object.values(n.configuredProviders).some(Boolean))&&q("settings"),Y()}).catch(()=>{n.connected=!1,re()})}function mt(){return`
393
+ </svg>`,i=new Blob([l],{type:"image/svg+xml;charset=utf-8"}),d=URL.createObjectURL(i);return new Promise(c=>{let p=new Image,h=document.createElement("canvas"),x=Math.min(window.devicePixelRatio||1,2);h.width=s*x,h.height=o*x,p.onload=()=>{URL.revokeObjectURL(d);let w=h.getContext("2d");if(!w){c(null);return}w.scale(x,x),w.drawImage(p,0,0);try{c(h.toDataURL("image/png",.8))}catch{c(null)}},p.onerror=()=>{URL.revokeObjectURL(d),c(null)},setTimeout(()=>{URL.revokeObjectURL(d),c(null)},5e3),p.src=d})}async function dt(t){let e=t||document.documentElement,s=e.getBoundingClientRect(),o=document.createElement("canvas");o.width=400,o.height=300;let r=o.getContext("2d");return r?(r.fillStyle="#1a1a2e",r.fillRect(0,0,400,300),r.fillStyle="#e0e0e0",r.font="14px system-ui",r.fillText(`Element: <${e.tagName.toLowerCase()}>`,20,30),r.fillStyle="#888",r.font="12px system-ui",r.fillText(`Size: ${Math.round(s.width)}x${Math.round(s.height)}`,20,55),r.fillText(`Classes: ${(e.className||"").toString().slice(0,40)}`,20,75),r.fillText(`Page: ${window.location.pathname}`,20,95),r.fillStyle="#6c5ce7",r.font="11px system-ui",r.fillText("(Full screenshot unavailable \u2014 context sent as metadata)",20,130),o.toDataURL("image/png")):null}function qe(t,e,s){if(e>s)return null;try{let o=t.cloneNode(!1);if(o.tagName==="SCRIPT"||o.tagName==="STYLE"||o.tagName==="SVG"||o.tagName==="CANVAS"||o.tagName==="VIDEO"||o.tagName==="IFRAME")return null;let r=window.getComputedStyle(t),l=["display","position","width","height","margin","padding","color","background-color","background","font-size","font-weight","font-family","border","border-radius","flex-direction","justify-content","align-items","gap","grid-template-columns","text-align","overflow"],i="";for(let d of l){let c=r.getPropertyValue(d);c&&c!=="normal"&&c!=="none"&&c!=="auto"&&c!=="0px"&&(i+=`${d}:${c};`)}o.setAttribute("style",i);for(let d=0;d<t.children.length&&d<20;d++){let c=qe(t.children[d],e+1,s);c&&o.appendChild(c)}return o}catch{return null}}var ae=[];var je=!1;function Be(){if(je)return;je=!0;let t=window.fetch;window.fetch=async function(...o){let r=new Request(...o),l={method:r.method,url:r.url,timestamp:Date.now()};try{let i=await t.apply(this,o);return l.status=i.status,l.duration=Date.now()-l.timestamp,we(l),i}catch(i){throw l.status=0,l.duration=Date.now()-l.timestamp,we(l),i}};let e=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(o,r,...l){return this.__om_method=o,this.__om_url=r,this.__om_start=Date.now(),e.apply(this,[o,r,...l])},XMLHttpRequest.prototype.send=function(...o){return this.addEventListener("loadend",()=>{we({method:this.__om_method||"GET",url:this.__om_url||"",status:this.status,duration:Date.now()-(this.__om_start||Date.now()),timestamp:this.__om_start||Date.now()})}),s.apply(this,o)}}function we(t){t.url.includes("__openmagic__")||(ae.push(t),ae.length>50&&ae.shift())}function ie(){return[...ae]}var re=[],pt=100,ze=!1;function Fe(){if(ze)return;ze=!0;let t=["log","warn","error","info","debug"];for(let e of t){let s=console[e];console[e]=function(...o){re.push({level:e,args:o.map(r=>{try{return typeof r=="object"?JSON.stringify(r).slice(0,500):String(r)}catch{return String(r)}}),timestamp:Date.now()}),re.length>pt&&re.shift(),s.apply(console,o)}}}function le(){return[...re]}function Ue(t,e){return{selectedElement:t?{tagName:t.tagName,id:t.id,className:t.className,textContent:t.textContent,outerHTML:t.outerHTML,cssSelector:t.cssSelector,computedStyles:t.computedStyles}:void 0,screenshot:e||void 0,networkLogs:ie().map(s=>({method:s.method,url:s.url,status:s.status,duration:s.duration,timestamp:s.timestamp})),consoleLogs:le().map(s=>({level:s.level,args:s.args,timestamp:s.timestamp}))}}var k={sparkle:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.582a.5.5 0 0 1 0 .962L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/></svg>',crosshair:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',camera:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/></svg>',chat:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',settings:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>',send:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>',x:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',externalLink:'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>',check:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>',copy:'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>',grip:'<svg width="7" height="14" viewBox="0 0 8 14" fill="currentColor"><circle cx="2" cy="2" r="1.2"/><circle cx="6" cy="2" r="1.2"/><circle cx="2" cy="7" r="1.2"/><circle cx="6" cy="7" r="1.2"/><circle cx="2" cy="12" r="1.2"/><circle cx="6" cy="12" r="1.2"/></svg>',network:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>',activity:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>',bug:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m8 2 1.88 1.88M14.12 3.88 16 2M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/></svg>',paperclip:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>',image:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>',trash:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>',minus:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/></svg>'},B={openai:{name:"OpenAI",keyUrl:"https://platform.openai.com/api-keys",keyPlaceholder:"sk-...",models:[{id:"gpt-5.4",name:"GPT-5.4"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini"},{id:"gpt-5.2",name:"GPT-5.2 Thinking"},{id:"o3",name:"o3"},{id:"o4-mini",name:"o4-mini"},{id:"gpt-4.1",name:"GPT-4.1"},{id:"gpt-4.1-mini",name:"GPT-4.1 Mini"}]},anthropic:{name:"Anthropic",keyUrl:"https://console.anthropic.com/settings/keys",keyPlaceholder:"sk-ant-...",models:[{id:"claude-opus-4-6",name:"Claude Opus 4.6"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5"}]},google:{name:"Google Gemini",keyUrl:"https://aistudio.google.com/apikey",keyPlaceholder:"AIza...",models:[{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro"},{id:"gemini-3-flash-preview",name:"Gemini 3 Flash"},{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro"},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash"}]},xai:{name:"xAI (Grok)",keyUrl:"https://console.x.ai/team/default/api-keys",keyPlaceholder:"xai-...",models:[{id:"grok-4.20-0309-reasoning",name:"Grok 4.20 Reasoning"},{id:"grok-4-1-fast-non-reasoning",name:"Grok 4.1 Fast"}]},deepseek:{name:"DeepSeek",keyUrl:"https://platform.deepseek.com/api_keys",keyPlaceholder:"sk-...",models:[{id:"deepseek-chat",name:"DeepSeek V3.2"},{id:"deepseek-reasoner",name:"DeepSeek R1"}]},mistral:{name:"Mistral",keyUrl:"https://console.mistral.ai/api-keys",keyPlaceholder:"...",models:[{id:"mistral-large-3-25-12",name:"Mistral Large 3"},{id:"codestral-2508",name:"Codestral"},{id:"devstral-2-25-12",name:"Devstral 2"}]},groq:{name:"Groq",keyUrl:"https://console.groq.com/keys",keyPlaceholder:"gsk_...",models:[{id:"meta-llama/llama-4-scout-17b-16e-instruct",name:"Llama 4 Scout"},{id:"llama-3.3-70b-versatile",name:"Llama 3.3 70B"}]},minimax:{name:"MiniMax",keyUrl:"https://platform.minimax.chat/user-center/basic-information/interface-key",keyPlaceholder:"MiniMax key...",models:[{id:"MiniMax-M2.7",name:"MiniMax M2.7"},{id:"MiniMax-M2.5",name:"MiniMax M2.5"}]},moonshot:{name:"Kimi (Moonshot)",keyUrl:"https://platform.moonshot.cn/console/api-keys",keyPlaceholder:"Moonshot key...",models:[{id:"kimi-k2.5",name:"Kimi K2.5"},{id:"kimi-k2-thinking",name:"Kimi K2 Thinking"}]},qwen:{name:"Qwen (Alibaba)",keyUrl:"https://dashscope.console.aliyun.com/apiKey",keyPlaceholder:"DashScope key...",models:[{id:"qwen3.5-plus",name:"Qwen 3.5 Plus"},{id:"qwen-max",name:"Qwen Max"}]},zhipu:{name:"Zhipu AI (GLM)",keyUrl:"https://open.bigmodel.cn/usercenter/apikeys",keyPlaceholder:"Zhipu key...",models:[{id:"glm-5",name:"GLM-5"},{id:"glm-4.7",name:"GLM-4.7"}]},doubao:{name:"Doubao (ByteDance)",keyUrl:"https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey",keyPlaceholder:"Volcano key...",models:[{id:"doubao-seed-2-0-pro",name:"Doubao Seed 2.0 Pro"},{id:"doubao-seed-2-0-code",name:"Doubao Seed 2.0 Code"}]},ollama:{name:"Ollama (Local)",keyPlaceholder:"not required",local:!0,models:[]},openrouter:{name:"OpenRouter",keyUrl:"https://openrouter.ai/settings/keys",keyPlaceholder:"sk-or-...",models:[]}};function de(t){let e=new TextEncoder().encode(t),s="";for(let o=0;o<e.length;o+=32768)s+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(s)}function X(t){let e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);return new TextDecoder().decode(s)}var Ee="0.33.0",n={connected:!1,panelOpen:!1,activePanel:"",selecting:!1,selectedElement:null,screenshot:null,messages:[],streaming:!1,streamContent:"",provider:"",model:"",hasApiKey:!1,configuredProviders:{},roots:[],updateAvailable:!1,latestVersion:"",saveStatus:"",networkCapture:!1,attachments:[],groundedFiles:[],minimized:!1},E,C,z,Xe,Le,D;function mt(){try{sessionStorage.setItem("__om_state__",JSON.stringify({messages:n.messages,provider:n.provider,model:n.model,panelOpen:n.panelOpen,activePanel:n.activePanel}))}catch{}}function ut(){try{let t=JSON.parse(sessionStorage.getItem("__om_state__")||"{}");t.messages?.length&&(n.messages=t.messages),t.provider&&(n.provider=t.provider),t.model&&(n.model=t.model),t.panelOpen&&(n.panelOpen=t.panelOpen,n.activePanel=t.activePanel||"")}catch{}}function We(){if(document.querySelector("openmagic-toolbar"))return;ut();let t=document.createElement("openmagic-toolbar");t.dataset.openmagic="true",E=t.attachShadow({mode:"closed"});let e=document.createElement("style");e.textContent=Ce,E.appendChild(e);let s=document.createElement("div");E.appendChild(s),s.innerHTML=ht(),C=s.querySelector(".om-toolbar"),z=s.querySelector(".om-prompt-input"),Xe=s.querySelector(".om-prompt-context"),Le=s.querySelector(".om-panel"),D=s.querySelector(".om-panel-body"),document.body.appendChild(t),gt(s),Lt();try{let i=JSON.parse(localStorage.getItem("__om_pos__")||"");i?.left&&i?.top&&(C.style.left=i.left,C.style.top=i.top,C.style.right="auto",C.style.bottom="auto")}catch{}Be(),Fe(),Ct();let r=document.querySelector("script[data-openmagic-token]")?.dataset.openmagicToken||window.__OPENMAGIC_TOKEN__,l=parseInt(window.location.port,10)||(window.location.protocol==="https:"?443:80);r&&xe(l,r).then(()=>(n.connected=!0,pe(),M("config.get"))).then(i=>{let d=i.payload?.provider||"",c=i.payload?.model||"";n.provider=n.provider||d,n.model=n.model||c,n.configuredProviders=i.payload?.apiKeys||{},n.hasApiKey=n.configuredProviders[n.provider]||!1,n.roots=i.payload?.roots||[],n.panelOpen&&n.activePanel?F(n.activePanel):(!n.provider||!n.hasApiKey&&!Object.values(n.configuredProviders).some(Boolean))&&F("settings"),se()}).catch(()=>{n.connected=!1,pe()})}function ht(){return`
394
394
  <div class="om-toolbar">
395
395
  <div class="om-toolbar-header">
396
- <span class="om-grab">${v.grip}</span>
396
+ <span class="om-grab">${k.grip}</span>
397
397
  <span class="om-pill-brand">
398
398
  <span class="om-pill-text">\u2728OpenMagic\u{1FA84}</span>
399
399
  </span>
400
400
  <span class="om-pill-divider"></span>
401
- <button class="om-pill-btn" data-action="select" title="Select element">${v.crosshair}</button>
402
- <button class="om-pill-btn" data-action="screenshot" title="Screenshot">${v.camera}</button>
403
- <button class="om-pill-btn" data-action="network" title="Network & Performance">${v.activity}</button>
401
+ <button class="om-pill-btn" data-action="select" title="Select element">${k.crosshair}</button>
402
+ <button class="om-pill-btn" data-action="screenshot" title="Screenshot">${k.camera}</button>
403
+ <button class="om-pill-btn" data-action="network" title="Network & Performance">${k.activity}</button>
404
404
  <span class="om-pill-divider"></span>
405
- <button class="om-pill-btn" data-action="chat" title="Chat">${v.chat}</button>
406
- <button class="om-pill-btn" data-action="settings" title="Settings">${v.settings}</button>
407
- <button class="om-pill-btn" data-action="minimize" title="Minimize">${v.minus}</button>
405
+ <button class="om-pill-btn" data-action="chat" title="Chat">${k.chat}</button>
406
+ <button class="om-pill-btn" data-action="settings" title="Settings">${k.settings}</button>
407
+ <button class="om-pill-btn" data-action="minimize" title="Minimize">${k.minus}</button>
408
408
  <span class="om-status-dot disconnected"></span>
409
409
  </div>
410
410
  <div class="om-panel om-hidden">
411
411
  <div class="om-panel-header">
412
412
  <span class="om-panel-title"></span>
413
- <span class="om-panel-version">v${Se}</span>
414
- <button class="om-panel-bug" data-action="report-issue" title="Report a bug on GitHub">${v.bug}</button>
415
- <button class="om-panel-clear" data-action="clear-chat" title="Clear chat">${v.trash}</button>
416
- <button class="om-panel-close" data-action="close-panel">${v.x}</button>
413
+ <span class="om-panel-version">v${Ee}</span>
414
+ <button class="om-panel-bug" data-action="report-issue" title="Report a bug on GitHub">${k.bug}</button>
415
+ <button class="om-panel-clear" data-action="clear-chat" title="Clear chat">${k.trash}</button>
416
+ <button class="om-panel-close" data-action="close-panel">${k.x}</button>
417
417
  </div>
418
418
  <div class="om-panel-body"></div>
419
419
  </div>
@@ -427,37 +427,37 @@
427
427
  <div class="om-prompt-attachments"></div>
428
428
  <div class="om-prompt-row">
429
429
  <div class="om-prompt-context"></div>
430
- <button class="om-prompt-attach" data-action="attach-image" title="Attach image">${v.paperclip}</button>
430
+ <button class="om-prompt-attach" data-action="attach-image" title="Attach image">${k.paperclip}</button>
431
431
  <input class="om-prompt-input" type="text" placeholder="Describe what to change..." autocomplete="off" />
432
- <button class="om-prompt-send" data-action="prompt-send">${v.send}</button>
432
+ <button class="om-prompt-send" data-action="prompt-send">${k.send}</button>
433
433
  <input type="file" class="om-file-input om-hidden" accept="image/*" multiple />
434
434
  </div>
435
- </div>`}function ut(t){t.addEventListener("click",o=>{let a=o.target.closest("[data-action]");if(!a)return;o.preventDefault(),o.stopPropagation();let i=a.dataset.action;yt(i,a)}),t.addEventListener("change",o=>{let a=o.target,i=a.dataset.field;i&&(i==="provider"?(n.provider=a.value,n.model=I[n.provider]?.models[0]?.id||"",n.hasApiKey=n.configuredProviders[n.provider]||I[n.provider]?.local||!1,n.saveStatus="",M()):i==="model"&&(n.model=a.value))}),D.addEventListener("keydown",o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),ke())});let e=t.querySelector(".om-file-input");e&&e.addEventListener("change",()=>{we(e.files),e.value=""});let s=t.querySelector(".om-prompt-row");s&&(s.addEventListener("dragover",o=>{o.preventDefault(),s.style.borderColor="rgba(108, 92, 231, 0.5)"}),s.addEventListener("dragleave",()=>{s.style.borderColor=""}),s.addEventListener("drop",o=>{o.preventDefault(),s.style.borderColor="";let a=o.dataTransfer;a?.files?.length&&we(a.files)}),D.addEventListener("paste",o=>{let a=o.clipboardData?.items;if(a){for(let i=0;i<a.length;i++)if(a[i].type.startsWith("image/")){let r=a[i].getAsFile();if(r){let p=new DataTransfer;p.items.add(r),we(p.files)}}}})),Pe(o=>{o.type==="reconnected"&&(n.connected=!0,re())}),document.addEventListener("keydown",o=>{if((o.ctrlKey||o.metaKey)&&o.shiftKey&&(o.key==="O"||o.key==="o")){if(o.preventDefault(),n.minimized){n.minimized=!1,E.querySelectorAll(".om-pill-btn:not([data-action='minimize']), .om-pill-divider, .om-status-dot").forEach(r=>r.style.display="");let i=k.querySelector(".om-prompt-row");i&&i.classList.remove("om-hidden")}else n.panelOpen?ie():q("chat");return}if(o.key==="Escape"){if(n.selecting)return;n.panelOpen&&(ie(),o.preventDefault())}}),D.addEventListener("keydown",o=>{(o.ctrlKey||o.metaKey)&&o.key==="Enter"&&(o.preventDefault(),ke())})}function Je(t){return n.roots.length>0?n.roots[0]+"/"+t:t}function ht(t,e){let s=e.split(`
436
- `).map(r=>r.trim()).filter(r=>r.length>0);if(s.length===0)return null;let o=t.split(`
437
- `),a=s[0],i=s[s.length-1];for(let r=0;r<o.length;r++){if(o[r].trim()!==a||r+s.length>o.length)continue;let p=!0;for(let c=0;c<s.length;c++)if(o[r+c].trim()!==s[c]){p=!1;break}if(p){let c=0;for(let d=0;d<r;d++)c+=o[d].length+1;let m=c;for(let d=r;d<r+s.length;d++)m+=o[d].length+1;return m>0&&m<=t.length&&t[m-1]===`
438
- `&&m--,{start:c,end:m}}}return null}async function Ue(t){let e=t.dataset.file,s=t.dataset.search,o=t.dataset.replace;if(!e||!s||!o)return;t.disabled=!0,t.innerHTML='<span class="om-spinner"></span>',t.style.opacity="0.5",t.style.pointerEvents="none";let a=t.closest(".om-diff-card");if(a){let c=a.querySelector(".om-diff-actions");c&&(c.innerHTML='<span class="om-spinner"></span> Applying...')}await new Promise(c=>requestAnimationFrame(c));let i,r;try{i=F(s),r=F(o)}catch{n.messages.push({role:"system",content:`Failed to decode diff data for ${e}`}),M();return}let p=Je(e);try{if(!i&&r){if((await S("fs.write",{path:p,content:r}))?.payload?.ok===!1)n.messages.push({role:"system",content:`Write failed: ${e}`});else{let y=a?.dataset.diffIdx;y!==void 0?n.messages[parseInt(y)]={role:"system",content:`Created ${e}`}:n.messages.push({role:"system",content:`Created ${e}`})}M(),U();return}let c,m=p,d=[p];e!==p&&d.push(e);let x=e.split("/").pop()||e,g=n.roots[0]||"",l=g?`${g}/${x}`:x;l!==p&&l!==e&&d.push(l);for(let u of d){let h=(await S("fs.read",{path:u}).catch(()=>null))?.payload?.content;if(h!=null&&String(h).length>0){c=String(h),m=u;break}}if(!c)n.messages.push({role:"system",content:`Could not read ${e} \u2014 tried: ${d.join(", ")}`});else{let u=c.split(i).length-1;if(u===1){let y=await S("fs.write",{path:m,content:c.replace(i,r)});if(y?.payload?.ok===!1)n.messages.push({role:"system",content:`Write failed: ${e} - ${y.payload?.error||"unknown"}`});else{let h=a?.dataset.diffIdx;h!==void 0?n.messages[parseInt(h)]={role:"system",content:`Applied change to ${e}. Reloading...`}:n.messages.push({role:"system",content:`Applied change to ${e}. Reloading...`})}}else if(u>1)n.messages.push({role:"system",content:`Found ${u} exact matches in ${e} \u2014 expected 1. Edit not applied.`});else{let y=ht(c,i);if(y){let h=c.slice(0,y.start)+r+c.slice(y.end),f=await S("fs.write",{path:m,content:h});if(f?.payload?.ok===!1)n.messages.push({role:"system",content:`Write failed: ${e} - ${f.payload?.error||"unknown"}`});else{let $=a?.dataset.diffIdx;$!==void 0?n.messages[parseInt($)]={role:"system",content:`Applied change to ${e} (fuzzy match). Reloading...`}:n.messages.push({role:"system",content:`Applied change to ${e} (fuzzy match). Reloading...`})}}else n.messages.push({role:"system",content:`No matching code found in ${e}. The file may have changed since the suggestion.`})}}}catch(c){n.messages.push({role:"system",content:`Failed to apply: ${e} \u2014 ${c.message}`})}M(),U(),setTimeout(()=>{window.location.reload()},1500)}function We(t){t.disabled=!0,t.style.opacity="0.5";let e=t.dataset.idx;if(e!==void 0){let s=parseInt(e);try{let o=JSON.parse(F(n.messages[s]?.content.slice(8)||""));n.messages[s]={role:"system",content:`Rejected change to ${o.file||"file"}`}}catch{n.messages[s]={role:"system",content:"Change rejected"}}}M(),U()}function gt(t){let e=k.querySelector(".om-apply-bar");if(e)if(t>0){e.classList.remove("om-hidden");let s=e.querySelector(".om-apply-bar-text");s&&(s.textContent=`${t} change${t>1?"s":""} ready`)}else e.classList.add("om-hidden")}function Ke(){let t=k.querySelector(".om-apply-bar");t&&t.classList.add("om-hidden")}async function ft(t){let e=t.dataset.file;if(!e)return;let s=Je(e),o=s+".openmagic-backup";try{let i=(await S("fs.read",{path:o}))?.payload?.content;i?(await S("fs.write",{path:s,content:i}),n.messages.push({role:"system",content:`Reverted change to ${e}`})):n.messages.push({role:"system",content:`No backup found for ${e}`})}catch{n.messages.push({role:"system",content:`Could not revert ${e} \u2014 backup may not exist`})}M()}function yt(t,e){switch(t){case"select":$t();break;case"screenshot":St();break;case"chat":ve("chat");break;case"settings":ve("settings");break;case"close-panel":ie();break;case"prompt-send":ke();break;case"save-settings":vt();break;case"get-key":{let s=e.dataset.url;s&&window.open(s,"_blank","noopener");break}case"change-key":{let s=k.querySelector("[data-key-change]");s&&s.classList.remove("om-hidden"),e.style.display="none";break}case"network":ve("chat"),wt();break;case"attach-image":kt();break;case"remove-attachment":{let s=parseInt(e.dataset.idx||"0",10);n.attachments.splice(s,1),Me();break}case"apply-diff":Ue(e);break;case"reject-diff":We(e);break;case"apply-all":{let s=k.querySelectorAll('[data-action="apply-diff"]');for(let o of Array.from(s))Ue(o);Ke();break}case"reject-all":{let s=k.querySelectorAll('[data-action="reject-diff"]');for(let o of Array.from(s))We(o);Ke();break}case"undo-diff":ft(e);break;case"clear-chat":{n.messages=[];try{sessionStorage.removeItem("__om_state__")}catch{}M();break}case"copy-msg":{let s=parseInt(e.dataset.idx||"0",10);e.innerHTML='<span class="om-spinner"></span>',Ge(s).then(o=>{try{navigator.clipboard.writeText(o)}catch{}e.innerHTML=v.check,setTimeout(()=>{e.innerHTML=v.copy},1500)});break}case"report-issue":{e.innerHTML='<span class="om-spinner"></span>',Ge().then(s=>{try{navigator.clipboard.writeText(s)}catch{}e.innerHTML=v.bug,window.open("https://github.com/Kalmuraee/OpenMagic/issues/new?template=bug_report.yml","_blank","noopener"),n.messages.push({role:"system",content:"Debug info copied to clipboard. Paste it in the Debug Info field on GitHub."}),n.panelOpen&&M()});break}case"clear-element":n.selectedElement=null,X();break;case"clear-screenshot":n.screenshot=null,X();break;case"minimize":{n.minimized=!n.minimized;let s=k.querySelector(".om-panel"),o=k.querySelector(".om-prompt-row"),a=k.querySelector(".om-prompt-attachments"),i=E.querySelectorAll(".om-pill-btn:not([data-action='minimize']), .om-pill-divider, .om-status-dot");n.minimized?(s&&s.classList.add("om-hidden"),o&&o.classList.add("om-hidden"),a&&a.classList.add("om-hidden"),i.forEach(r=>r.style.display="none")):(o&&o.classList.remove("om-hidden"),a&&a.classList.remove("om-hidden"),i.forEach(r=>r.style.display=""),n.panelOpen&&n.activePanel&&s&&s.classList.remove("om-hidden"));break}}}function re(){let t=k.querySelector(".om-status-dot");if(t){let e=n.updateAvailable?"outdated":n.connected?"connected":"disconnected";t.className=`om-status-dot ${e}`,t.setAttribute("title",n.updateAvailable?`v${n.latestVersion} available \u2014 run npx openmagic@latest`:n.connected?"Connected":"Disconnected")}}function Y(){k.querySelectorAll(".om-pill-btn").forEach(t=>{let e=t.dataset.action;t.classList.toggle("active",e===n.activePanel||e==="select"&&n.selecting)})}function X(){let t=[];n.selectedElement&&t.push(`<span class="om-prompt-chip">${n.selectedElement.tagName}${n.selectedElement.id?"#"+n.selectedElement.id:""} <button class="om-prompt-chip-x" data-action="clear-element">${v.x}</button></span>`),n.screenshot&&t.push(`<span class="om-prompt-chip">Screenshot <button class="om-prompt-chip-x" data-action="clear-screenshot">${v.x}</button></span>`),n.attachments.length&&t.push(`<span class="om-prompt-chip">${n.attachments.length} image${n.attachments.length>1?"s":""}</span>`),n.groundedFiles.length&&t.push(`<span class="om-prompt-chip">${n.groundedFiles.length} files grounded</span>`),Ve.innerHTML=t.join("")}function q(t){n.panelOpen=!0,n.activePanel=t,Ee.classList.remove("om-hidden");let e=k.querySelector(".om-panel-title");e&&(e.textContent=t==="settings"?"Settings":"Chat"),M(),Y()}function ie(){n.panelOpen=!1,n.activePanel="",Ee.classList.add("om-hidden"),Y()}function ve(t){n.panelOpen&&n.activePanel===t?ie():q(t)}function M(){n.activePanel==="settings"?N.innerHTML=bt():n.activePanel==="chat"&&(N.innerHTML=xt(),U()),dt()}function bt(){let t=Object.entries(I).map(([l,u])=>{let h=n.configuredProviders[l]||u.local?" \u2713":"";return`<option value="${l}" ${n.provider===l?"selected":""}>${u.name}${h}</option>`}).join(""),e=I[n.provider],s=e?e.models.map(l=>`<option value="${l.id}" ${n.model===l.id?"selected":""}>${l.name}</option>`).join(""):'<option value="">Select provider first</option>',o=e?.local||!1,a=e?.keyUrl||"",i=e?.keyPlaceholder||"Enter API key...",r=n.configuredProviders[n.provider]||!1,p=n.updateAvailable?`<div class="om-update-banner">v${n.latestVersion} available <code class="om-update-cmd">npx openmagic@latest</code></div>`:"",c=r||o?`<div class="om-status om-status-success">${v.check} ${e?.name||"Provider"} connected</div>`:"",m=n.saveStatus==="saving"?'<span class="om-spinner"></span> Saving...':n.saveStatus==="saved"?`${v.check} Saved`:"Save",d=n.saveStatus==="saving"?"om-btn om-btn-saving":n.saveStatus==="saved"?"om-btn om-btn-saved":"om-btn",x=n.saveStatus==="saving"?"disabled":"",g="";return!o&&n.provider&&(r?g=`
435
+ </div>`}function gt(t){t.addEventListener("click",o=>{let r=o.target.closest("[data-action]");if(!r)return;o.preventDefault(),o.stopPropagation();let l=r.dataset.action;xt(l,r)}),t.addEventListener("change",o=>{let r=o.target,l=r.dataset.field;l&&(l==="provider"?(n.provider=r.value,n.model=B[n.provider]?.models[0]?.id||"",n.hasApiKey=n.configuredProviders[n.provider]||B[n.provider]?.local||!1,n.saveStatus="",H()):l==="model"&&(n.model=r.value))}),z.addEventListener("keydown",o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),Se())});let e=t.querySelector(".om-file-input");e&&e.addEventListener("change",()=>{$e(e.files),e.value=""});let s=t.querySelector(".om-prompt-row");s&&(s.addEventListener("dragover",o=>{o.preventDefault(),s.style.borderColor="rgba(108, 92, 231, 0.5)"}),s.addEventListener("dragleave",()=>{s.style.borderColor=""}),s.addEventListener("drop",o=>{o.preventDefault(),s.style.borderColor="";let r=o.dataTransfer;r?.files?.length&&$e(r.files)}),z.addEventListener("paste",o=>{let r=o.clipboardData?.items;if(r){for(let l=0;l<r.length;l++)if(r[l].type.startsWith("image/")){let i=r[l].getAsFile();if(i){let d=new DataTransfer;d.items.add(i),$e(d.files)}}}})),Re(o=>{o.type==="reconnected"&&(n.connected=!0,pe())}),document.addEventListener("keydown",o=>{if((o.ctrlKey||o.metaKey)&&o.shiftKey&&(o.key==="O"||o.key==="o")){if(o.preventDefault(),n.minimized){n.minimized=!1,C.querySelectorAll(".om-pill-btn:not([data-action='minimize']), .om-pill-divider, .om-status-dot").forEach(i=>i.style.display="");let l=E.querySelector(".om-prompt-row");l&&l.classList.remove("om-hidden")}else n.panelOpen?me():F("chat");return}if(o.key==="Escape"){if(n.selecting)return;n.panelOpen&&(me(),o.preventDefault())}}),z.addEventListener("keydown",o=>{(o.ctrlKey||o.metaKey)&&o.key==="Enter"&&(o.preventDefault(),Se())})}function Ye(t){return n.roots.length>0?n.roots[0]+"/"+t:t}function ft(t,e){let s=e.split(`
436
+ `).map(i=>i.trim()).filter(i=>i.length>0);if(s.length===0)return null;let o=t.split(`
437
+ `),r=s[0],l=s[s.length-1];for(let i=0;i<o.length;i++){if(o[i].trim()!==r||i+s.length>o.length)continue;let d=!0;for(let c=0;c<s.length;c++)if(o[i+c].trim()!==s[c]){d=!1;break}if(d){let c=0;for(let h=0;h<i;h++)c+=o[h].length+1;let p=c;for(let h=i;h<i+s.length;h++)p+=o[h].length+1;return p>0&&p<=t.length&&t[p-1]===`
438
+ `&&p--,{start:c,end:p}}}return null}async function Ge(t){let e=t.dataset.file,s=t.dataset.search,o=t.dataset.replace;if(!e||!s||!o)return;t.disabled=!0,t.innerHTML='<span class="om-spinner"></span>',t.style.opacity="0.5",t.style.pointerEvents="none";let r=t.closest(".om-diff-card");if(r){let c=r.querySelector(".om-diff-actions");c&&(c.innerHTML='<span class="om-spinner"></span> Applying...')}await new Promise(c=>requestAnimationFrame(c));let l,i;try{l=X(s),i=X(o)}catch{n.messages.push({role:"system",content:`Failed to decode diff data for ${e}`}),H();return}let d=Ye(e);try{if(!l&&i){if((await M("fs.write",{path:d,content:i}))?.payload?.ok===!1)n.messages.push({role:"system",content:`Write failed: ${e}`});else{let m=r?.dataset.diffIdx;m!==void 0?n.messages[parseInt(m)]={role:"system",content:`Created ${e}`}:n.messages.push({role:"system",content:`Created ${e}`})}H(),Y();return}let c,p=d,h=[d];e!==d&&h.push(e);let x=e.split("/").pop()||e,w=n.roots[0]||"",a=w?`${w}/${x}`:x;a!==d&&a!==e&&h.push(a);for(let g of h){let u=(await M("fs.read",{path:g}).catch(()=>null))?.payload?.content;if(u!=null&&String(u).length>0){c=String(u),p=g;break}}if(!c)n.messages.push({role:"system",content:`Could not read ${e} \u2014 tried: ${h.join(", ")}`});else{let g=c.split(l).length-1;if(g===1){let m=await M("fs.write",{path:p,content:c.replace(l,i)});if(m?.payload?.ok===!1)n.messages.push({role:"system",content:`Write failed: ${e} - ${m.payload?.error||"unknown"}`});else{let u=r?.dataset.diffIdx;u!==void 0?n.messages[parseInt(u)]={role:"system",content:`Applied change to ${e}. Reloading...`}:n.messages.push({role:"system",content:`Applied change to ${e}. Reloading...`})}}else if(g>1)n.messages.push({role:"system",content:`Found ${g} exact matches in ${e} \u2014 expected 1. Edit not applied.`});else{let m=ft(c,l);if(m){let u=c.slice(0,m.start)+i+c.slice(m.end),f=await M("fs.write",{path:p,content:u});if(f?.payload?.ok===!1)n.messages.push({role:"system",content:`Write failed: ${e} - ${f.payload?.error||"unknown"}`});else{let b=r?.dataset.diffIdx;b!==void 0?n.messages[parseInt(b)]={role:"system",content:`Applied change to ${e} (fuzzy match). Reloading...`}:n.messages.push({role:"system",content:`Applied change to ${e} (fuzzy match). Reloading...`})}}else n.messages.push({role:"system",content:`No matching code found in ${e}. The file may have changed since the suggestion.`})}}}catch(c){n.messages.push({role:"system",content:`Failed to apply: ${e} \u2014 ${c.message}`})}H(),Y(),setTimeout(()=>{window.location.reload()},1500)}function Ke(t){t.disabled=!0,t.style.opacity="0.5";let e=t.dataset.idx;if(e!==void 0){let s=parseInt(e);try{let o=JSON.parse(X(n.messages[s]?.content.slice(8)||""));n.messages[s]={role:"system",content:`Rejected change to ${o.file||"file"}`}}catch{n.messages[s]={role:"system",content:"Change rejected"}}}H(),Y()}function yt(t){let e=E.querySelector(".om-apply-bar");if(e)if(t>0){e.classList.remove("om-hidden");let s=e.querySelector(".om-apply-bar-text");s&&(s.textContent=`${t} change${t>1?"s":""} ready`)}else e.classList.add("om-hidden")}function Ve(){let t=E.querySelector(".om-apply-bar");t&&t.classList.add("om-hidden")}async function bt(t){let e=t.dataset.file;if(!e)return;let s=Ye(e),o=s+".openmagic-backup";try{let l=(await M("fs.read",{path:o}))?.payload?.content;l?(await M("fs.write",{path:s,content:l}),n.messages.push({role:"system",content:`Reverted change to ${e}`})):n.messages.push({role:"system",content:`No backup found for ${e}`})}catch{n.messages.push({role:"system",content:`Could not revert ${e} \u2014 backup may not exist`})}H()}function xt(t,e){switch(t){case"select":Mt();break;case"screenshot":Et();break;case"chat":ke("chat");break;case"settings":ke("settings");break;case"close-panel":me();break;case"prompt-send":Se();break;case"save-settings":kt();break;case"get-key":{let s=e.dataset.url;s&&window.open(s,"_blank","noopener");break}case"change-key":{let s=E.querySelector("[data-key-change]");s&&s.classList.remove("om-hidden"),e.style.display="none";break}case"network":ke("chat"),$t();break;case"attach-image":St();break;case"remove-attachment":{let s=parseInt(e.dataset.idx||"0",10);n.attachments.splice(s,1),Te();break}case"apply-diff":Ge(e);break;case"reject-diff":Ke(e);break;case"apply-all":{let s=E.querySelectorAll('[data-action="apply-diff"]');for(let o of Array.from(s))Ge(o);Ve();break}case"reject-all":{let s=E.querySelectorAll('[data-action="reject-diff"]');for(let o of Array.from(s))Ke(o);Ve();break}case"undo-diff":bt(e);break;case"clear-chat":{n.messages=[];try{sessionStorage.removeItem("__om_state__")}catch{}H();break}case"copy-msg":{let s=parseInt(e.dataset.idx||"0",10);e.innerHTML='<span class="om-spinner"></span>',Je(s).then(o=>{try{navigator.clipboard.writeText(o)}catch{}e.innerHTML=k.check,setTimeout(()=>{e.innerHTML=k.copy},1500)});break}case"report-issue":{e.innerHTML='<span class="om-spinner"></span>',Je().then(s=>{try{navigator.clipboard.writeText(s)}catch{}e.innerHTML=k.bug,window.open("https://github.com/Kalmuraee/OpenMagic/issues/new?template=bug_report.yml","_blank","noopener"),n.messages.push({role:"system",content:"Debug info copied to clipboard. Paste it in the Debug Info field on GitHub."}),n.panelOpen&&H()});break}case"clear-element":n.selectedElement=null,oe();break;case"clear-screenshot":n.screenshot=null,oe();break;case"minimize":{n.minimized=!n.minimized;let s=E.querySelector(".om-panel"),o=E.querySelector(".om-prompt-row"),r=E.querySelector(".om-prompt-attachments"),l=C.querySelectorAll(".om-pill-btn:not([data-action='minimize']), .om-pill-divider, .om-status-dot");n.minimized?(s&&s.classList.add("om-hidden"),o&&o.classList.add("om-hidden"),r&&r.classList.add("om-hidden"),l.forEach(i=>i.style.display="none")):(o&&o.classList.remove("om-hidden"),r&&r.classList.remove("om-hidden"),l.forEach(i=>i.style.display=""),n.panelOpen&&n.activePanel&&s&&s.classList.remove("om-hidden"));break}}}function pe(){let t=E.querySelector(".om-status-dot");if(t){let e=n.updateAvailable?"outdated":n.connected?"connected":"disconnected";t.className=`om-status-dot ${e}`,t.setAttribute("title",n.updateAvailable?`v${n.latestVersion} available \u2014 run npx openmagic@latest`:n.connected?"Connected":"Disconnected")}}function se(){E.querySelectorAll(".om-pill-btn").forEach(t=>{let e=t.dataset.action;t.classList.toggle("active",e===n.activePanel||e==="select"&&n.selecting)})}function oe(){let t=[];n.selectedElement&&t.push(`<span class="om-prompt-chip">${n.selectedElement.tagName}${n.selectedElement.id?"#"+n.selectedElement.id:""} <button class="om-prompt-chip-x" data-action="clear-element">${k.x}</button></span>`),n.screenshot&&t.push(`<span class="om-prompt-chip">Screenshot <button class="om-prompt-chip-x" data-action="clear-screenshot">${k.x}</button></span>`),n.attachments.length&&t.push(`<span class="om-prompt-chip">${n.attachments.length} image${n.attachments.length>1?"s":""}</span>`),n.groundedFiles.length&&t.push(`<span class="om-prompt-chip">${n.groundedFiles.length} files grounded</span>`),Xe.innerHTML=t.join("")}function F(t){n.panelOpen=!0,n.activePanel=t,Le.classList.remove("om-hidden");let e=E.querySelector(".om-panel-title");e&&(e.textContent=t==="settings"?"Settings":"Chat"),H(),se()}function me(){n.panelOpen=!1,n.activePanel="",Le.classList.add("om-hidden"),se()}function ke(t){n.panelOpen&&n.activePanel===t?me():F(t)}function H(){n.activePanel==="settings"?D.innerHTML=vt():n.activePanel==="chat"&&(D.innerHTML=wt(),Y()),mt()}function vt(){let t=Object.entries(B).map(([a,g])=>{let u=n.configuredProviders[a]||g.local?" \u2713":"";return`<option value="${a}" ${n.provider===a?"selected":""}>${g.name}${u}</option>`}).join(""),e=B[n.provider],s=e?e.models.map(a=>`<option value="${a.id}" ${n.model===a.id?"selected":""}>${a.name}</option>`).join(""):'<option value="">Select provider first</option>',o=e?.local||!1,r=e?.keyUrl||"",l=e?.keyPlaceholder||"Enter API key...",i=n.configuredProviders[n.provider]||!1,d=n.updateAvailable?`<div class="om-update-banner">v${n.latestVersion} available <code class="om-update-cmd">npx openmagic@latest</code></div>`:"",c=i||o?`<div class="om-status om-status-success">${k.check} ${e?.name||"Provider"} connected</div>`:"",p=n.saveStatus==="saving"?'<span class="om-spinner"></span> Saving...':n.saveStatus==="saved"?`${k.check} Saved`:"Save",h=n.saveStatus==="saving"?"om-btn om-btn-saving":n.saveStatus==="saved"?"om-btn om-btn-saved":"om-btn",x=n.saveStatus==="saving"?"disabled":"",w="";return!o&&n.provider&&(i?w=`
439
439
  <div class="om-field">
440
440
  <label class="om-label">API Key</label>
441
441
  <div class="om-key-configured">
442
- ${v.check} <span>Key configured</span>
442
+ ${k.check} <span>Key configured</span>
443
443
  <button class="om-btn-change-key" data-action="change-key">Change</button>
444
444
  </div>
445
445
  <div class="om-key-change-row om-hidden" data-key-change>
446
446
  <div class="om-key-row">
447
- <input type="text" class="om-input om-key-input" data-field="apiKey" placeholder="${i}" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
448
- ${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${v.externalLink} Get key</button>`:""}
447
+ <input type="text" class="om-input om-key-input" data-field="apiKey" placeholder="${l}" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
448
+ ${r?`<button class="om-btn-get-key" data-action="get-key" data-url="${r}">${k.externalLink} Get key</button>`:""}
449
449
  </div>
450
450
  </div>
451
- </div>`:g=`
451
+ </div>`:w=`
452
452
  <div class="om-field">
453
453
  <label class="om-label">API Key</label>
454
454
  <div class="om-key-row">
455
- <input type="text" class="om-input om-key-input" data-field="apiKey" placeholder="${i}" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
456
- ${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${v.externalLink} Get key</button>`:""}
455
+ <input type="text" class="om-input om-key-input" data-field="apiKey" placeholder="${l}" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
456
+ ${r?`<button class="om-btn-get-key" data-action="get-key" data-url="${r}">${k.externalLink} Get key</button>`:""}
457
457
  </div>
458
- ${a?`<div class="om-key-hint"><a data-action="get-key" data-url="${a}">Get your ${e?.name||""} API key here</a></div>`:""}
458
+ ${r?`<div class="om-key-hint"><a data-action="get-key" data-url="${r}">Get your ${e?.name||""} API key here</a></div>`:""}
459
459
  </div>`),`
460
- ${p}
460
+ ${d}
461
461
  <div class="om-settings">
462
462
  <div class="om-field">
463
463
  <label class="om-label">Provider</label>
@@ -467,29 +467,31 @@
467
467
  <label class="om-label">Model</label>
468
468
  <select class="om-select" data-field="model"><option value="">Select Model...</option>${s}</select>
469
469
  </div>
470
- ${g}
471
- <button class="${d}" data-action="save-settings" ${x}>${m}</button>
470
+ ${w}
471
+ <button class="${h}" data-action="save-settings" ${x}>${p}</button>
472
472
  ${c}
473
- </div>`}function xt(){if(!n.provider||!n.hasApiKey&&!I[n.provider]?.local)return'<div class="om-status om-status-error">Configure your provider in Settings first</div>';let t=n.messages.map((o,a)=>{if(o.content.startsWith("__DIFFGROUP__"))return"";if(o.content.startsWith("__DIFF__"))try{let r=JSON.parse(F(o.content.slice(8))),p=r.type==="create"||!r.search&&r.replace,c=ae(r.search||""),m=ae(r.replace||"");return`<div class="om-diff-card" data-diff-idx="${a}">
474
- <div class="om-diff-file">${A(p?"Create new file":"Edit")}: ${A(r.file)}</div>
475
- ${r.search?`<div class="om-diff-removed">${A(r.search.slice(0,200))}</div>`:""}
476
- <div class="om-diff-added">${A((r.replace||"").slice(0,300))}</div>
473
+ </div>`}function wt(){if(!n.provider||!n.hasApiKey&&!B[n.provider]?.local)return'<div class="om-status om-status-error">Configure your provider in Settings first</div>';let t=n.messages.map((o,r)=>{if(o.content.startsWith("__DIFFGROUP__"))return"";if(o.content.startsWith("__DIFF__"))try{let i=JSON.parse(X(o.content.slice(8))),d=i.type==="create"||!i.search&&i.replace,c=de(i.search||""),p=de(i.replace||"");return`<div class="om-diff-card" data-diff-idx="${r}">
474
+ <div class="om-diff-file">${q(d?"Create new file":"Edit")}: ${q(i.file)}</div>
475
+ ${i.search?`<div class="om-diff-removed">${q(i.search.slice(0,200))}</div>`:""}
476
+ <div class="om-diff-added">${q((i.replace||"").slice(0,300))}</div>
477
477
  <div class="om-diff-actions">
478
- <button class="om-btn om-btn-sm" data-action="apply-diff" data-file="${A(r.file)}" data-search="${c}" data-replace="${m}">Apply</button>
479
- <button class="om-btn-secondary om-btn-sm" data-action="reject-diff" data-idx="${a}">Reject</button>
478
+ <button class="om-btn om-btn-sm" data-action="apply-diff" data-file="${q(i.file)}" data-search="${c}" data-replace="${p}">Apply</button>
479
+ <button class="om-btn-secondary om-btn-sm" data-action="reject-diff" data-idx="${r}">Reject</button>
480
480
  </div>
481
- </div>`}catch{return'<div class="om-msg om-msg-system">Malformed diff data</div>'}if(o.content.startsWith("Applied change to ")){let r=o.content.replace("Applied change to ","").replace(/ \(fuzzy match.*?\)/g,"").replace(". Reloading...","");return`<div class="om-msg om-msg-system">${A(o.content)} <button class="om-undo-btn" data-action="undo-diff" data-file="${A(r)}">Undo</button></div>`}let i=o.role==="user"||o.role==="assistant"?`<button class="om-copy-btn" data-action="copy-msg" data-idx="${a}" title="Copy">${v.copy}</button>`:"";return o.role==="assistant"?`<div class="om-msg om-msg-assistant">${Mt(o.content)}${i}</div>`:`<div class="om-msg om-msg-${o.role}">${A(o.content)}${i}</div>`}).join(""),e=n.streaming?'<div class="om-msg om-msg-assistant"><span class="om-spinner"></span> Generating response...</div>':"";return`<div class="om-chat-messages">${!n.messages.length&&!n.streaming?'<div class="om-chat-empty">Select an element or type below to start</div>':""}${t}${e}</div>`}function U(){requestAnimationFrame(()=>{let t=N.querySelector(".om-chat-messages");t&&(t.scrollTop=t.scrollHeight)})}async function vt(){let e=N.querySelector('[data-field="apiKey"]')?.value||"";if(!n.provider){n.saveStatus="error",se(),setTimeout(()=>{n.saveStatus="",M()},2e3);return}if(!be()){n.saveStatus="error",se();let o=N.querySelector('[data-action="save-settings"]');o&&(o.innerHTML="Not connected - check terminal"),setTimeout(()=>{n.saveStatus="",M()},3e3);return}let s={provider:n.provider,model:n.model};e&&(s.apiKey=e),n.saveStatus="saving",se();try{let o=await Promise.race([S("config.set",s),new Promise((a,i)=>setTimeout(()=>i(new Error("Save timed out")),8e3))]);e&&n.provider&&(n.configuredProviders[n.provider]=!0),n.hasApiKey=!!(e||n.configuredProviders[n.provider]),n.saveStatus="saved",se(),setTimeout(()=>{n.saveStatus="",n.activePanel==="settings"&&q("chat")},1200)}catch(o){n.saveStatus="error";let a=N.querySelector('[data-action="save-settings"]'),i=(o?.message||"").includes("timeout")?"Connection timeout - is the CLI running?":(o?.message||"").includes("connected")?"Not connected to OpenMagic server":`Save failed: ${o?.message||"Unknown error"}`;a&&(a.innerHTML=i,a.className="om-btn",a.disabled=!1),setTimeout(()=>{n.saveStatus="",M()},4e3)}}function se(){let t=N.querySelector('[data-action="save-settings"]');t&&(n.saveStatus==="saving"?(t.innerHTML='<span class="om-spinner"></span> Saving...',t.className="om-btn om-btn-saving",t.disabled=!0):n.saveStatus==="saved"?(t.innerHTML=`${v.check} Saved`,t.className="om-btn om-btn-saved",t.disabled=!1):n.saveStatus==="error"?(t.innerHTML="Save failed - try again",t.className="om-btn",t.disabled=!1):(t.innerHTML="Save",t.className="om-btn",t.disabled=!1))}async function ke(){let t=D.value.trim();if(!t||n.streaming)return;if(!n.provider||!n.hasApiKey&&!I[n.provider]?.local){q("settings");return}n.messages.push({role:"user",content:t}),n.streaming=!0,n.streamContent="",D.value="",q("chat");let e=Be(n.selectedElement,n.screenshot);e.pageUrl=window.location.href,e.pageTitle=document.title,n.attachments.length>0&&(e.screenshot||(e.screenshot=n.attachments[0]),e.attachments=[...n.attachments]);let s=5,o=32e3,a=/\.(?:[cm]?[jt]sx?|svelte|vue|astro|html?|css|scss|less|php|py)$/i,i=N.querySelector(".om-msg-assistant:last-child");i&&(i.innerHTML='<span class="om-spinner"></span> Reading project files...');try{let c=await S("fs.list",{});c?.payload?.projectTree&&(e.projectTree=c.payload.projectTree);let d=(c?.payload?.files||[]).filter(b=>b.type==="file"&&a.test(b.path)),x=[t];if(n.selectedElement&&(n.selectedElement.id&&x.push(n.selectedElement.id),n.selectedElement.className&&x.push(n.selectedElement.className),n.selectedElement.textContent&&x.push(n.selectedElement.textContent.slice(0,100)),n.selectedElement.componentHint&&x.push(n.selectedElement.componentHint),n.selectedElement.ancestry))for(let b of n.selectedElement.ancestry)x.push(b);let g=x.filter(Boolean).join(" ").toLowerCase().split(/[^a-z0-9_-]+/).filter(b=>b.length>=2&&!["the","to","in","of","and","div","span","class","style"].includes(b)),u=window.location.pathname.split("/").filter(b=>b.length>1&&!/^\d+$/.test(b)),y=d.map(b=>{let w=0,L=b.path.toLowerCase();for(let R of u)L.includes(R.toLowerCase())&&(w+=15);if(n.selectedElement?.componentHint){let R=n.selectedElement.componentHint.toLowerCase();L.includes(R)&&(w+=12)}for(let R of g)L.includes(R)&&(w+=5);return/(component|page|route|layout|template|view)/.test(L)&&(w+=3),/page\.[jt]sx?$|layout\.[jt]sx?$|\+page\.svelte$/.test(L)&&(w+=5),{...b,score:w}}).sort((b,w)=>w.score-b.score),h=[],f=new Set,$=0;for(let b of y.slice(0,s)){if(b.score<=0||$>=o)break;try{let w=n.roots[0]||"",L=w?`${w}/${b.path}`:b.path,R=await S("fs.read",{path:L}),j=String(R?.payload?.content||"");if(!j)continue;let W=Math.min(8e3,o-$),ce=j.slice(0,W);j.length>W&&(ce+=`
482
- // [FILE TRUNCATED \u2014 showing ${W} of ${j.length} chars]`),h.push({path:b.path,content:ce}),f.add(b.path),$+=ce.length;let Xe=b.path.replace(/\.[^.]+$/,""),Ye=[".module.css",".module.scss",".css",".scss",".styles.ts"];for(let de of Ye){let T=Xe+de;if(f.has(T)||$>=o)continue;if(d.find(K=>K.path===T)){try{let K=await S("fs.read",{path:w?`${w}/${T}`:T}),P=String(K?.payload?.content||"");if(P){let Z=Math.min(4e3,o-$),z=P.slice(0,Z);P.length>Z&&(z+=`
483
- // [FILE TRUNCATED \u2014 showing ${Z} of ${P.length} chars]`),h.push({path:T,content:z}),f.add(T),$+=z.length}}catch{}break}}let Ze=j.matchAll(/(?:import|from)\s+['"]\.?\.\/([\w/.-]+)['"]/g);for(let de of Ze){if($>=o)break;let T=de[1],O=b.path.replace(/\/[^/]+$/,""),K=[`${O}/${T}`,`${O}/${T}.tsx`,`${O}/${T}.ts`,`${O}/${T}.jsx`,`${O}/${T}.js`,`${O}/${T}/index.tsx`,`${O}/${T}/index.ts`];for(let P of K){if(f.has(P))break;if(d.find(z=>z.path===P)){try{let z=await S("fs.read",{path:w?`${w}/${P}`:P}),Q=String(z?.payload?.content||"");if(Q){let pe=Math.min(8e3,o-$),me=Q.slice(0,pe);Q.length>pe&&(me+=`
484
- // [FILE TRUNCATED \u2014 showing ${pe} of ${Q.length} chars]`),h.push({path:P,content:me}),f.add(P),$+=me.length}}catch{}break}}}}catch{}}if($<o)try{let b=n.roots[0]||"",w=await S("fs.read",{path:b?`${b}/package.json`:"package.json"}),L=String(w?.payload?.content||"");if(L)try{let R=JSON.parse(L),j={...R.dependencies,...R.devDependencies},W=JSON.stringify(j,null,2);h.push({path:"package.json (dependencies)",content:W.slice(0,2e3)})}catch{h.push({path:"package.json",content:L.slice(0,2e3)})}}catch{}if(h.length){e.files=h;let b=h.map(w=>w.path.split("/").pop()).join(", ");i&&(i.innerHTML=`<span class="om-spinner"></span> Thinking... (${h.length} files: ${b})`)}n.groundedFiles=h.map(b=>b.path)}catch{}let r=4,p=0;try{for(;p<=r;){n.streamContent="";let c=await He("llm.chat",{provider:n.provider,model:n.model,messages:n.messages.map(g=>({role:g.role,content:g.content})),context:e},g=>{n.streamContent+=g}),m=n.streamContent||c?.content||"",d=m.match(/NEED_FILE:\s*"?([^\s"}\]]+)"?/)||m.match(/(?:need|provide|show|read|see|contents?\s+of)\s+(?:the\s+)?(?:file\s+)?[`"']?([a-zA-Z0-9_/.@-]+\.[a-z]{1,5})[`"']?/i)||m.match(/(?:source\s+(?:file|code)\s+(?:for|of|at))\s+[`"']?([a-zA-Z0-9_/.@-]+\.[a-z]{1,5})[`"']?/i);if(d&&!c?.modifications?.length&&p<r){let g=d[1].trim();p++;let l=N.querySelector(".om-msg-assistant:last-child");l&&(l.innerHTML=`<span class="om-spinner"></span> Reading ${g}...`);try{let u=n.roots[0]||"",y=u?`${u}/${g}`:g,h,f=[y];g!==y&&f.push(g);let $=g.split("/").pop()||g,b=u?`${u}/${$}`:$;b!==y&&b!==g&&f.push(b);for(let w of f){let L=await S("fs.read",{path:w}).catch(()=>null);if(L?.payload?.content){h=String(L.payload.content);break}}if(h)e.files||(e.files=[]),e.files.push({path:g,content:h.slice(0,8e3)});else{n.messages.push({role:"system",content:`Could not read ${g}`});break}}catch{n.messages.push({role:"system",content:`File not found: ${g}`});break}continue}let x=m;try{let g=JSON.parse(m);g.explanation&&(x=g.explanation)}catch{let g=m.match(/```(?:json)?\s*([\s\S]*?)```/);if(g)try{let l=JSON.parse(g[1]);l.explanation&&(x=l.explanation)}catch{}}if(n.messages.push({role:"assistant",content:x}),c?.modifications?.length){let g=Math.random().toString(36).slice(2),l=c.modifications.filter(u=>u.type==="edit"&&u.file&&u.search&&u.replace||u.type==="create"&&u.file&&u.content);gt(l.length);for(let u of c.modifications)if(u.type==="edit"&&u.file&&u.search&&u.replace){let y=Math.random().toString(36).slice(2),h=JSON.stringify({id:y,file:u.file,search:u.search,replace:u.replace,groupId:g});n.messages.push({role:"system",content:`__DIFF__${ae(h)}`})}else if(u.type==="create"&&u.file&&u.content){let y=Math.random().toString(36).slice(2),h=JSON.stringify({id:y,file:u.file,search:"",replace:u.content,type:"create",groupId:g});n.messages.push({role:"system",content:`__DIFF__${ae(h)}`})}else u.type==="delete"&&u.file&&n.messages.push({role:"system",content:`LLM proposed deleting ${u.file} \u2014 skipped (use edit with search/replace instead)`})}break}}catch(c){n.messages.push({role:"system",content:`Error: ${c.message}`})}n.streaming=!1,n.streamContent="",n.attachments=[],Me(),M(),U()}function wt(){let t=window.performance,e=t.getEntriesByType("navigation")[0],s=t.getEntriesByType("paint"),o=t.getEntriesByType("resource").slice(-20),a=ne(),i=oe(),r=[];r.push("--- Network & Performance Capture ---"),e&&(r.push(`Page load: ${Math.round(e.loadEventEnd-e.startTime)}ms`),r.push(`DOM ready: ${Math.round(e.domContentLoadedEventEnd-e.startTime)}ms`),r.push(`TTFB: ${Math.round(e.responseStart-e.startTime)}ms`));let p=s.find(c=>c.name==="first-contentful-paint");if(p&&r.push(`FCP: ${Math.round(p.startTime)}ms`),o.length){let c=o.filter(d=>d.initiatorType==="fetch"||d.initiatorType==="xmlhttprequest"),m=c.length>0?c:o;r.push(`
485
- All network requests (${m.length}):`);for(let d of m.slice(-30)){let x=d.name.length>80?"..."+d.name.slice(-77):d.name,g=d.responseStatus||"";r.push(` ${Math.round(d.duration)}ms ${g?`[${g}]`:""} ${x}`)}}if(a.length){r.push(`
486
- Fetch/XHR requests (${a.length}):`);for(let c of a.slice(-20))r.push(` ${c.method} ${c.url.slice(0,80)} \u2192 ${c.status||"pending"} (${c.duration||"?"}ms)`)}if(i.length){let c=i.filter(d=>d.level==="error"),m=i.filter(d=>d.level==="warn");c.length&&r.push(`
487
- Console errors: ${c.length}`),m.length&&r.push(`Console warnings: ${m.length}`)}if(o.length>5){let c=[...o].sort((m,d)=>d.duration-m.duration).slice(0,5);r.push(`
488
- Slowest resources:`);for(let m of c)r.push(` ${Math.round(m.duration)}ms \u2014 ${m.name.split("/").pop()?.slice(0,60)}`)}n.messages.push({role:"system",content:r.join(`
489
- `)}),M(),U(),X()}function kt(){let t=k.querySelector(".om-file-input");t&&t.click()}function we(t){if(t)for(let e=0;e<t.length&&n.attachments.length<5;e++){let s=t[e];if(!s.type.startsWith("image/")||s.size>10*1024*1024)continue;let o=new FileReader;o.onload=()=>{typeof o.result=="string"&&(n.attachments.push(o.result),Me())},o.readAsDataURL(s)}}function Me(){let t=k.querySelector(".om-prompt-attachments");if(t){if(!n.attachments.length){t.innerHTML="",t.classList.add("om-hidden");return}t.classList.remove("om-hidden"),t.innerHTML=n.attachments.map((e,s)=>`<div class="om-attachment-thumb">
481
+ </div>`}catch{return'<div class="om-msg om-msg-system">Malformed diff data</div>'}if(o.content.startsWith("Applied change to ")){let i=o.content.replace("Applied change to ","").replace(/ \(fuzzy match.*?\)/g,"").replace(". Reloading...","");return`<div class="om-msg om-msg-system">${q(o.content)} <button class="om-undo-btn" data-action="undo-diff" data-file="${q(i)}">Undo</button></div>`}let l=o.role==="user"||o.role==="assistant"?`<button class="om-copy-btn" data-action="copy-msg" data-idx="${r}" title="Copy">${k.copy}</button>`:"";return o.role==="assistant"?`<div class="om-msg om-msg-assistant">${Tt(o.content)}${l}</div>`:`<div class="om-msg om-msg-${o.role}">${q(o.content)}${l}</div>`}).join(""),e=n.streaming?'<div class="om-msg om-msg-assistant"><span class="om-spinner"></span> Generating response...</div>':"";return`<div class="om-chat-messages">${!n.messages.length&&!n.streaming?'<div class="om-chat-empty">Select an element or type below to start</div>':""}${t}${e}</div>`}function Y(){requestAnimationFrame(()=>{let t=D.querySelector(".om-chat-messages");t&&(t.scrollTop=t.scrollHeight)})}async function kt(){let e=D.querySelector('[data-field="apiKey"]')?.value||"";if(!n.provider){n.saveStatus="error",ce(),setTimeout(()=>{n.saveStatus="",H()},2e3);return}if(!ve()){n.saveStatus="error",ce();let o=D.querySelector('[data-action="save-settings"]');o&&(o.innerHTML="Not connected - check terminal"),setTimeout(()=>{n.saveStatus="",H()},3e3);return}let s={provider:n.provider,model:n.model};e&&(s.apiKey=e),n.saveStatus="saving",ce();try{let o=await Promise.race([M("config.set",s),new Promise((r,l)=>setTimeout(()=>l(new Error("Save timed out")),8e3))]);e&&n.provider&&(n.configuredProviders[n.provider]=!0),n.hasApiKey=!!(e||n.configuredProviders[n.provider]),n.saveStatus="saved",ce(),setTimeout(()=>{n.saveStatus="",n.activePanel==="settings"&&F("chat")},1200)}catch(o){n.saveStatus="error";let r=D.querySelector('[data-action="save-settings"]'),l=(o?.message||"").includes("timeout")?"Connection timeout - is the CLI running?":(o?.message||"").includes("connected")?"Not connected to OpenMagic server":`Save failed: ${o?.message||"Unknown error"}`;r&&(r.innerHTML=l,r.className="om-btn",r.disabled=!1),setTimeout(()=>{n.saveStatus="",H()},4e3)}}function ce(){let t=D.querySelector('[data-action="save-settings"]');t&&(n.saveStatus==="saving"?(t.innerHTML='<span class="om-spinner"></span> Saving...',t.className="om-btn om-btn-saving",t.disabled=!0):n.saveStatus==="saved"?(t.innerHTML=`${k.check} Saved`,t.className="om-btn om-btn-saved",t.disabled=!1):n.saveStatus==="error"?(t.innerHTML="Save failed - try again",t.className="om-btn",t.disabled=!1):(t.innerHTML="Save",t.className="om-btn",t.disabled=!1))}async function Se(){let t=z.value.trim();if(!t||n.streaming)return;if(!n.provider||!n.hasApiKey&&!B[n.provider]?.local){F("settings");return}n.messages.push({role:"user",content:t}),n.streaming=!0,n.streamContent="",z.value="",F("chat");let e=Ue(n.selectedElement,n.screenshot);e.pageUrl=window.location.href,e.pageTitle=document.title,n.attachments.length>0&&(e.screenshot||(e.screenshot=n.attachments[0]),e.attachments=[...n.attachments]);let s=5,o=32e3,r=/\.(?:[cm]?[jt]sx?|svelte|vue|astro|html?|css|scss|less|php|py)$/i,l=D.querySelector(".om-msg-assistant:last-child");l&&(l.innerHTML='<span class="om-spinner"></span> Reading project files...');try{let c=await M("fs.list",{});c?.payload?.projectTree&&(e.projectTree=c.payload.projectTree);let h=(c?.payload?.files||[]).filter(y=>y.type==="file"&&r.test(y.path)),x=[t];if(n.selectedElement&&(n.selectedElement.id&&x.push(n.selectedElement.id),n.selectedElement.className&&x.push(n.selectedElement.className),n.selectedElement.textContent&&x.push(n.selectedElement.textContent.slice(0,100)),n.selectedElement.componentHint&&x.push(n.selectedElement.componentHint),n.selectedElement.ancestry))for(let y of n.selectedElement.ancestry)x.push(y);let w=x.filter(Boolean).join(" ").toLowerCase().split(/[^a-z0-9_-]+/).filter(y=>y.length>=2&&!["the","to","in","of","and","div","span","class","style"].includes(y)),g=window.location.pathname.split("/").filter(y=>y.length>1&&!/^\d+$/.test(y)),m=h.map(y=>{let v=0,S=y.path.toLowerCase(),_=S.replace(/\([^)]+\)\//g,"");for(let L of g)_.includes(L.toLowerCase())&&(v+=15);if(n.selectedElement?.componentHint){let L=n.selectedElement.componentHint.toLowerCase();S.includes(L)&&(v+=12)}for(let L of w)S.includes(L)&&(v+=5);return/(component|page|route|layout|template|view)/.test(S)&&(v+=3),/page\.[jt]sx?$|layout\.[jt]sx?$|\+page\.svelte$/.test(S)&&(v+=5),{...y,score:v}}).sort((y,v)=>v.score-y.score),u=[],f=new Set,b=0;for(let y of m.slice(0,s)){if(y.score<=0||b>=o)break;try{let v=n.roots[0]||"",S=v?`${v}/${y.path}`:y.path,_=await M("fs.read",{path:S}),L=String(_?.payload?.content||"");if(!L)continue;let I=Math.min(8e3,o-b),W=L.slice(0,I);L.length>I&&(W+=`
482
+ // [FILE TRUNCATED \u2014 showing ${I} of ${L.length} chars]`),u.push({path:y.path,content:W}),f.add(y.path),b+=W.length;let Z=y.path.replace(/\.[^.]+$/,""),Ze=[".module.css",".module.scss",".css",".scss",".styles.ts"];for(let Q of Ze){let $=Z+Q;if(f.has($)||b>=o)continue;if(h.find(j=>j.path===$)){try{let j=await M("fs.read",{path:v?`${v}/${$}`:$}),T=String(j?.payload?.content||"");if(T){let G=Math.min(4e3,o-b),P=T.slice(0,G);T.length>G&&(P+=`
483
+ // [FILE TRUNCATED \u2014 showing ${G} of ${T.length} chars]`),u.push({path:$,content:P}),f.add($),b+=P.length}}catch{}break}}if(u.length<=2&&b<o){let Q=["layout.tsx","layout.jsx","layout.js","layout.ts"],$=y.path.replace(/\/[^/]+$/,""),A=0;for(;$&&A<4&&b<o;){let j=!1;for(let G of Q){let P=`${$}/${G}`;if(f.has(P)){j=!0;break}try{let K=await M("fs.read",{path:v?`${v}/${P}`:P}).catch(()=>null),U=String(K?.payload?.content||"");if(U){let V=Math.min(4e3,o-b),he=U.slice(0,V);U.length>V&&(he+=`
484
+ // [TRUNCATED]`),u.push({path:P,content:he}),f.add(P),b+=he.length,j=!0;break}}catch{}}let T=$.replace(/\/[^/]+$/,"");if(T===$||!T)break;$=T,A++}}let Qe=L.matchAll(/(?:import|from)\s+['"]\.?\.\/([\w/.-]+)['"]/g);for(let Q of Qe){if(b>=o)break;let $=Q[1],A=y.path.replace(/\/[^/]+$/,""),j=[`${A}/${$}`,`${A}/${$}.tsx`,`${A}/${$}.ts`,`${A}/${$}.jsx`,`${A}/${$}.js`,`${A}/${$}/index.tsx`,`${A}/${$}/index.ts`];for(let T of j){if(f.has(T))break;if(h.find(P=>P.path===T)){try{let P=await M("fs.read",{path:v?`${v}/${T}`:T}),K=String(P?.payload?.content||"");if(K){let U=Math.min(8e3,o-b),V=K.slice(0,U);K.length>U&&(V+=`
485
+ // [FILE TRUNCATED \u2014 showing ${U} of ${K.length} chars]`),u.push({path:T,content:V}),f.add(T),b+=V.length}}catch{}break}}}}catch{}}if(b<o)try{let y=n.roots[0]||"",v=await M("fs.read",{path:y?`${y}/package.json`:"package.json"}),S=String(v?.payload?.content||"");if(S)try{let _=JSON.parse(S),L={..._.dependencies,..._.devDependencies},I=JSON.stringify(L,null,2);u.push({path:"package.json (dependencies)",content:I.slice(0,2e3)})}catch{u.push({path:"package.json",content:S.slice(0,2e3)})}}catch{}if(b<o){let y=n.roots[0]||"",v=["tailwind.config.ts","tailwind.config.js","tailwind.config.mjs","src/app/globals.css","src/styles/globals.css","styles/globals.css","app/globals.css","src/index.css","src/global.css"];for(let S of v)if(!(b>=o||f.has(S)))try{let _=y?`${y}/${S}`:S,L=await M("fs.read",{path:_}).catch(()=>null),I=String(L?.payload?.content||"");if(I){let W=Math.min(4e3,o-b),Z=I.slice(0,W);I.length>W&&(Z+=`
486
+ /* [TRUNCATED] */`),u.push({path:S,content:Z}),f.add(S),b+=Z.length}}catch{}}if(u.length){e.files=u;let y=u.map(v=>v.path.split("/").pop()).join(", ");l&&(l.innerHTML=`<span class="om-spinner"></span> Thinking... (${u.length} files: ${y})`)}n.groundedFiles=u.map(y=>y.path)}catch{}let i=4,d=0;try{for(;d<=i;){n.streamContent="";let c=await Ne("llm.chat",{provider:n.provider,model:n.model,messages:n.messages.map(a=>({role:a.role,content:a.content})),context:e},a=>{n.streamContent+=a}),p=n.streamContent||c?.content||"",h=p.match(/NEED_FILE:\s*"?([^\s"}\]]+)"?/)||p.match(/(?:need|provide|show|read|see|contents?\s+of)\s+(?:the\s+)?(?:file\s+)?[`"']?([a-zA-Z0-9_/.@-]+\.[a-z]{1,5})[`"']?/i)||p.match(/(?:source\s+(?:file|code)\s+(?:for|of|at))\s+[`"']?([a-zA-Z0-9_/.@-]+\.[a-z]{1,5})[`"']?/i);if(h&&d<i){let a=h[1].trim();d++;let g=D.querySelector(".om-msg-assistant:last-child");g&&(g.innerHTML=`<span class="om-spinner"></span> Reading ${a}...`);try{let m=n.roots[0]||"",u=m?`${m}/${a}`:a,f,b=[u];a!==u&&b.push(a);let y=a.split("/").pop()||a,v=m?`${m}/${y}`:y;v!==u&&v!==a&&b.push(v);for(let S of b){let _=await M("fs.read",{path:S}).catch(()=>null);if(_?.payload?.content){f=String(_.payload.content);break}}if(f)e.files||(e.files=[]),e.files.push({path:a,content:f.slice(0,8e3)});else{n.messages.push({role:"system",content:`Could not read ${a}`});break}}catch{n.messages.push({role:"system",content:`File not found: ${a}`});break}continue}let x=p.match(/SEARCH_FILES:\s*"([^"]+)"(?:\s+in\s+(\S+))?/);if(x&&d<i){let a=x[1],g=x[2]||"";d++;let m=D.querySelector(".om-msg-assistant:last-child");m&&(m.innerHTML=`<span class="om-spinner"></span> Searching: "${a}"...`);try{let f=(await M("fs.grep",{pattern:a,path:g}))?.payload?.results||[];f.length&&(e.searchResults||(e.searchResults=[]),e.searchResults.push({query:a,matches:f}))}catch{}continue}let w=p;try{let a=JSON.parse(p);a.explanation&&(w=a.explanation)}catch{let a=p.match(/```(?:json)?\s*([\s\S]*?)```/);if(a)try{let g=JSON.parse(a[1]);g.explanation&&(w=g.explanation)}catch{}}if(n.messages.push({role:"assistant",content:w}),c?.modifications?.length){let a=Math.random().toString(36).slice(2),g=c.modifications.filter(m=>m.type==="edit"&&m.file&&m.search&&m.replace||m.type==="create"&&m.file&&m.content);yt(g.length);for(let m of c.modifications)if(m.type==="edit"&&m.file&&m.search&&m.replace){let u=Math.random().toString(36).slice(2),f=JSON.stringify({id:u,file:m.file,search:m.search,replace:m.replace,groupId:a});n.messages.push({role:"system",content:`__DIFF__${de(f)}`})}else if(m.type==="create"&&m.file&&m.content){let u=Math.random().toString(36).slice(2),f=JSON.stringify({id:u,file:m.file,search:"",replace:m.content,type:"create",groupId:a});n.messages.push({role:"system",content:`__DIFF__${de(f)}`})}else m.type==="delete"&&m.file&&n.messages.push({role:"system",content:`LLM proposed deleting ${m.file} \u2014 skipped (use edit with search/replace instead)`})}break}}catch(c){n.messages.push({role:"system",content:`Error: ${c.message}`})}n.streaming=!1,n.streamContent="",n.attachments=[],Te(),H(),Y()}function $t(){let t=window.performance,e=t.getEntriesByType("navigation")[0],s=t.getEntriesByType("paint"),o=t.getEntriesByType("resource").slice(-20),r=ie(),l=le(),i=[];i.push("--- Network & Performance Capture ---"),e&&(i.push(`Page load: ${Math.round(e.loadEventEnd-e.startTime)}ms`),i.push(`DOM ready: ${Math.round(e.domContentLoadedEventEnd-e.startTime)}ms`),i.push(`TTFB: ${Math.round(e.responseStart-e.startTime)}ms`));let d=s.find(c=>c.name==="first-contentful-paint");if(d&&i.push(`FCP: ${Math.round(d.startTime)}ms`),o.length){let c=o.filter(h=>h.initiatorType==="fetch"||h.initiatorType==="xmlhttprequest"),p=c.length>0?c:o;i.push(`
487
+ All network requests (${p.length}):`);for(let h of p.slice(-30)){let x=h.name.length>80?"..."+h.name.slice(-77):h.name,w=h.responseStatus||"";i.push(` ${Math.round(h.duration)}ms ${w?`[${w}]`:""} ${x}`)}}if(r.length){i.push(`
488
+ Fetch/XHR requests (${r.length}):`);for(let c of r.slice(-20))i.push(` ${c.method} ${c.url.slice(0,80)} \u2192 ${c.status||"pending"} (${c.duration||"?"}ms)`)}if(l.length){let c=l.filter(h=>h.level==="error"),p=l.filter(h=>h.level==="warn");c.length&&i.push(`
489
+ Console errors: ${c.length}`),p.length&&i.push(`Console warnings: ${p.length}`)}if(o.length>5){let c=[...o].sort((p,h)=>h.duration-p.duration).slice(0,5);i.push(`
490
+ Slowest resources:`);for(let p of c)i.push(` ${Math.round(p.duration)}ms \u2014 ${p.name.split("/").pop()?.slice(0,60)}`)}n.messages.push({role:"system",content:i.join(`
491
+ `)}),H(),Y(),oe()}function St(){let t=E.querySelector(".om-file-input");t&&t.click()}function $e(t){if(t)for(let e=0;e<t.length&&n.attachments.length<5;e++){let s=t[e];if(!s.type.startsWith("image/")||s.size>10*1024*1024)continue;let o=new FileReader;o.onload=()=>{typeof o.result=="string"&&(n.attachments.push(o.result),Te())},o.readAsDataURL(s)}}function Te(){let t=E.querySelector(".om-prompt-attachments");if(t){if(!n.attachments.length){t.innerHTML="",t.classList.add("om-hidden");return}t.classList.remove("om-hidden"),t.innerHTML=n.attachments.map((e,s)=>`<div class="om-attachment-thumb">
490
492
  <img src="${e}" alt="attachment" />
491
- <button class="om-attachment-remove" data-action="remove-attachment" data-idx="${s}">${v.x}</button>
492
- </div>`).join("")}}var V=null,J=null;function $t(){n.selecting?$e():le()}function le(){n.selecting=!0,document.body.style.cursor="crosshair",Y(),J=e=>{let s=e.target;if(s.closest("openmagic-toolbar")||s.dataset?.openmagic)return;let o=s.getBoundingClientRect();Ne({x:o.x,y:o.y,width:o.width,height:o.height})},V=e=>{e.preventDefault(),e.stopPropagation();let s=e.target;s.closest("openmagic-toolbar")||s.dataset?.openmagic||(n.selectedElement=Re(s),$e(),X(),D.focus())};let t=e=>{e.key==="Escape"&&$e()};document.addEventListener("mousemove",J,!0),document.addEventListener("click",V,!0),document.addEventListener("keydown",t,!0),le._escHandler=t}function $e(){n.selecting=!1,document.body.style.cursor="",Ae(),J&&(document.removeEventListener("mousemove",J,!0),J=null),V&&(document.removeEventListener("click",V,!0),V=null);let t=le._escHandler;t&&(document.removeEventListener("keydown",t,!0),le._escHandler=null),Y()}async function St(){let t;try{let o=n.selectedElement?.cssSelector?.trim();o&&(t=document.querySelector(o)||void 0)}catch{}let e=await Oe(t||void 0);e.data&&e.data.length>5e3?(n.screenshot=e.data,X(),D.focus()):(n.messages.push({role:"system",content:"Take a screenshot manually (Cmd+Shift+4 on Mac, Win+Shift+S on Windows), then paste it here (Ctrl+V) or drag it onto the prompt bar."}),q("chat"),M())}function Et(){let t=!1,e=0,s=0,o=0,a=0;E.addEventListener("mousedown",i=>{let r=i.target;if(r.closest("[data-action]")||!r.closest(".om-grab")&&!r.closest(".om-pill-brand"))return;t=!0,e=i.clientX,s=i.clientY;let p=E.getBoundingClientRect();o=p.left,a=p.top,i.preventDefault()}),document.addEventListener("mousemove",i=>{t&&(E.style.left=o+i.clientX-e+"px",E.style.top=a+i.clientY-s+"px",E.style.right="auto",E.style.bottom="auto")}),document.addEventListener("mouseup",()=>{if(t){t=!1;try{localStorage.setItem("__om_pos__",JSON.stringify({left:E.style.left,top:E.style.top}))}catch{}}})}function A(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}function Mt(t){let e=t.replace(/\\n/g,`
493
- `),s=A(e);return s=s.replace(/```(\w*)\n([\s\S]*?)```/g,'<pre class="om-code-block"><code>$2</code></pre>'),s=s.replace(/`([^`]+)`/g,'<code class="om-inline-code">$1</code>'),s=s.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),s=s.replace(/([^*]|^)\*([^*]+)\*([^*]|$)/g,"$1<em>$2</em>$3"),s=s.replace(/^- (.+)$/gm,"&#8226; $1"),s=s.replace(/\n/g,"<br>"),s}async function Ge(t){let e=[],s=null;try{be()&&(s=(await Promise.race([S("debug.logs"),new Promise((u,y)=>setTimeout(()=>y(new Error("timeout")),3e3))]))?.payload||null)}catch{}e.push("## Environment"),e.push(""),e.push(`- **OpenMagic**: v${Se}${n.updateAvailable?` (v${n.latestVersion} available)`:""}`),e.push(`- **Browser**: ${navigator.userAgent}`),e.push(`- **Platform**: ${navigator.platform}`),e.push(`- **Viewport**: ${window.innerWidth}x${window.innerHeight} (devicePixelRatio: ${window.devicePixelRatio})`),e.push(`- **Page URL**: ${window.location.href}`),e.push(`- **Page Title**: ${document.title}`),s&&(e.push(`- **Node.js**: ${s.nodeVersion} (${s.platform}/${s.arch})`),e.push(`- **Server PID**: ${s.pid}`),e.push(`- **Server Uptime**: ${s.uptime}s`),e.push(`- **Server Memory**: ${s.memoryMB}MB RSS`),e.push(`- **Server CWD**: ${s.cwd}`)),e.push(""),e.push("## Configuration"),e.push(""),e.push(`- **WebSocket**: ${n.connected?"connected":"disconnected"}`),e.push(`- **Provider**: ${I[n.provider]?.name||n.provider||"not set"}`),e.push(`- **Model**: ${n.model||"not set"}`),e.push(`- **API Key Set**: ${n.hasApiKey?"yes":"no"}`);let o=Object.entries(n.configuredProviders).filter(([,l])=>l).map(([l])=>I[l]?.name||l);if(o.length&&e.push(`- **Configured Providers**: ${o.join(", ")}`),n.roots.length&&e.push(`- **Project Roots**: ${n.roots.join(", ")}`),n.selectedElement){let l=n.selectedElement;e.push(""),e.push("## Selected Element"),e.push(""),e.push(`- **Selector**: \`${l.cssSelector||""}\``),e.push(`- **Tag**: \`${l.tagName}\``),l.id&&e.push(`- **ID**: \`${l.id}\``),l.className&&e.push(`- **Class**: \`${l.className}\``),l.componentHint&&e.push(`- **Component**: \`${l.componentHint}\``),l.ancestry?.length&&e.push(`- **Ancestry**: ${l.ancestry.join(" > ")}`),l.textContent&&e.push(`- **Text**: ${l.textContent.slice(0,150)}`)}if(n.groundedFiles.length){e.push(""),e.push("## Files Sent to LLM"),e.push("");for(let l of n.groundedFiles)e.push(`- \`${l}\``)}let a=[];for(let l of n.messages)if(l.content.startsWith("__DIFF__"))try{let u=JSON.parse(F(l.content.slice(8)));a.push({file:u.file,type:u.type||"edit"})}catch{}if(a.length){e.push(""),e.push("## Proposed Changes"),e.push("");for(let l of a)e.push(`- \`${l.file}\` (${l.type})`)}let i=n.messages.filter(l=>l.role==="system"&&(l.content.startsWith("Applied change to ")||l.content.startsWith("Rejected change to ")||l.content.startsWith("Reverted change to ")||l.content.startsWith("Created ")||l.content.startsWith("Change rejected")||l.content.startsWith("No matching code")||l.content.startsWith("Write failed")||l.content.startsWith("Could not read")));if(i.length){e.push(""),e.push("## Applied/Rejected Changes"),e.push("");for(let l of i)e.push(`- ${l.content.slice(0,200)}`)}let r=window.performance,p=r.getEntriesByType("navigation")[0],c=r.getEntriesByType("paint");if(p){e.push(""),e.push("## Page Performance"),e.push(""),e.push(`- **Page Load**: ${Math.round(p.loadEventEnd-p.startTime)}ms`),e.push(`- **DOM Ready**: ${Math.round(p.domContentLoadedEventEnd-p.startTime)}ms`),e.push(`- **TTFB**: ${Math.round(p.responseStart-p.startTime)}ms`);let l=c.find(u=>u.name==="first-contentful-paint");l&&e.push(`- **FCP**: ${Math.round(l.startTime)}ms`)}let m=oe();if(m.length){let l=m.filter(h=>h.level==="error"),u=m.filter(h=>h.level==="warn"),y=m.filter(h=>h.level==="log"||h.level==="info"||h.level==="debug");if(e.push(""),e.push("## Browser Console"),e.push(""),e.push(`Total: ${m.length} entries (${l.length} errors, ${u.length} warnings, ${y.length} log/info/debug)`),l.length){e.push(""),e.push(`### Errors (${l.length})`),e.push("```");for(let h of l.slice(-15))e.push(`[${new Date(h.timestamp).toISOString()}] ${h.args.map(f=>String(f)).join(" ").slice(0,300)}`);e.push("```")}if(u.length){e.push(""),e.push(`### Warnings (${u.length})`),e.push("```");for(let h of u.slice(-10))e.push(`[${new Date(h.timestamp).toISOString()}] ${h.args.map(f=>String(f)).join(" ").slice(0,200)}`);e.push("```")}if(y.length){e.push(""),e.push("<details><summary>Log/Info/Debug ("+y.length+" entries)</summary>"),e.push(""),e.push("```");for(let h of y.slice(-30))e.push(`[${new Date(h.timestamp).toISOString()}] [${h.level}] ${h.args.map(f=>String(f)).join(" ").slice(0,200)}`);e.push("```"),e.push("</details>")}}let d=ne(),x=d.filter(l=>l.status&&l.status>=400),g=d.filter(l=>l.duration&&l.duration>2e3);if(x.length||g.length){if(e.push(""),e.push("## Network Issues"),e.push(""),x.length){e.push(`### Failed Requests (${x.length})`),e.push("```");for(let l of x.slice(-15))e.push(`${l.method} ${l.url.slice(0,120)} \u2192 ${l.status} (${l.duration||"?"}ms)`);e.push("```")}if(g.length){e.push(`### Slow Requests >2s (${g.length})`),e.push("```");for(let l of g.slice(-10))e.push(`${l.method} ${l.url.slice(0,120)} \u2192 ${l.status} (${l.duration}ms)`);e.push("```")}}if(s?.logs?.length){let l=s.logs,u=l.filter(f=>f.level==="error"),y=l.filter(f=>f.level==="warn"),h=l.filter(f=>f.level==="log"||f.level==="info");if(e.push(""),e.push("## Server Logs (Terminal)"),e.push(""),e.push(`Total: ${l.length} entries (${u.length} errors, ${y.length} warnings, ${h.length} log/info)`),u.length){e.push(""),e.push(`### Server Errors (${u.length})`),e.push("```");for(let f of u.slice(-15))e.push(`[${new Date(f.ts).toISOString()}] ${f.msg.slice(0,300)}`);e.push("```")}if(y.length){e.push(""),e.push(`### Server Warnings (${y.length})`),e.push("```");for(let f of y.slice(-10))e.push(`[${new Date(f.ts).toISOString()}] ${f.msg.slice(0,200)}`);e.push("```")}e.push(""),e.push("<details><summary>All server logs ("+l.length+" entries)</summary>"),e.push(""),e.push("```");for(let f of l.slice(-50))e.push(`[${new Date(f.ts).toISOString()}] [${f.level}] ${f.msg.slice(0,200)}`);e.push("```"),e.push("</details>")}if(n.messages.length){e.push(""),e.push("## Chat History"),e.push(""),e.push("<details><summary>Full conversation ("+n.messages.length+" messages)</summary>"),e.push(""),e.push("```");for(let l of n.messages)if(!l.content.startsWith("__DIFFGROUP__")){if(l.content.startsWith("__DIFF__")){try{let u=JSON.parse(F(l.content.slice(8)));e.push(`[diff] ${u.type||"edit"}: ${u.file}`),u.search&&e.push(` - search: ${u.search.slice(0,100)}...`),u.replace&&e.push(` + replace: ${u.replace.slice(0,100)}...`)}catch{e.push("[diff] (parse error)")}continue}e.push(`[${l.role}] ${l.content.slice(0,500)}`)}e.push("```"),e.push("</details>")}if(t!==void 0){let l=n.messages[t];l&&(e.push(""),e.push("## Copied Message"),e.push(""),e.push("```"),e.push(`[${l.role}] ${l.content.slice(0,2e3)}`),e.push("```"))}return e.join(`
494
- `)}function Lt(){fetch("https://registry.npmjs.org/openmagic/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)}).then(t=>t.ok?t.json():null).then(t=>{if(!t?.version)return;let e=t.version.split(".").map(Number),s=Se.split(".").map(Number);for(let o=0;o<3;o++){if((e[o]||0)>(s[o]||0)){n.updateAvailable=!0,n.latestVersion=t.version,Tt();return}if((e[o]||0)<(s[o]||0))return}}).catch(()=>{})}function Tt(){re()}typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Fe):Fe());})();
493
+ <button class="om-attachment-remove" data-action="remove-attachment" data-idx="${s}">${k.x}</button>
494
+ </div>`).join("")}}var te=null,ne=null;function Mt(){n.selecting?Me():ue()}function ue(){n.selecting=!0,document.body.style.cursor="crosshair",se(),ne=e=>{let s=e.target;if(s.closest("openmagic-toolbar")||s.dataset?.openmagic)return;let o=s.getBoundingClientRect();Oe({x:o.x,y:o.y,width:o.width,height:o.height})},te=e=>{e.preventDefault(),e.stopPropagation();let s=e.target;s.closest("openmagic-toolbar")||s.dataset?.openmagic||(n.selectedElement=Ae(s),Me(),oe(),z.focus())};let t=e=>{e.key==="Escape"&&Me()};document.addEventListener("mousemove",ne,!0),document.addEventListener("click",te,!0),document.addEventListener("keydown",t,!0),ue._escHandler=t}function Me(){n.selecting=!1,document.body.style.cursor="",De(),ne&&(document.removeEventListener("mousemove",ne,!0),ne=null),te&&(document.removeEventListener("click",te,!0),te=null);let t=ue._escHandler;t&&(document.removeEventListener("keydown",t,!0),ue._escHandler=null),se()}async function Et(){let t;try{let o=n.selectedElement?.cssSelector?.trim();o&&(t=document.querySelector(o)||void 0)}catch{}let e=await Ie(t||void 0);e.data&&e.data.length>5e3?(n.screenshot=e.data,oe(),z.focus()):(n.messages.push({role:"system",content:"Take a screenshot manually (Cmd+Shift+4 on Mac, Win+Shift+S on Windows), then paste it here (Ctrl+V) or drag it onto the prompt bar."}),F("chat"),H())}function Lt(){let t=!1,e=0,s=0,o=0,r=0;C.addEventListener("mousedown",l=>{let i=l.target;if(i.closest("[data-action]")||!i.closest(".om-grab")&&!i.closest(".om-pill-brand"))return;t=!0,e=l.clientX,s=l.clientY;let d=C.getBoundingClientRect();o=d.left,r=d.top,l.preventDefault()}),document.addEventListener("mousemove",l=>{t&&(C.style.left=o+l.clientX-e+"px",C.style.top=r+l.clientY-s+"px",C.style.right="auto",C.style.bottom="auto")}),document.addEventListener("mouseup",()=>{if(t){t=!1;try{localStorage.setItem("__om_pos__",JSON.stringify({left:C.style.left,top:C.style.top}))}catch{}}})}function q(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}function Tt(t){let e=t.replace(/\\n/g,`
495
+ `),s=q(e);return s=s.replace(/```(\w*)\n([\s\S]*?)```/g,'<pre class="om-code-block"><code>$2</code></pre>'),s=s.replace(/`([^`]+)`/g,'<code class="om-inline-code">$1</code>'),s=s.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),s=s.replace(/([^*]|^)\*([^*]+)\*([^*]|$)/g,"$1<em>$2</em>$3"),s=s.replace(/^- (.+)$/gm,"&#8226; $1"),s=s.replace(/\n/g,"<br>"),s}async function Je(t){let e=[],s=null;try{ve()&&(s=(await Promise.race([M("debug.logs"),new Promise((g,m)=>setTimeout(()=>m(new Error("timeout")),3e3))]))?.payload||null)}catch{}e.push("## Environment"),e.push(""),e.push(`- **OpenMagic**: v${Ee}${n.updateAvailable?` (v${n.latestVersion} available)`:""}`),e.push(`- **Browser**: ${navigator.userAgent}`),e.push(`- **Platform**: ${navigator.platform}`),e.push(`- **Viewport**: ${window.innerWidth}x${window.innerHeight} (devicePixelRatio: ${window.devicePixelRatio})`),e.push(`- **Page URL**: ${window.location.href}`),e.push(`- **Page Title**: ${document.title}`),s&&(e.push(`- **Node.js**: ${s.nodeVersion} (${s.platform}/${s.arch})`),e.push(`- **Server PID**: ${s.pid}`),e.push(`- **Server Uptime**: ${s.uptime}s`),e.push(`- **Server Memory**: ${s.memoryMB}MB RSS`),e.push(`- **Server CWD**: ${s.cwd}`)),e.push(""),e.push("## Configuration"),e.push(""),e.push(`- **WebSocket**: ${n.connected?"connected":"disconnected"}`),e.push(`- **Provider**: ${B[n.provider]?.name||n.provider||"not set"}`),e.push(`- **Model**: ${n.model||"not set"}`),e.push(`- **API Key Set**: ${n.hasApiKey?"yes":"no"}`);let o=Object.entries(n.configuredProviders).filter(([,a])=>a).map(([a])=>B[a]?.name||a);if(o.length&&e.push(`- **Configured Providers**: ${o.join(", ")}`),n.roots.length&&e.push(`- **Project Roots**: ${n.roots.join(", ")}`),n.selectedElement){let a=n.selectedElement;e.push(""),e.push("## Selected Element"),e.push(""),e.push(`- **Selector**: \`${a.cssSelector||""}\``),e.push(`- **Tag**: \`${a.tagName}\``),a.id&&e.push(`- **ID**: \`${a.id}\``),a.className&&e.push(`- **Class**: \`${a.className}\``),a.componentHint&&e.push(`- **Component**: \`${a.componentHint}\``),a.ancestry?.length&&e.push(`- **Ancestry**: ${a.ancestry.join(" > ")}`),a.textContent&&e.push(`- **Text**: ${a.textContent.slice(0,150)}`)}if(n.groundedFiles.length){e.push(""),e.push("## Files Sent to LLM"),e.push("");for(let a of n.groundedFiles)e.push(`- \`${a}\``)}let r=[];for(let a of n.messages)if(a.content.startsWith("__DIFF__"))try{let g=JSON.parse(X(a.content.slice(8)));r.push({file:g.file,type:g.type||"edit"})}catch{}if(r.length){e.push(""),e.push("## Proposed Changes"),e.push("");for(let a of r)e.push(`- \`${a.file}\` (${a.type})`)}let l=n.messages.filter(a=>a.role==="system"&&(a.content.startsWith("Applied change to ")||a.content.startsWith("Rejected change to ")||a.content.startsWith("Reverted change to ")||a.content.startsWith("Created ")||a.content.startsWith("Change rejected")||a.content.startsWith("No matching code")||a.content.startsWith("Write failed")||a.content.startsWith("Could not read")));if(l.length){e.push(""),e.push("## Applied/Rejected Changes"),e.push("");for(let a of l)e.push(`- ${a.content.slice(0,200)}`)}let i=window.performance,d=i.getEntriesByType("navigation")[0],c=i.getEntriesByType("paint");if(d){e.push(""),e.push("## Page Performance"),e.push(""),e.push(`- **Page Load**: ${Math.round(d.loadEventEnd-d.startTime)}ms`),e.push(`- **DOM Ready**: ${Math.round(d.domContentLoadedEventEnd-d.startTime)}ms`),e.push(`- **TTFB**: ${Math.round(d.responseStart-d.startTime)}ms`);let a=c.find(g=>g.name==="first-contentful-paint");a&&e.push(`- **FCP**: ${Math.round(a.startTime)}ms`)}let p=le();if(p.length){let a=p.filter(u=>u.level==="error"),g=p.filter(u=>u.level==="warn"),m=p.filter(u=>u.level==="log"||u.level==="info"||u.level==="debug");if(e.push(""),e.push("## Browser Console"),e.push(""),e.push(`Total: ${p.length} entries (${a.length} errors, ${g.length} warnings, ${m.length} log/info/debug)`),a.length){e.push(""),e.push(`### Errors (${a.length})`),e.push("```");for(let u of a.slice(-15))e.push(`[${new Date(u.timestamp).toISOString()}] ${u.args.map(f=>String(f)).join(" ").slice(0,300)}`);e.push("```")}if(g.length){e.push(""),e.push(`### Warnings (${g.length})`),e.push("```");for(let u of g.slice(-10))e.push(`[${new Date(u.timestamp).toISOString()}] ${u.args.map(f=>String(f)).join(" ").slice(0,200)}`);e.push("```")}if(m.length){e.push(""),e.push("<details><summary>Log/Info/Debug ("+m.length+" entries)</summary>"),e.push(""),e.push("```");for(let u of m.slice(-30))e.push(`[${new Date(u.timestamp).toISOString()}] [${u.level}] ${u.args.map(f=>String(f)).join(" ").slice(0,200)}`);e.push("```"),e.push("</details>")}}let h=ie(),x=h.filter(a=>a.status&&a.status>=400),w=h.filter(a=>a.duration&&a.duration>2e3);if(x.length||w.length){if(e.push(""),e.push("## Network Issues"),e.push(""),x.length){e.push(`### Failed Requests (${x.length})`),e.push("```");for(let a of x.slice(-15))e.push(`${a.method} ${a.url.slice(0,120)} \u2192 ${a.status} (${a.duration||"?"}ms)`);e.push("```")}if(w.length){e.push(`### Slow Requests >2s (${w.length})`),e.push("```");for(let a of w.slice(-10))e.push(`${a.method} ${a.url.slice(0,120)} \u2192 ${a.status} (${a.duration}ms)`);e.push("```")}}if(s?.logs?.length){let a=s.logs,g=a.filter(f=>f.level==="error"),m=a.filter(f=>f.level==="warn"),u=a.filter(f=>f.level==="log"||f.level==="info");if(e.push(""),e.push("## Server Logs (Terminal)"),e.push(""),e.push(`Total: ${a.length} entries (${g.length} errors, ${m.length} warnings, ${u.length} log/info)`),g.length){e.push(""),e.push(`### Server Errors (${g.length})`),e.push("```");for(let f of g.slice(-15))e.push(`[${new Date(f.ts).toISOString()}] ${f.msg.slice(0,300)}`);e.push("```")}if(m.length){e.push(""),e.push(`### Server Warnings (${m.length})`),e.push("```");for(let f of m.slice(-10))e.push(`[${new Date(f.ts).toISOString()}] ${f.msg.slice(0,200)}`);e.push("```")}e.push(""),e.push("<details><summary>All server logs ("+a.length+" entries)</summary>"),e.push(""),e.push("```");for(let f of a.slice(-50))e.push(`[${new Date(f.ts).toISOString()}] [${f.level}] ${f.msg.slice(0,200)}`);e.push("```"),e.push("</details>")}if(n.messages.length){e.push(""),e.push("## Chat History"),e.push(""),e.push("<details><summary>Full conversation ("+n.messages.length+" messages)</summary>"),e.push(""),e.push("```");for(let a of n.messages)if(!a.content.startsWith("__DIFFGROUP__")){if(a.content.startsWith("__DIFF__")){try{let g=JSON.parse(X(a.content.slice(8)));e.push(`[diff] ${g.type||"edit"}: ${g.file}`),g.search&&e.push(` - search: ${g.search.slice(0,100)}...`),g.replace&&e.push(` + replace: ${g.replace.slice(0,100)}...`)}catch{e.push("[diff] (parse error)")}continue}e.push(`[${a.role}] ${a.content.slice(0,500)}`)}e.push("```"),e.push("</details>")}if(t!==void 0){let a=n.messages[t];a&&(e.push(""),e.push("## Copied Message"),e.push(""),e.push("```"),e.push(`[${a.role}] ${a.content.slice(0,2e3)}`),e.push("```"))}return e.join(`
496
+ `)}function Ct(){fetch("https://registry.npmjs.org/openmagic/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)}).then(t=>t.ok?t.json():null).then(t=>{if(!t?.version)return;let e=t.version.split(".").map(Number),s=Ee.split(".").map(Number);for(let o=0;o<3;o++){if((e[o]||0)>(s[o]||0)){n.updateAvailable=!0,n.latestVersion=t.version,Ht();return}if((e[o]||0)<(s[o]||0))return}}).catch(()=>{})}function Ht(){pe()}typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",We):We());})();
495
497
  //# sourceMappingURL=index.global.js.map