openmagic 0.30.3 → 0.30.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +2 -2
- package/dist/cli.js.map +1 -1
- package/dist/toolbar/index.global.js +35 -35
- package/dist/toolbar/index.global.js.map +1 -1
- package/package.json +1 -1
|
@@ -369,72 +369,72 @@
|
|
|
369
369
|
.om-msg:hover .om-copy-btn { opacity: 1; }
|
|
370
370
|
.om-copy-btn:hover { color: #ccc; background: rgba(0,0,0,0.5); }
|
|
371
371
|
.om-msg { position: relative; }
|
|
372
|
-
`;var
|
|
372
|
+
`;var _=null,T=new Map,G=[],me=[],B=!1,Me=!1,de=null,pe=0;function ue(){return Math.random().toString(36).slice(2)+Date.now().toString(36)}function ge(e,o){return Me=!0,new Promise((s,t)=>{let a=!1,i=setTimeout(()=>{a||(a=!0,t(new Error("Handshake timeout")),_?.close())},1e4);try{let r=window.location.hostname||"127.0.0.1",d=window.location.protocol==="https:"?"wss:":"ws:";_=new WebSocket(`${d}//${r}:${e}/__openmagic__/ws`),_.onopen=()=>{let l=ue();_.send(JSON.stringify({id:l,type:"handshake",payload:{token:o}})),T.set(l,p=>{if(p.type==="handshake.ok"){clearTimeout(i),B=!0,pe=0;for(let c of me)_?.send(c);me=[],a||(a=!0,s())}else p.type==="error"&&(clearTimeout(i),a||(a=!0,t(new Error(p.payload?.message||"Handshake failed"))))})},_.onmessage=l=>{try{let p=JSON.parse(l.data);p.id&&T.has(p.id)&&(T.get(p.id)(p),(p.type==="llm.done"||p.type==="llm.error"||!p.type.startsWith("llm."))&&T.delete(p.id));for(let c of G)c(p)}catch{}},_.onclose=()=>{let l=B;if(B=!1,T.forEach((p,c)=>{p({type:"error",id:c,payload:{message:"Connection lost"}})}),T.clear(),!l&&!a){clearTimeout(i),a=!0,t(new Error("WebSocket closed before handshake"));return}if(l&&Me&&!de){let p=Math.min(2e3*Math.pow(1.5,pe),3e4);pe++,de=setTimeout(()=>{de=null,ge(e,o).then(()=>{for(let c of G)c({type:"reconnected",payload:{}})}).catch(()=>{})},p)}},_.onerror=()=>{!B&&!a&&(clearTimeout(i),a=!0,t(new Error("WebSocket connection failed")))}}catch(r){clearTimeout(i),a||(a=!0,t(r))}})}function Le(e){let o=JSON.stringify(e);_&&_.readyState===WebSocket.OPEN&&B?_.send(o):me.push(o)}function k(e,o){return new Promise((s,t)=>{let a=ue(),i=setTimeout(()=>{T.delete(a),t(new Error("Request timeout"))},3e4);T.set(a,r=>{clearTimeout(i),r.type==="error"?t(new Error(r.payload?.message||"Unknown error")):s(r)}),Le({id:a,type:e,payload:o})})}function Te(e,o,s){return new Promise((t,a)=>{let i=ue(),r=setTimeout(()=>{T.delete(i),a(new Error("Stream timeout"))},12e4);T.set(i,d=>{d.type==="llm.chunk"?s(d.payload?.delta||""):d.type==="llm.done"?(clearTimeout(r),T.delete(i),t(d.payload)):(d.type==="llm.error"||d.type==="error")&&(clearTimeout(r),T.delete(i),a(new Error(d.payload?.message||"Stream error")))}),Le({id:i,type:e,payload:o})})}function Ce(e){return G.push(e),()=>{G=G.filter(o=>o!==e)}}function He(){return B}var Pe=["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 _e(e){let o=window.getComputedStyle(e),s={};for(let c of Pe)s[c]=o.getPropertyValue(c);let t=e.getBoundingClientRect(),a={};if(e.parentElement&&e.parentElement!==document.body){let c=window.getComputedStyle(e.parentElement);for(let y of Pe)a[y]=c.getPropertyValue(y)}let i=[];if(e.parentElement){let c=Array.from(e.parentElement.children),y=c.indexOf(e),m=Math.max(0,y-3),b=Math.min(c.length,y+4);m>0&&i.push(`... ${m} elements before ...`);for(let u=m;u<b;u++){let f=c[u],h=f.tagName.toLowerCase(),M=(f.className||"").toString().slice(0,60);f===e?i.push(`[SELECTED] <${h} class="${M}">`):i.push(`<${h} class="${M}">`)}b<c.length&&i.push(`... ${c.length-b} elements after ...`)}let r=ot(e),d={};for(let c of Array.from(e.attributes))(c.name.startsWith("aria-")||c.name==="role"||c.name==="tabindex")&&(d[c.name]=c.value);let l=[];for(let c of Array.from(e.attributes))c.name.startsWith("on")&&l.push(c.name);let p=st(e);return{tagName:e.tagName.toLowerCase(),id:e.id||"",className:e.className||"",textContent:(e.textContent||"").trim().slice(0,200),outerHTML:et(e),cssSelector:tt(e),xpath:nt(e),computedStyles:s,ancestry:Ze(e),componentHint:Qe(e),rect:{x:t.x,y:t.y,width:t.width,height:t.height},parentStyles:a,siblings:i,matchedCssRules:r,viewport:{width:window.innerWidth,height:window.innerHeight},ariaAttributes:d,eventHandlers:l,reactProps:p}}function Ze(e,o=5){let s=[],t=e.parentElement;for(;t&&t!==document.body&&s.length<o;){let a=t.tagName.toLowerCase(),i=(typeof t.className=="string"?t.className:"").split(/\s+/).filter(r=>r.length>1&&!r.startsWith("_")).slice(0,3).join(".");s.push(i?`${a}.${i}`:a),t=t.parentElement}return s}function Qe(e){let o=e;for(;o&&o!==document.body;){let s=o.getAttribute("data-component")||o.getAttribute("data-testid")||o.getAttribute("data-cy");if(s)return s;let t=Object.keys(o);for(let a of t)if(a.startsWith("__reactFiber")||a.startsWith("__reactInternalInstance"))try{let i=o[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{}o=o.parentElement}return""}function et(e){let o=e.cloneNode(!0);o.querySelectorAll("script, style, svg").forEach(a=>a.remove());let t=o.outerHTML;if(t.length>2e3){let a=e.tagName.toLowerCase(),i=Array.from(e.attributes).map(d=>`${d.name}="${d.value}"`).join(" "),r=Array.from(e.children).slice(0,5).map(d=>`<${d.tagName.toLowerCase()} .../>`).join(`
|
|
373
373
|
`);t=`<${a} ${i}>
|
|
374
374
|
${r}
|
|
375
375
|
${e.children.length>5?`<!-- +${e.children.length-5} more children -->`:""}
|
|
376
|
-
</${a}>`}return t}function tt(e){if(e.id)return`#${CSS.escape(e.id)}`;let o=[],s=e;for(;s&&s!==document.body;){let t=s.tagName.toLowerCase();if(s.id){o.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&&(t+="."+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;t+=`:nth-of-type(${r})`}}o.unshift(t),s=s.parentElement}return o.join(" > ")}function nt(e){let o=[],s=e;for(;s&&s!==document;){if(s.nodeType===Node.ELEMENT_NODE){let t=s,a=1,i=t.previousElementSibling;for(;i;)i.tagName===t.tagName&&a++,i=i.previousElementSibling;o.unshift(`${t.tagName.toLowerCase()}[${a}]`)}s=s.parentNode}return"/"+o.join("/")}function ot(e){let o=[];try{for(let s of Array.from(document.styleSheets))try{let t=s.cssRules||s.rules;if(!t)continue;for(let a of Array.from(t))if(a instanceof CSSStyleRule)try{if(e.matches(a.selectorText)){let i=a.cssText;i.length>10&&i.length<500&&o.push(i)}}catch{}}catch{}}catch{}return o.slice(0,15)}function st(e){try{let o=Object.keys(e);for(let s of o)if(s.startsWith("__reactFiber")||s.startsWith("__reactInternalInstance")){let t=e[s];if(!t?.memoizedProps)continue;let a=t.memoizedProps,i={},r=0;for(let[d,l]of Object.entries(a)){if(r>=10)break;if(d==="children")continue;let p=typeof l;p==="string"||p==="number"||p==="boolean"||l===null?(i[d]=l,r++):p==="function"?(i[d]="[function]",r++):Array.isArray(l)&&(i[d]=`[Array(${l.length})]`,r++)}return Object.keys(i).length>0?i:null}}catch{}return null}var
|
|
376
|
+
</${a}>`}return t}function tt(e){if(e.id)return`#${CSS.escape(e.id)}`;let o=[],s=e;for(;s&&s!==document.body;){let t=s.tagName.toLowerCase();if(s.id){o.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&&(t+="."+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;t+=`:nth-of-type(${r})`}}o.unshift(t),s=s.parentElement}return o.join(" > ")}function nt(e){let o=[],s=e;for(;s&&s!==document;){if(s.nodeType===Node.ELEMENT_NODE){let t=s,a=1,i=t.previousElementSibling;for(;i;)i.tagName===t.tagName&&a++,i=i.previousElementSibling;o.unshift(`${t.tagName.toLowerCase()}[${a}]`)}s=s.parentNode}return"/"+o.join("/")}function ot(e){let o=[];try{for(let s of Array.from(document.styleSheets))try{let t=s.cssRules||s.rules;if(!t)continue;for(let a of Array.from(t))if(a instanceof CSSStyleRule)try{if(e.matches(a.selectorText)){let i=a.cssText;i.length>10&&i.length<500&&o.push(i)}}catch{}}catch{}}catch{}return o.slice(0,15)}function st(e){try{let o=Object.keys(e);for(let s of o)if(s.startsWith("__reactFiber")||s.startsWith("__reactInternalInstance")){let t=e[s];if(!t?.memoizedProps)continue;let a=t.memoizedProps,i={},r=0;for(let[d,l]of Object.entries(a)){if(r>=10)break;if(d==="children")continue;let p=typeof l;p==="string"||p==="number"||p==="boolean"||l===null?(i[d]=l,r++):p==="function"?(i[d]="[function]",r++):Array.isArray(l)&&(i[d]=`[Array(${l.length})]`,r++)}return Object.keys(i).length>0?i:null}}catch{}return null}var C=null;function Ne(e){C||(C=document.createElement("div"),C.style.cssText=`
|
|
377
377
|
position: fixed;
|
|
378
378
|
pointer-events: none;
|
|
379
379
|
z-index: 2147483646;
|
|
380
380
|
border: 2px solid #6c5ce7;
|
|
381
381
|
background: rgba(108, 92, 231, 0.1);
|
|
382
382
|
transition: all 0.1s ease;
|
|
383
|
-
`,
|
|
383
|
+
`,C.dataset.openmagic="highlight",document.body.appendChild(C)),C.style.left=`${e.x}px`,C.style.top=`${e.y}px`,C.style.width=`${e.width}px`,C.style.height=`${e.height}px`,C.style.display="block"}function Re(){C&&(C.style.display="none")}async function Ae(e){try{let o=e||document.body,s=await at(o);if(s)return{data:s}}catch{}try{let o=await rt(e);if(o)return{data:o}}catch(o){return{data:null,error:`Screenshot failed: ${o.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 at(e){let o=e.getBoundingClientRect(),s=Math.min(o.width||window.innerWidth,1920),t=Math.min(o.height||window.innerHeight,1080),a=Oe(e,0,4);if(!a)return null;let i=`
|
|
384
384
|
<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${t}">
|
|
385
385
|
<foreignObject width="100%" height="100%">
|
|
386
386
|
<div xmlns="http://www.w3.org/1999/xhtml" style="width:${s}px;height:${t}px;overflow:hidden;">
|
|
387
387
|
${a.outerHTML}
|
|
388
388
|
</div>
|
|
389
389
|
</foreignObject>
|
|
390
|
-
</svg>`,r=new Blob([i],{type:"image/svg+xml;charset=utf-8"}),d=URL.createObjectURL(r);return new Promise(l=>{let p=new Image,c=document.createElement("canvas"),g=Math.min(window.devicePixelRatio||1,2);c.width=s*g,c.height=t*g,p.onload=()=>{URL.revokeObjectURL(d);let m=c.getContext("2d");if(!m){l(null);return}m.scale(g,g),m.drawImage(p,0,0);try{l(c.toDataURL("image/png",.8))}catch{l(null)}},p.onerror=()=>{URL.revokeObjectURL(d),l(null)},setTimeout(()=>{URL.revokeObjectURL(d),l(null)},5e3),p.src=d})}async function rt(e){let o=e||document.documentElement,s=o.getBoundingClientRect(),t=document.createElement("canvas");t.width=400,t.height=300;let a=t.getContext("2d");return a?(a.fillStyle="#1a1a2e",a.fillRect(0,0,400,300),a.fillStyle="#e0e0e0",a.font="14px system-ui",a.fillText(`Element: <${o.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: ${(o.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),t.toDataURL("image/png")):null}function Oe(e,o,s){if(o>s)return null;try{let t=e.cloneNode(!1);if(t.tagName==="SCRIPT"||t.tagName==="STYLE"||t.tagName==="SVG"||t.tagName==="CANVAS"||t.tagName==="VIDEO"||t.tagName==="IFRAME")return null;let a=window.getComputedStyle(e),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 d of i){let l=a.getPropertyValue(d);l&&l!=="normal"&&l!=="none"&&l!=="auto"&&l!=="0px"&&(r+=`${d}:${l};`)}t.setAttribute("style",r);for(let d=0;d<e.children.length&&d<20;d++){let l=Oe(e.children[d],o+1,s);l&&t.appendChild(l)}return t}catch{return null}}var Q=[];var ze=!1;function De(){if(ze)return;ze=!0;let e=window.fetch;window.fetch=async function(...t){let a=new Request(...t),i={method:a.method,url:a.url,timestamp:Date.now()};try{let r=await e.apply(this,t);return i.status=r.status,i.duration=Date.now()-i.timestamp,he(i),r}catch(r){throw i.status=0,i.duration=Date.now()-i.timestamp,he(i),r}};let o=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(t,a,...i){return this.__om_method=t,this.__om_url=a,this.__om_start=Date.now(),o.apply(this,[t,a,...i])},XMLHttpRequest.prototype.send=function(...t){return this.addEventListener("loadend",()=>{he({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,t)}}function he(e){e.url.includes("__openmagic__")||(Q.push(e),Q.length>50&&Q.shift())}function fe(){return[...Q]}var ee=[],it=100,qe=!1;function Ie(){if(qe)return;qe=!0;let e=["log","warn","error","info","debug"];for(let o of e){let s=console[o];console[o]=function(...t){ee.push({level:o,args:t.map(a=>{try{return typeof a=="object"?JSON.stringify(a).slice(0,500):String(a)}catch{return String(a)}}),timestamp:Date.now()}),ee.length>it&&ee.shift(),s.apply(console,t)}}}function ye(){return[...ee]}function je(e,o){return{selectedElement:e?{tagName:e.tagName,id:e.id,className:e.className,textContent:e.textContent,outerHTML:e.outerHTML,cssSelector:e.cssSelector,computedStyles:e.computedStyles}:void 0,screenshot:o||void 0,networkLogs:fe().map(s=>({method:s.method,url:s.url,status:s.status,duration:s.duration,timestamp:s.timestamp})),consoleLogs:ye().map(s=>({level:s.level,args:s.args,timestamp:s.timestamp}))}}var y={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>',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 ne(e){let o=new TextEncoder().encode(e),s="";for(let t=0;t<o.length;t+=32768)s+=String.fromCharCode(...o.subarray(t,t+32768));return btoa(s)}function oe(e){let o=atob(e),s=new Uint8Array(o.length);for(let t=0;t<o.length;t++)s[t]=o.charCodeAt(t);return new TextDecoder().decode(s)}var Ke="0.30.3",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},w,S,q,Ge,Se,A;function lt(){try{sessionStorage.setItem("__om_state__",JSON.stringify({messages:n.messages,provider:n.provider,model:n.model,panelOpen:n.panelOpen,activePanel:n.activePanel}))}catch{}}function ct(){try{let e=JSON.parse(sessionStorage.getItem("__om_state__")||"{}");e.messages?.length&&(n.messages=e.messages),e.provider&&(n.provider=e.provider),e.model&&(n.model=e.model),e.panelOpen&&(n.panelOpen=e.panelOpen,n.activePanel=e.activePanel||"")}catch{}}function Be(){if(document.querySelector("openmagic-toolbar"))return;ct();let e=document.createElement("openmagic-toolbar");e.dataset.openmagic="true",w=e.attachShadow({mode:"closed"});let o=document.createElement("style");o.textContent=Ee,w.appendChild(o);let s=document.createElement("div");w.appendChild(s),s.innerHTML=dt(),S=s.querySelector(".om-toolbar"),q=s.querySelector(".om-prompt-input"),Ge=s.querySelector(".om-prompt-context"),Se=s.querySelector(".om-panel"),A=s.querySelector(".om-panel-body"),document.body.appendChild(e),pt(s),kt();try{let r=JSON.parse(localStorage.getItem("__om_pos__")||"");r?.left&&r?.top&&(S.style.left=r.left,S.style.top=r.top,S.style.right="auto",S.style.bottom="auto")}catch{}De(),Ie(),$t();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&&ge(i,a).then(()=>(n.connected=!0,ve(),v("config.get"))).then(r=>{let d=r.payload?.provider||"",l=r.payload?.model||"";n.provider=n.provider||d,n.model=n.model||l,n.configuredProviders=r.payload?.apiKeys||{},n.hasApiKey=n.configuredProviders[n.provider]||!1,n.roots=r.payload?.roots||[],n.panelOpen&&n.activePanel?R(n.activePanel):(!n.provider||!n.hasApiKey&&!Object.values(n.configuredProviders).some(Boolean))&&R("settings"),J()}).catch(()=>{n.connected=!1,ve()})}function dt(){return`
|
|
390
|
+
</svg>`,r=new Blob([i],{type:"image/svg+xml;charset=utf-8"}),d=URL.createObjectURL(r);return new Promise(l=>{let p=new Image,c=document.createElement("canvas"),y=Math.min(window.devicePixelRatio||1,2);c.width=s*y,c.height=t*y,p.onload=()=>{URL.revokeObjectURL(d);let m=c.getContext("2d");if(!m){l(null);return}m.scale(y,y),m.drawImage(p,0,0);try{l(c.toDataURL("image/png",.8))}catch{l(null)}},p.onerror=()=>{URL.revokeObjectURL(d),l(null)},setTimeout(()=>{URL.revokeObjectURL(d),l(null)},5e3),p.src=d})}async function rt(e){let o=e||document.documentElement,s=o.getBoundingClientRect(),t=document.createElement("canvas");t.width=400,t.height=300;let a=t.getContext("2d");return a?(a.fillStyle="#1a1a2e",a.fillRect(0,0,400,300),a.fillStyle="#e0e0e0",a.font="14px system-ui",a.fillText(`Element: <${o.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: ${(o.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),t.toDataURL("image/png")):null}function Oe(e,o,s){if(o>s)return null;try{let t=e.cloneNode(!1);if(t.tagName==="SCRIPT"||t.tagName==="STYLE"||t.tagName==="SVG"||t.tagName==="CANVAS"||t.tagName==="VIDEO"||t.tagName==="IFRAME")return null;let a=window.getComputedStyle(e),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 d of i){let l=a.getPropertyValue(d);l&&l!=="normal"&&l!=="none"&&l!=="auto"&&l!=="0px"&&(r+=`${d}:${l};`)}t.setAttribute("style",r);for(let d=0;d<e.children.length&&d<20;d++){let l=Oe(e.children[d],o+1,s);l&&t.appendChild(l)}return t}catch{return null}}var Q=[];var ze=!1;function De(){if(ze)return;ze=!0;let e=window.fetch;window.fetch=async function(...t){let a=new Request(...t),i={method:a.method,url:a.url,timestamp:Date.now()};try{let r=await e.apply(this,t);return i.status=r.status,i.duration=Date.now()-i.timestamp,he(i),r}catch(r){throw i.status=0,i.duration=Date.now()-i.timestamp,he(i),r}};let o=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(t,a,...i){return this.__om_method=t,this.__om_url=a,this.__om_start=Date.now(),o.apply(this,[t,a,...i])},XMLHttpRequest.prototype.send=function(...t){return this.addEventListener("loadend",()=>{he({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,t)}}function he(e){e.url.includes("__openmagic__")||(Q.push(e),Q.length>50&&Q.shift())}function fe(){return[...Q]}var ee=[],it=100,qe=!1;function Ie(){if(qe)return;qe=!0;let e=["log","warn","error","info","debug"];for(let o of e){let s=console[o];console[o]=function(...t){ee.push({level:o,args:t.map(a=>{try{return typeof a=="object"?JSON.stringify(a).slice(0,500):String(a)}catch{return String(a)}}),timestamp:Date.now()}),ee.length>it&&ee.shift(),s.apply(console,t)}}}function ye(){return[...ee]}function Be(e,o){return{selectedElement:e?{tagName:e.tagName,id:e.id,className:e.className,textContent:e.textContent,outerHTML:e.outerHTML,cssSelector:e.cssSelector,computedStyles:e.computedStyles}:void 0,screenshot:o||void 0,networkLogs:fe().map(s=>({method:s.method,url:s.url,status:s.status,duration:s.duration,timestamp:s.timestamp})),consoleLogs:ye().map(s=>({level:s.level,args:s.args,timestamp:s.timestamp}))}}var x={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>',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>'},j={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 ne(e){let o=new TextEncoder().encode(e),s="";for(let t=0;t<o.length;t+=32768)s+=String.fromCharCode(...o.subarray(t,t+32768));return btoa(s)}function oe(e){let o=atob(e),s=new Uint8Array(o.length);for(let t=0;t<o.length;t++)s[t]=o.charCodeAt(t);return new TextDecoder().decode(s)}var Ke="0.30.5",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},S,$,q,Ge,Se,A;function lt(){try{sessionStorage.setItem("__om_state__",JSON.stringify({messages:n.messages,provider:n.provider,model:n.model,panelOpen:n.panelOpen,activePanel:n.activePanel}))}catch{}}function ct(){try{let e=JSON.parse(sessionStorage.getItem("__om_state__")||"{}");e.messages?.length&&(n.messages=e.messages),e.provider&&(n.provider=e.provider),e.model&&(n.model=e.model),e.panelOpen&&(n.panelOpen=e.panelOpen,n.activePanel=e.activePanel||"")}catch{}}function je(){if(document.querySelector("openmagic-toolbar"))return;ct();let e=document.createElement("openmagic-toolbar");e.dataset.openmagic="true",S=e.attachShadow({mode:"closed"});let o=document.createElement("style");o.textContent=Ee,S.appendChild(o);let s=document.createElement("div");S.appendChild(s),s.innerHTML=dt(),$=s.querySelector(".om-toolbar"),q=s.querySelector(".om-prompt-input"),Ge=s.querySelector(".om-prompt-context"),Se=s.querySelector(".om-panel"),A=s.querySelector(".om-panel-body"),document.body.appendChild(e),pt(s),kt();try{let r=JSON.parse(localStorage.getItem("__om_pos__")||"");r?.left&&r?.top&&($.style.left=r.left,$.style.top=r.top,$.style.right="auto",$.style.bottom="auto")}catch{}De(),Ie(),$t();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&&ge(i,a).then(()=>(n.connected=!0,ve(),k("config.get"))).then(r=>{let d=r.payload?.provider||"",l=r.payload?.model||"";n.provider=n.provider||d,n.model=n.model||l,n.configuredProviders=r.payload?.apiKeys||{},n.hasApiKey=n.configuredProviders[n.provider]||!1,n.roots=r.payload?.roots||[],n.panelOpen&&n.activePanel?O(n.activePanel):(!n.provider||!n.hasApiKey&&!Object.values(n.configuredProviders).some(Boolean))&&O("settings"),J()}).catch(()=>{n.connected=!1,ve()})}function dt(){return`
|
|
391
391
|
<div class="om-toolbar">
|
|
392
392
|
<div class="om-toolbar-header">
|
|
393
|
-
<span class="om-grab">${
|
|
393
|
+
<span class="om-grab">${x.grip}</span>
|
|
394
394
|
<span class="om-pill-brand">
|
|
395
395
|
<span class="om-pill-text">\u2728OpenMagic\u{1FA84}</span>
|
|
396
396
|
</span>
|
|
397
397
|
<span class="om-pill-divider"></span>
|
|
398
|
-
<button class="om-pill-btn" data-action="select" title="Select element">${
|
|
399
|
-
<button class="om-pill-btn" data-action="screenshot" title="Screenshot">${
|
|
400
|
-
<button class="om-pill-btn" data-action="network" title="Network & Performance">${
|
|
398
|
+
<button class="om-pill-btn" data-action="select" title="Select element">${x.crosshair}</button>
|
|
399
|
+
<button class="om-pill-btn" data-action="screenshot" title="Screenshot">${x.camera}</button>
|
|
400
|
+
<button class="om-pill-btn" data-action="network" title="Network & Performance">${x.activity}</button>
|
|
401
401
|
<span class="om-pill-divider"></span>
|
|
402
|
-
<button class="om-pill-btn" data-action="chat" title="Chat">${
|
|
403
|
-
<button class="om-pill-btn" data-action="settings" title="Settings">${
|
|
404
|
-
<button class="om-pill-btn" data-action="minimize" title="Minimize">${
|
|
402
|
+
<button class="om-pill-btn" data-action="chat" title="Chat">${x.chat}</button>
|
|
403
|
+
<button class="om-pill-btn" data-action="settings" title="Settings">${x.settings}</button>
|
|
404
|
+
<button class="om-pill-btn" data-action="minimize" title="Minimize">${x.minus}</button>
|
|
405
405
|
<span class="om-status-dot disconnected"></span>
|
|
406
406
|
</div>
|
|
407
407
|
<div class="om-panel om-hidden">
|
|
408
408
|
<div class="om-panel-header">
|
|
409
409
|
<span class="om-panel-title"></span>
|
|
410
410
|
<span class="om-panel-version">v${Ke}</span>
|
|
411
|
-
<button class="om-panel-clear" data-action="clear-chat" title="Clear chat">${
|
|
412
|
-
<button class="om-panel-close" data-action="close-panel">${
|
|
411
|
+
<button class="om-panel-clear" data-action="clear-chat" title="Clear chat">${x.trash}</button>
|
|
412
|
+
<button class="om-panel-close" data-action="close-panel">${x.x}</button>
|
|
413
413
|
</div>
|
|
414
414
|
<div class="om-panel-body"></div>
|
|
415
415
|
</div>
|
|
416
416
|
<div class="om-prompt-attachments"></div>
|
|
417
417
|
<div class="om-prompt-row">
|
|
418
418
|
<div class="om-prompt-context"></div>
|
|
419
|
-
<button class="om-prompt-attach" data-action="attach-image" title="Attach image">${
|
|
419
|
+
<button class="om-prompt-attach" data-action="attach-image" title="Attach image">${x.paperclip}</button>
|
|
420
420
|
<input class="om-prompt-input" type="text" placeholder="Describe what to change..." autocomplete="off" />
|
|
421
|
-
<button class="om-prompt-send" data-action="prompt-send">${
|
|
421
|
+
<button class="om-prompt-send" data-action="prompt-send">${x.send}</button>
|
|
422
422
|
<input type="file" class="om-file-input om-hidden" accept="image/*" multiple />
|
|
423
423
|
</div>
|
|
424
|
-
</div>`}function pt(e){e.addEventListener("click",t=>{let a=t.target.closest("[data-action]");if(!a)return;t.preventDefault(),t.stopPropagation();let i=a.dataset.action;gt(i,a)}),e.addEventListener("change",t=>{let a=t.target,i=a.dataset.field;i&&(i==="provider"?(n.provider=a.value,n.model=
|
|
424
|
+
</div>`}function pt(e){e.addEventListener("click",t=>{let a=t.target.closest("[data-action]");if(!a)return;t.preventDefault(),t.stopPropagation();let i=a.dataset.action;gt(i,a)}),e.addEventListener("change",t=>{let a=t.target,i=a.dataset.field;i&&(i==="provider"?(n.provider=a.value,n.model=j[n.provider]?.models[0]?.id||"",n.hasApiKey=n.configuredProviders[n.provider]||j[n.provider]?.local||!1,n.saveStatus="",E()):i==="model"&&(n.model=a.value))}),q.addEventListener("keydown",t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),we())});let o=e.querySelector(".om-file-input");o&&o.addEventListener("change",()=>{xe(o.files),o.value=""});let s=e.querySelector(".om-prompt-row");s&&(s.addEventListener("dragover",t=>{t.preventDefault(),s.style.borderColor="rgba(108, 92, 231, 0.5)"}),s.addEventListener("dragleave",()=>{s.style.borderColor=""}),s.addEventListener("drop",t=>{t.preventDefault(),s.style.borderColor="";let a=t.dataTransfer;a?.files?.length&&xe(a.files)}),q.addEventListener("paste",t=>{let a=t.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 d=new DataTransfer;d.items.add(r),xe(d.files)}}}})),Ce(t=>{t.type==="reconnected"&&(n.connected=!0,ve())}),document.addEventListener("keydown",t=>{if((t.ctrlKey||t.metaKey)&&t.shiftKey&&(t.key==="O"||t.key==="o")){if(t.preventDefault(),n.minimized){n.minimized=!1,$.querySelectorAll(".om-pill-btn:not([data-action='minimize']), .om-pill-divider, .om-status-dot").forEach(r=>r.style.display="");let i=S.querySelector(".om-prompt-row");i&&i.classList.remove("om-hidden")}else n.panelOpen?se():O("chat");return}if(t.key==="Escape"){if(n.selecting)return;n.panelOpen&&(se(),t.preventDefault())}}),q.addEventListener("keydown",t=>{(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),we())})}function We(e){return n.roots.length>0?n.roots[0]+"/"+e:e}function mt(e,o){let s=o.split(`
|
|
425
425
|
`).map(r=>r.trim()).filter(r=>r.length>0);if(s.length===0)return null;let t=e.split(`
|
|
426
426
|
`),a=s[0],i=s[s.length-1];for(let r=0;r<t.length;r++){if(t[r].trim()!==a||r+s.length>t.length)continue;let d=!0;for(let l=0;l<s.length;l++)if(t[r+l].trim()!==s[l]){d=!1;break}if(d){let l=0;for(let c=0;c<r;c++)l+=t[c].length+1;let p=l;for(let c=r;c<r+s.length;c++)p+=t[c].length+1;return p>0&&p<=e.length&&e[p-1]===`
|
|
427
|
-
`&&p--,{start:l,end:p}}}return null}async function Fe(e){let o=e.dataset.file,s=e.dataset.search,t=e.dataset.replace;if(!o||!s||!t)return;e.disabled=!0,e.innerHTML='<span class="om-spinner"></span>',e.style.opacity="0.5",e.style.pointerEvents="none";let a=e.closest(".om-diff-card");if(a){let l=a.querySelector(".om-diff-actions");l&&(l.innerHTML='<span class="om-spinner"></span> Applying...')}await new Promise(l=>requestAnimationFrame(l));let i,r;try{i=oe(s),r=oe(t)}catch{n.messages.push({role:"system",content:`Failed to decode diff data for ${o}`})
|
|
427
|
+
`&&p--,{start:l,end:p}}}return null}async function Fe(e){let o=e.dataset.file,s=e.dataset.search,t=e.dataset.replace;if(!o||!s||!t)return;e.disabled=!0,e.innerHTML='<span class="om-spinner"></span>',e.style.opacity="0.5",e.style.pointerEvents="none";let a=e.closest(".om-diff-card");if(a){let l=a.querySelector(".om-diff-actions");l&&(l.innerHTML='<span class="om-spinner"></span> Applying...')}await new Promise(l=>requestAnimationFrame(l));let i,r;try{i=oe(s),r=oe(t)}catch{n.messages.push({role:"system",content:`Failed to decode diff data for ${o}`}),E();return}let d=We(o);try{if(!i&&r){if((await k("fs.write",{path:d,content:r}))?.payload?.ok===!1)n.messages.push({role:"system",content:`Write failed: ${o}`});else{let f=a?.dataset.diffIdx;f!==void 0?n.messages[parseInt(f)]={role:"system",content:`Created ${o}`}:n.messages.push({role:"system",content:`Created ${o}`})}E(),F();return}let l,p=d,c=[d];o!==d&&c.push(o);let y=o.split("/").pop()||o,m=n.roots[0]||"",b=m?`${m}/${y}`:y;b!==d&&b!==o&&c.push(b);for(let u of c){let h=(await k("fs.read",{path:u}).catch(()=>null))?.payload?.content;if(h!=null&&String(h).length>0){l=String(h),p=u;break}}if(!l)n.messages.push({role:"system",content:`Could not read ${o} \u2014 tried: ${c.join(", ")}`});else{let u=l.split(i).length-1;if(u===1){let f=await k("fs.write",{path:p,content:l.replace(i,r)});if(f?.payload?.ok===!1)n.messages.push({role:"system",content:`Write failed: ${o} - ${f.payload?.error||"unknown"}`});else{let h=a?.dataset.diffIdx;h!==void 0?n.messages[parseInt(h)]={role:"system",content:`Applied change to ${o}. Refresh the page to see the update.`}:n.messages.push({role:"system",content:`Applied change to ${o}. Refresh the page to see the update.`})}}else if(u>1)n.messages.push({role:"system",content:`Found ${u} exact matches in ${o} \u2014 expected 1. Edit not applied.`});else{let f=mt(l,i);if(f){let h=l.slice(0,f.start)+r+l.slice(f.end),M=await k("fs.write",{path:p,content:h});if(M?.payload?.ok===!1)n.messages.push({role:"system",content:`Write failed: ${o} - ${M.payload?.error||"unknown"}`});else{let w=a?.dataset.diffIdx;w!==void 0?n.messages[parseInt(w)]={role:"system",content:`Applied change to ${o} (fuzzy match). Refresh the page to see the update.`}:n.messages.push({role:"system",content:`Applied change to ${o} (fuzzy match). Refresh the page to see the update.`})}}else n.messages.push({role:"system",content:`No matching code found in ${o}. The file may have changed since the suggestion.`})}}}catch(l){n.messages.push({role:"system",content:`Failed to apply: ${o} \u2014 ${l.message}`})}E(),F()}function Ue(e){e.disabled=!0,e.style.opacity="0.5";let o=e.dataset.idx;if(o!==void 0){let s=parseInt(o);try{let t=JSON.parse(oe(n.messages[s]?.content.slice(8)||""));n.messages[s]={role:"system",content:`Rejected change to ${t.file||"file"}`}}catch{n.messages[s]={role:"system",content:"Change rejected"}}}E(),F()}async function ut(e){let o=e.dataset.file;if(!o)return;let s=We(o),t=s+".openmagic-backup";try{let i=(await k("fs.read",{path:t}))?.payload?.content;i?(await k("fs.write",{path:s,content:i}),n.messages.push({role:"system",content:`Reverted change to ${o}`})):n.messages.push({role:"system",content:`No backup found for ${o}`})}catch{n.messages.push({role:"system",content:`Could not revert ${o} \u2014 backup may not exist`})}E()}function gt(e,o){switch(e){case"select":vt();break;case"screenshot":wt();break;case"chat":be("chat");break;case"settings":be("settings");break;case"close-panel":se();break;case"prompt-send":we();break;case"save-settings":yt();break;case"get-key":{let s=o.dataset.url;s&&window.open(s,"_blank","noopener");break}case"change-key":{let s=S.querySelector("[data-key-change]");s&&s.classList.remove("om-hidden"),o.style.display="none";break}case"network":be("chat"),bt();break;case"attach-image":xt();break;case"remove-attachment":{let s=parseInt(o.dataset.idx||"0",10);n.attachments.splice(s,1),$e();break}case"apply-diff":Fe(o);break;case"reject-diff":Ue(o);break;case"apply-all":{if(o.dataset.group){let t=S.querySelectorAll('[data-action="apply-diff"]');for(let a of Array.from(t))a.closest(".om-diff-card")&&Fe(a)}break}case"reject-all":{if(o.dataset.group){let t=S.querySelectorAll('[data-action="reject-diff"]');for(let a of Array.from(t))Ue(a)}break}case"undo-diff":ut(o);break;case"clear-chat":{n.messages=[];try{sessionStorage.removeItem("__om_state__")}catch{}E();break}case"copy-msg":{let s=parseInt(o.dataset.idx||"0",10),t=n.messages[s];if(t){try{navigator.clipboard.writeText(t.content)}catch{}o.innerHTML=x.check,setTimeout(()=>{o.innerHTML=x.copy},1500)}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=S.querySelector(".om-panel"),t=S.querySelector(".om-prompt-row"),a=S.querySelector(".om-prompt-attachments"),i=$.querySelectorAll(".om-pill-btn:not([data-action='minimize']), .om-pill-divider, .om-status-dot");n.minimized?(s&&s.classList.add("om-hidden"),t&&t.classList.add("om-hidden"),a&&a.classList.add("om-hidden"),i.forEach(r=>r.style.display="none")):(t&&t.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 ve(){let e=S.querySelector(".om-status-dot");e&&(e.className=`om-status-dot ${n.connected?"connected":"disconnected"}`)}function J(){S.querySelectorAll(".om-pill-btn").forEach(e=>{let o=e.dataset.action;e.classList.toggle("active",o===n.activePanel||o==="select"&&n.selecting)})}function X(){let e=[];n.selectedElement&&e.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">${x.x}</button></span>`),n.screenshot&&e.push(`<span class="om-prompt-chip">Screenshot <button class="om-prompt-chip-x" data-action="clear-screenshot">${x.x}</button></span>`),n.attachments.length&&e.push(`<span class="om-prompt-chip">${n.attachments.length} image${n.attachments.length>1?"s":""}</span>`),n.groundedFiles.length&&e.push(`<span class="om-prompt-chip">${n.groundedFiles.length} files grounded</span>`),Ge.innerHTML=e.join("")}function O(e){n.panelOpen=!0,n.activePanel=e,Se.classList.remove("om-hidden");let o=S.querySelector(".om-panel-title");o&&(o.textContent=e==="settings"?"Settings":"Chat"),E(),J()}function se(){n.panelOpen=!1,n.activePanel="",Se.classList.add("om-hidden"),J()}function be(e){n.panelOpen&&n.activePanel===e?se():O(e)}function E(){n.activePanel==="settings"?A.innerHTML=ht():n.activePanel==="chat"&&(A.innerHTML=ft(),F()),lt()}function ht(){let e=Object.entries(j).map(([b,u])=>{let h=n.configuredProviders[b]||u.local?" \u2713":"";return`<option value="${b}" ${n.provider===b?"selected":""}>${u.name}${h}</option>`}).join(""),o=j[n.provider],s=o?o.models.map(b=>`<option value="${b.id}" ${n.model===b.id?"selected":""}>${b.name}</option>`).join(""):'<option value="">Select provider first</option>',t=o?.local||!1,a=o?.keyUrl||"",i=o?.keyPlaceholder||"Enter API key...",r=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>`:"",l=r||t?`<div class="om-status om-status-success">${x.check} ${o?.name||"Provider"} connected</div>`:"",p=n.saveStatus==="saving"?'<span class="om-spinner"></span> Saving...':n.saveStatus==="saved"?`${x.check} Saved`:"Save",c=n.saveStatus==="saving"?"om-btn om-btn-saving":n.saveStatus==="saved"?"om-btn om-btn-saved":"om-btn",y=n.saveStatus==="saving"?"disabled":"",m="";return!t&&n.provider&&(r?m=`
|
|
428
428
|
<div class="om-field">
|
|
429
429
|
<label class="om-label">API Key</label>
|
|
430
430
|
<div class="om-key-configured">
|
|
431
|
-
${
|
|
431
|
+
${x.check} <span>Key configured</span>
|
|
432
432
|
<button class="om-btn-change-key" data-action="change-key">Change</button>
|
|
433
433
|
</div>
|
|
434
434
|
<div class="om-key-change-row om-hidden" data-key-change>
|
|
435
435
|
<div class="om-key-row">
|
|
436
436
|
<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" />
|
|
437
|
-
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${
|
|
437
|
+
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${x.externalLink} Get key</button>`:""}
|
|
438
438
|
</div>
|
|
439
439
|
</div>
|
|
440
440
|
</div>`:m=`
|
|
@@ -442,7 +442,7 @@
|
|
|
442
442
|
<label class="om-label">API Key</label>
|
|
443
443
|
<div class="om-key-row">
|
|
444
444
|
<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" />
|
|
445
|
-
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${
|
|
445
|
+
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${x.externalLink} Get key</button>`:""}
|
|
446
446
|
</div>
|
|
447
447
|
${a?`<div class="om-key-hint"><a data-action="get-key" data-url="${a}">Get your ${o?.name||""} API key here</a></div>`:""}
|
|
448
448
|
</div>`),`
|
|
@@ -457,33 +457,33 @@
|
|
|
457
457
|
<select class="om-select" data-field="model"><option value="">Select Model...</option>${s}</select>
|
|
458
458
|
</div>
|
|
459
459
|
${m}
|
|
460
|
-
<button class="${c}" data-action="save-settings" ${
|
|
460
|
+
<button class="${c}" data-action="save-settings" ${y}>${p}</button>
|
|
461
461
|
${l}
|
|
462
|
-
</div>`}function ft(){if(!n.provider||!n.hasApiKey&&!
|
|
462
|
+
</div>`}function ft(){if(!n.provider||!n.hasApiKey&&!j[n.provider]?.local)return'<div class="om-status om-status-error">Configure your provider in Settings first</div>';let e=n.messages.map((t,a)=>{if(t.content.startsWith("__DIFFGROUP__")){let r=t.content.split("__"),d=r[2];return`<div class="om-diff-group-header">
|
|
463
463
|
<span>${r[3]} file changes</span>
|
|
464
464
|
<div class="om-diff-actions">
|
|
465
465
|
<button class="om-btn om-btn-sm" data-action="apply-all" data-group="${d}">Apply All</button>
|
|
466
466
|
<button class="om-btn-secondary om-btn-sm" data-action="reject-all" data-group="${d}">Reject All</button>
|
|
467
467
|
</div>
|
|
468
468
|
</div>`}if(t.content.startsWith("__DIFF__"))try{let r=JSON.parse(oe(t.content.slice(8))),d=r.type==="create"||!r.search&&r.replace,l=ne(r.search||""),p=ne(r.replace||"");return`<div class="om-diff-card" data-diff-idx="${a}">
|
|
469
|
-
<div class="om-diff-file">${
|
|
470
|
-
${r.search?`<div class="om-diff-removed">${
|
|
471
|
-
<div class="om-diff-added">${
|
|
469
|
+
<div class="om-diff-file">${R(d?"Create new file":"Edit")}: ${R(r.file)}</div>
|
|
470
|
+
${r.search?`<div class="om-diff-removed">${R(r.search.slice(0,200))}</div>`:""}
|
|
471
|
+
<div class="om-diff-added">${R((r.replace||"").slice(0,300))}</div>
|
|
472
472
|
<div class="om-diff-actions">
|
|
473
|
-
<button class="om-btn om-btn-sm" data-action="apply-diff" data-file="${
|
|
473
|
+
<button class="om-btn om-btn-sm" data-action="apply-diff" data-file="${R(r.file)}" data-search="${l}" data-replace="${p}">Apply</button>
|
|
474
474
|
<button class="om-btn-secondary om-btn-sm" data-action="reject-diff" data-idx="${a}">Reject</button>
|
|
475
475
|
</div>
|
|
476
|
-
</div>`}catch{return'<div class="om-msg om-msg-system">Malformed diff data</div>'}if(t.content.startsWith("Applied change to ")){let r=t.content.replace("Applied change to ","").replace(
|
|
477
|
-
// [FILE TRUNCATED \u2014 showing ${U} of ${D.length} chars]`),
|
|
478
|
-
// [FILE TRUNCATED \u2014 showing ${Y} of ${
|
|
479
|
-
// [FILE TRUNCATED \u2014 showing ${le} of ${Z.length} chars]`),
|
|
480
|
-
All network requests (${p.length}):`);for(let c of p.slice(-30)){let
|
|
476
|
+
</div>`}catch{return'<div class="om-msg om-msg-system">Malformed diff data</div>'}if(t.content.startsWith("Applied change to ")){let r=t.content.replace("Applied change to ","").replace(/ \(fuzzy match.*?\)/g,"").replace(". Refresh the page to see the update.","");return`<div class="om-msg om-msg-system">${R(t.content)} <button class="om-undo-btn" data-action="undo-diff" data-file="${R(r)}">Undo</button></div>`}let i=t.role==="user"||t.role==="assistant"?`<button class="om-copy-btn" data-action="copy-msg" data-idx="${a}" title="Copy">${x.copy}</button>`:"";return t.role==="assistant"?`<div class="om-msg om-msg-assistant">${St(t.content)}${i}</div>`:`<div class="om-msg om-msg-${t.role}">${R(t.content)}${i}</div>`}).join(""),o=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>':""}${e}${o}</div>`}function F(){requestAnimationFrame(()=>{let e=A.querySelector(".om-chat-messages");e&&(e.scrollTop=e.scrollHeight)})}async function yt(){let o=A.querySelector('[data-field="apiKey"]')?.value||"";if(!n.provider){n.saveStatus="error",te(),setTimeout(()=>{n.saveStatus="",E()},2e3);return}if(!He()){n.saveStatus="error",te();let t=A.querySelector('[data-action="save-settings"]');t&&(t.innerHTML="Not connected - check terminal"),setTimeout(()=>{n.saveStatus="",E()},3e3);return}let s={provider:n.provider,model:n.model};o&&(s.apiKey=o),n.saveStatus="saving",te();try{let t=await Promise.race([k("config.set",s),new Promise((a,i)=>setTimeout(()=>i(new Error("Save timed out")),8e3))]);o&&n.provider&&(n.configuredProviders[n.provider]=!0),n.hasApiKey=!!(o||n.configuredProviders[n.provider]),n.saveStatus="saved",te(),setTimeout(()=>{n.saveStatus="",n.activePanel==="settings"&&O("chat")},1200)}catch(t){n.saveStatus="error";let a=A.querySelector('[data-action="save-settings"]'),i=(t?.message||"").includes("timeout")?"Connection timeout - is the CLI running?":(t?.message||"").includes("connected")?"Not connected to OpenMagic server":`Save failed: ${t?.message||"Unknown error"}`;a&&(a.innerHTML=i,a.className="om-btn",a.disabled=!1),setTimeout(()=>{n.saveStatus="",E()},4e3)}}function te(){let e=A.querySelector('[data-action="save-settings"]');e&&(n.saveStatus==="saving"?(e.innerHTML='<span class="om-spinner"></span> Saving...',e.className="om-btn om-btn-saving",e.disabled=!0):n.saveStatus==="saved"?(e.innerHTML=`${x.check} Saved`,e.className="om-btn om-btn-saved",e.disabled=!1):n.saveStatus==="error"?(e.innerHTML="Save failed - try again",e.className="om-btn",e.disabled=!1):(e.innerHTML="Save",e.className="om-btn",e.disabled=!1))}async function we(){let e=q.value.trim();if(!e||n.streaming)return;if(!n.provider||!n.hasApiKey&&!j[n.provider]?.local){O("settings");return}n.messages.push({role:"user",content:e}),n.streaming=!0,n.streamContent="",q.value="",O("chat");let o=Be(n.selectedElement,n.screenshot);o.pageUrl=window.location.href,o.pageTitle=document.title,n.attachments.length>0&&(o.screenshot||(o.screenshot=n.attachments[0]),o.attachments=[...n.attachments]);let s=5,t=32e3,a=/\.(?:[cm]?[jt]sx?|svelte|vue|astro|html?|css|scss|less|php|py)$/i,i=A.querySelector(".om-msg-assistant:last-child");i&&(i.innerHTML='<span class="om-spinner"></span> Reading project files...');try{let l=await k("fs.list",{});l?.payload?.projectTree&&(o.projectTree=l.payload.projectTree);let c=(l?.payload?.files||[]).filter(g=>g.type==="file"&&a.test(g.path)),y=[e];if(n.selectedElement&&(n.selectedElement.id&&y.push(n.selectedElement.id),n.selectedElement.className&&y.push(n.selectedElement.className),n.selectedElement.textContent&&y.push(n.selectedElement.textContent.slice(0,100)),n.selectedElement.componentHint&&y.push(n.selectedElement.componentHint),n.selectedElement.ancestry))for(let g of n.selectedElement.ancestry)y.push(g);let m=y.filter(Boolean).join(" ").toLowerCase().split(/[^a-z0-9_-]+/).filter(g=>g.length>=2&&!["the","to","in","of","and","div","span","class","style"].includes(g)),u=window.location.pathname.split("/").filter(g=>g.length>1&&!/^\d+$/.test(g)),f=c.map(g=>{let v=0,H=g.path.toLowerCase();for(let N of u)H.includes(N.toLowerCase())&&(v+=15);if(n.selectedElement?.componentHint){let N=n.selectedElement.componentHint.toLowerCase();H.includes(N)&&(v+=12)}for(let N of m)H.includes(N)&&(v+=5);return/(component|page|route|layout|template|view)/.test(H)&&(v+=3),/page\.[jt]sx?$|layout\.[jt]sx?$|\+page\.svelte$/.test(H)&&(v+=5),{...g,score:v}}).sort((g,v)=>v.score-g.score),h=[],M=new Set,w=0;for(let g of f.slice(0,s)){if(g.score<=0||w>=t)break;try{let v=n.roots[0]||"",H=v?`${v}/${g.path}`:g.path,N=await k("fs.read",{path:H}),D=String(N?.payload?.content||"");if(!D)continue;let U=Math.min(8e3,t-w),re=D.slice(0,U);D.length>U&&(re+=`
|
|
477
|
+
// [FILE TRUNCATED \u2014 showing ${U} of ${D.length} chars]`),h.push({path:g.path,content:re}),M.add(g.path),w+=re.length;let Ve=g.path.replace(/\.[^.]+$/,""),Xe=[".module.css",".module.scss",".css",".scss",".styles.ts"];for(let ie of Xe){let L=Ve+ie;if(M.has(L)||w>=t)continue;if(c.find(K=>K.path===L)){try{let K=await k("fs.read",{path:v?`${v}/${L}`:L}),P=String(K?.payload?.content||"");if(P){let Y=Math.min(4e3,t-w),I=P.slice(0,Y);P.length>Y&&(I+=`
|
|
478
|
+
// [FILE TRUNCATED \u2014 showing ${Y} of ${P.length} chars]`),h.push({path:L,content:I}),M.add(L),w+=I.length}}catch{}break}}let Je=D.matchAll(/(?:import|from)\s+['"]\.?\.\/([\w/.-]+)['"]/g);for(let ie of Je){if(w>=t)break;let L=ie[1],z=g.path.replace(/\/[^/]+$/,""),K=[`${z}/${L}`,`${z}/${L}.tsx`,`${z}/${L}.ts`,`${z}/${L}.jsx`,`${z}/${L}.js`,`${z}/${L}/index.tsx`,`${z}/${L}/index.ts`];for(let P of K){if(M.has(P))break;if(c.find(I=>I.path===P)){try{let I=await k("fs.read",{path:v?`${v}/${P}`:P}),Z=String(I?.payload?.content||"");if(Z){let le=Math.min(8e3,t-w),ce=Z.slice(0,le);Z.length>le&&(ce+=`
|
|
479
|
+
// [FILE TRUNCATED \u2014 showing ${le} of ${Z.length} chars]`),h.push({path:P,content:ce}),M.add(P),w+=ce.length}}catch{}break}}}}catch{}}if(w<t)try{let g=n.roots[0]||"",v=await k("fs.read",{path:g?`${g}/package.json`:"package.json"}),H=String(v?.payload?.content||"");if(H)try{let N=JSON.parse(H),D={...N.dependencies,...N.devDependencies},U=JSON.stringify(D,null,2);h.push({path:"package.json (dependencies)",content:U.slice(0,2e3)})}catch{h.push({path:"package.json",content:H.slice(0,2e3)})}}catch{}if(h.length){o.files=h;let g=h.map(v=>v.path.split("/").pop()).join(", ");i&&(i.innerHTML=`<span class="om-spinner"></span> Thinking... (${h.length} files: ${g})`)}n.groundedFiles=h.map(g=>g.path)}catch{}let r=4,d=0;try{for(;d<=r;){n.streamContent="";let l=await Te("llm.chat",{provider:n.provider,model:n.model,messages:n.messages.map(m=>({role:m.role,content:m.content})),context:o},m=>{n.streamContent+=m}),p=n.streamContent||l?.content||"",c=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(c&&!l?.modifications?.length&&d<r){let m=c[1].trim();d++,n.messages.push({role:"system",content:`Reading ${m}...`}),E();try{let b=n.roots[0]||"",u=b?`${b}/${m}`:m,f,h=u,M=await k("fs.read",{path:u}).catch(()=>null);if(f=M?.payload?.content?String(M.payload.content):void 0,!f&&m!==u){let w=await k("fs.read",{path:m}).catch(()=>null);w?.payload?.content&&(f=String(w.payload.content),h=m)}if(!f){let w=m.split("/").pop()||m,g=b?`${b}/${w}`:w;if(g!==u){let v=await k("fs.read",{path:g}).catch(()=>null);v?.payload?.content&&(f=String(v.payload.content),h=g)}}if(f)o.files||(o.files=[]),o.files.push({path:m,content:f.slice(0,8e3)}),n.messages.push({role:"assistant",content:p}),n.messages.push({role:"user",content:`Here is ${m}. Now please make the edit.`});else{n.messages.push({role:"system",content:`Could not read ${m}`});break}}catch{n.messages.push({role:"system",content:`File not found: ${m}`});break}continue}let y=p;try{let m=JSON.parse(p);m.explanation&&(y=m.explanation)}catch{let m=p.match(/```(?:json)?\s*([\s\S]*?)```/);if(m)try{let b=JSON.parse(m[1]);b.explanation&&(y=b.explanation)}catch{}}if(n.messages.push({role:"assistant",content:y}),l?.modifications?.length){let m=Math.random().toString(36).slice(2),b=l.modifications.filter(u=>u.type==="edit"&&u.file&&u.search&&u.replace||u.type==="create"&&u.file&&u.content);b.length>1&&n.messages.push({role:"system",content:`__DIFFGROUP__${m}__${b.length}`});for(let u of l.modifications)if(u.type==="edit"&&u.file&&u.search&&u.replace){let f=Math.random().toString(36).slice(2),h=JSON.stringify({id:f,file:u.file,search:u.search,replace:u.replace,groupId:m});n.messages.push({role:"system",content:`__DIFF__${ne(h)}`})}else if(u.type==="create"&&u.file&&u.content){let f=Math.random().toString(36).slice(2),h=JSON.stringify({id:f,file:u.file,search:"",replace:u.content,type:"create",groupId:m});n.messages.push({role:"system",content:`__DIFF__${ne(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(l){n.messages.push({role:"system",content:`Error: ${l.message}`})}n.streaming=!1,n.streamContent="",n.attachments=[],$e(),E(),F()}function bt(){let e=window.performance,o=e.getEntriesByType("navigation")[0],s=e.getEntriesByType("paint"),t=e.getEntriesByType("resource").slice(-20),a=fe(),i=ye(),r=[];r.push("--- Network & Performance Capture ---"),o&&(r.push(`Page load: ${Math.round(o.loadEventEnd-o.startTime)}ms`),r.push(`DOM ready: ${Math.round(o.domContentLoadedEventEnd-o.startTime)}ms`),r.push(`TTFB: ${Math.round(o.responseStart-o.startTime)}ms`));let d=s.find(l=>l.name==="first-contentful-paint");if(d&&r.push(`FCP: ${Math.round(d.startTime)}ms`),t.length){let l=t.filter(c=>c.initiatorType==="fetch"||c.initiatorType==="xmlhttprequest"),p=l.length>0?l:t;r.push(`
|
|
480
|
+
All network requests (${p.length}):`);for(let c of p.slice(-30)){let y=c.name.length>80?"..."+c.name.slice(-77):c.name,m=c.responseStatus||"";r.push(` ${Math.round(c.duration)}ms ${m?`[${m}]`:""} ${y}`)}}if(a.length){r.push(`
|
|
481
481
|
Fetch/XHR requests (${a.length}):`);for(let l of a.slice(-20))r.push(` ${l.method} ${l.url.slice(0,80)} \u2192 ${l.status||"pending"} (${l.duration||"?"}ms)`)}if(i.length){let l=i.filter(c=>c.level==="error"),p=i.filter(c=>c.level==="warn");l.length&&r.push(`
|
|
482
482
|
Console errors: ${l.length}`),p.length&&r.push(`Console warnings: ${p.length}`)}if(t.length>5){let l=[...t].sort((p,c)=>c.duration-p.duration).slice(0,5);r.push(`
|
|
483
483
|
Slowest resources:`);for(let p of l)r.push(` ${Math.round(p.duration)}ms \u2014 ${p.name.split("/").pop()?.slice(0,60)}`)}n.messages.push({role:"system",content:r.join(`
|
|
484
|
-
`)})
|
|
484
|
+
`)}),E(),F(),X()}function xt(){let e=S.querySelector(".om-file-input");e&&e.click()}function xe(e){if(e)for(let o=0;o<e.length&&n.attachments.length<5;o++){let s=e[o];if(!s.type.startsWith("image/")||s.size>10*1024*1024)continue;let t=new FileReader;t.onload=()=>{typeof t.result=="string"&&(n.attachments.push(t.result),$e())},t.readAsDataURL(s)}}function $e(){let e=S.querySelector(".om-prompt-attachments");if(e){if(!n.attachments.length){e.innerHTML="",e.classList.add("om-hidden");return}e.classList.remove("om-hidden"),e.innerHTML=n.attachments.map((o,s)=>`<div class="om-attachment-thumb">
|
|
485
485
|
<img src="${o}" alt="attachment" />
|
|
486
|
-
<button class="om-attachment-remove" data-action="remove-attachment" data-idx="${s}">${
|
|
487
|
-
</div>`).join("")}}var W=null,V=null;function vt(){n.selecting?ke():ae()}function ae(){n.selecting=!0,document.body.style.cursor="crosshair",J(),V=o=>{let s=o.target;if(s.closest("openmagic-toolbar")||s.dataset?.openmagic)return;let t=s.getBoundingClientRect();Ne({x:t.x,y:t.y,width:t.width,height:t.height})},W=o=>{o.preventDefault(),o.stopPropagation();let s=o.target;s.closest("openmagic-toolbar")||s.dataset?.openmagic||(n.selectedElement=_e(s),ke(),X(),q.focus())};let e=o=>{o.key==="Escape"&&ke()};document.addEventListener("mousemove",V,!0),document.addEventListener("click",W,!0),document.addEventListener("keydown",e,!0),ae._escHandler=e}function ke(){n.selecting=!1,document.body.style.cursor="",
|
|
488
|
-
`),s=
|
|
486
|
+
<button class="om-attachment-remove" data-action="remove-attachment" data-idx="${s}">${x.x}</button>
|
|
487
|
+
</div>`).join("")}}var W=null,V=null;function vt(){n.selecting?ke():ae()}function ae(){n.selecting=!0,document.body.style.cursor="crosshair",J(),V=o=>{let s=o.target;if(s.closest("openmagic-toolbar")||s.dataset?.openmagic)return;let t=s.getBoundingClientRect();Ne({x:t.x,y:t.y,width:t.width,height:t.height})},W=o=>{o.preventDefault(),o.stopPropagation();let s=o.target;s.closest("openmagic-toolbar")||s.dataset?.openmagic||(n.selectedElement=_e(s),ke(),X(),q.focus())};let e=o=>{o.key==="Escape"&&ke()};document.addEventListener("mousemove",V,!0),document.addEventListener("click",W,!0),document.addEventListener("keydown",e,!0),ae._escHandler=e}function ke(){n.selecting=!1,document.body.style.cursor="",Re(),V&&(document.removeEventListener("mousemove",V,!0),V=null),W&&(document.removeEventListener("click",W,!0),W=null);let e=ae._escHandler;e&&(document.removeEventListener("keydown",e,!0),ae._escHandler=null),J()}async function wt(){let e;try{let t=n.selectedElement?.cssSelector?.trim();t&&(e=document.querySelector(t)||void 0)}catch{}let o=await Ae(e||void 0);o.data&&o.data.length>5e3?(n.screenshot=o.data,X(),q.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."}),O("chat"),E())}function kt(){let e=!1,o=0,s=0,t=0,a=0;$.addEventListener("mousedown",i=>{let r=i.target;if(r.closest("[data-action]")||!r.closest(".om-grab")&&!r.closest(".om-pill-brand"))return;e=!0,o=i.clientX,s=i.clientY;let d=$.getBoundingClientRect();t=d.left,a=d.top,i.preventDefault()}),document.addEventListener("mousemove",i=>{e&&($.style.left=t+i.clientX-o+"px",$.style.top=a+i.clientY-s+"px",$.style.right="auto",$.style.bottom="auto")}),document.addEventListener("mouseup",()=>{if(e){e=!1;try{localStorage.setItem("__om_pos__",JSON.stringify({left:$.style.left,top:$.style.top}))}catch{}}})}function R(e){let o=document.createElement("div");return o.textContent=e,o.innerHTML}function St(e){let o=e.replace(/\\n/g,`
|
|
488
|
+
`),s=R(o);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,"• $1"),s=s.replace(/\n/g,"<br>"),s}function $t(){fetch("https://registry.npmjs.org/openmagic/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)}).then(e=>e.ok?e.json():null).then(e=>{if(!e?.version)return;let o=e.version.split(".").map(Number),s=Ke.split(".").map(Number);for(let t=0;t<3;t++){if((o[t]||0)>(s[t]||0)){n.updateAvailable=!0,n.latestVersion=e.version,Et();return}if((o[t]||0)<(s[t]||0))return}}).catch(()=>{})}function Et(){if(S.querySelector(".om-update-dot"))return;let o=document.createElement("span");o.className="om-update-dot",o.title=`v${n.latestVersion} available`,o.addEventListener("click",()=>O("settings"));let s=S.querySelector(".om-toolbar-header");s&&s.appendChild(o)}typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",je):je());})();
|
|
489
489
|
//# sourceMappingURL=index.global.js.map
|