openmagic 0.43.1 → 0.43.2
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/README.md +1 -0
- package/dist/cli.js +106 -18
- package/dist/cli.js.map +1 -1
- package/dist/toolbar/index.global.js +34 -34
- package/dist/toolbar/index.global.js.map +1 -1
- package/package.json +5 -3
|
@@ -393,25 +393,25 @@
|
|
|
393
393
|
.om-msg:hover .om-copy-btn { opacity: 1; }
|
|
394
394
|
.om-copy-btn:hover { color: #ccc; background: rgba(0,0,0,0.5); }
|
|
395
395
|
.om-msg { position: relative; }
|
|
396
|
-
`;var X=null,
|
|
396
|
+
`;var X=null,K=new Map,le=[],se=[],ie=!1,Fe=!1,Me=null,Ee=0;function Le(){return Math.random().toString(36).slice(2)+Date.now().toString(36)}function Ce(t,e){return Fe=!0,new Promise((s,n)=>{let a=!1,i=setTimeout(()=>{a||(a=!0,n(new Error("Handshake timeout")),X?.close())},1e4);try{let r=window.location.hostname||"127.0.0.1",u=window.location.protocol==="https:"?"wss:":"ws:";X=new WebSocket(`${u}//${r}:${t}/__openmagic__/ws`),X.onopen=()=>{let d=Le();X.send(JSON.stringify({id:d,type:"handshake",payload:{token:e}})),K.set(d,p=>{if(p.type==="handshake.ok"){clearTimeout(i),ie=!0,Ee=0;for(let c of se)X?.send(c.data);se=[],a||(a=!0,s())}else p.type==="error"&&(clearTimeout(i),a||(a=!0,n(new Error(p.payload?.message||"Handshake failed"))))})},X.onmessage=d=>{try{let p=JSON.parse(d.data);p.id&&K.has(p.id)&&(K.get(p.id)(p),(p.type==="llm.done"||p.type==="llm.error"||!p.type.startsWith("llm."))&&K.delete(p.id));for(let c of le)c(p)}catch{}},X.onclose=()=>{let d=ie;if(ie=!1,K.forEach((p,c)=>{p({type:"error",id:c,payload:{message:"Connection lost"}})}),K.clear(),!d&&!a){clearTimeout(i),a=!0,n(new Error("WebSocket closed before handshake"));return}if(d&&Fe&&!Me){let p=Math.min(2e3*Math.pow(1.5,Ee),3e4);Ee++,Me=setTimeout(()=>{Me=null,Ce(t,e).then(()=>{for(let c of le)c({type:"reconnected",payload:{}})}).catch(()=>{})},p)}},X.onerror=()=>{!ie&&!a&&(clearTimeout(i),a=!0,n(new Error("WebSocket connection failed")))}}catch(r){clearTimeout(i),a||(a=!0,n(r))}})}function Be(t){let e=JSON.stringify(t);X&&X.readyState===WebSocket.OPEN&&ie?X.send(e):se.push({id:t.id,type:t.type,data:e})}function N(t,e){return new Promise((s,n)=>{let a=Le(),i=setTimeout(()=>{K.delete(a),se=se.filter(r=>r.id!==a),n(new Error("Request timeout"))},3e4);K.set(a,r=>{clearTimeout(i),r.type==="error"?n(new Error(r.payload?.message||"Unknown error")):s(r)}),Be({id:a,type:t,payload:e})})}function We(t,e,s){return new Promise((n,a)=>{let i=Le(),r=3e5,u=setTimeout(d,r);function d(){K.delete(i),se=se.filter(c=>c.id!==i),a(new Error("Stream timeout"))}function p(){clearTimeout(u),u=setTimeout(d,r)}K.set(i,c=>{c.type==="llm.chunk"?(p(),s(c.payload?.delta||"")):c.type==="llm.done"?(clearTimeout(u),K.delete(i),n(c.payload)):(c.type==="llm.error"||c.type==="error")&&(clearTimeout(u),K.delete(i),a(new Error(c.payload?.message||"Stream error")))}),Be({id:i,type:t,payload:e})})}function Ue(t){return le.push(t),()=>{le=le.filter(e=>e!==t)}}function Te(){return ie}var Ke=["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 Ge(t){let e=window.getComputedStyle(t),s={};for(let S of Ke)s[S]=e.getPropertyValue(S);let n=t.getBoundingClientRect(),a={};if(t.parentElement&&t.parentElement!==document.body){let S=window.getComputedStyle(t.parentElement);for(let L of Ke)a[L]=S.getPropertyValue(L)}let i=[];if(t.parentElement){let S=Array.from(t.parentElement.children),L=S.indexOf(t),w=Math.max(0,L-3),T=Math.min(S.length,L+4);w>0&&i.push(`... ${w} elements before ...`);for(let P=w;P<T;P++){let H=S[P],O=H.tagName.toLowerCase(),I=(H.className||"").toString().slice(0,60);H===t?i.push(`[SELECTED] <${O} class="${I}">`):i.push(`<${O} class="${I}">`)}T<S.length&&i.push(`... ${S.length-T} elements after ...`)}let r=[],u=Array.from(t.children).slice(0,12);for(let S=0;S<u.length;S++){let L=u[S],w=L.getBoundingClientRect(),T=window.getComputedStyle(L),P=null;if(S<u.length-1){let H=u[S+1].getBoundingClientRect();P={vertical:Math.round(H.top-w.bottom),horizontal:Math.round(Math.abs(H.left-w.right))}}r.push({tag:L.tagName.toLowerCase(),className:(L.className||"").toString().slice(0,80),rect:{x:Math.round(w.x),y:Math.round(w.y),width:Math.round(w.width),height:Math.round(w.height)},gapToNext:P,margin:T.margin,padding:T.padding})}let d=bt(t),p=vt(t,d),c={};for(let S of Array.from(t.attributes))(S.name.startsWith("aria-")||S.name==="role"||S.name==="tabindex")&&(c[S.name]=S.value);let x=[];for(let S of Array.from(t.attributes))S.name.startsWith("on")&&x.push(S.name);let M=xt(t),l=document.documentElement,f=window.getComputedStyle(l),g={};for(let S of Object.keys(l.dataset))g[S]=l.dataset[S]||"";let h={darkMode:l.classList.contains("dark")||l.dataset.theme==="dark"||l.dataset.mode==="dark"||window.matchMedia("(prefers-color-scheme: dark)").matches,colorScheme:f.colorScheme||"",htmlDataAttributes:g},m={};try{for(let L of d){let w=L.matchAll(/var\((--[a-zA-Z0-9_-]+)/g);for(let T of w){let P=T[1];m[P]||(m[P]=e.getPropertyValue(P).trim()||"(unset)")}}let S=(t.getAttribute("style")||"").matchAll(/var\((--[a-zA-Z0-9_-]+)/g);for(let L of S)m[L[1]]||(m[L[1]]=e.getPropertyValue(L[1]).trim()||"(unset)")}catch{}let v=e.zIndex,$=e.position!=="static"&&v!=="auto"||e.opacity!=="1"||e.transform!=="none"||e.filter!=="none",j=t.parentElement?window.getComputedStyle(t.parentElement).zIndex:"auto",D={zIndex:v,createsContext:$,parentZIndex:j},ne=n.top<window.innerHeight&&n.bottom>0&&n.left<window.innerWidth&&n.right>0,y=!0;try{y=t.checkVisibility?.({checkOpacity:!0,checkVisibilityCSS:!0})??!0}catch{y=e.display!=="none"&&e.visibility!=="hidden"}let k=t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth,E={isVisible:y,isInViewport:ne,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft,isScrollable:k},A=[],C=["(max-width: 639px)","(min-width: 640px)","(min-width: 768px)","(min-width: 1024px)","(min-width: 1280px)","(min-width: 1536px)","(prefers-color-scheme: dark)","(prefers-reduced-motion: reduce)"];for(let S of C)try{window.matchMedia(S).matches&&A.push(S)}catch{}let W="",U="";try{W=window.getComputedStyle(t,"::before").content||""}catch{}try{U=window.getComputedStyle(t,"::after").content||""}catch{}let V={before:W,after:U},re=null;return(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLButtonElement)&&(re={disabled:t.disabled||!1,readOnly:t.readOnly||!1,invalid:t.checkValidity?!t.checkValidity():!1}),{tagName:t.tagName.toLowerCase(),id:t.id||"",className:t.className||"",textContent:(t.textContent||"").trim().slice(0,200),outerHTML:ft(t),cssSelector:gt(t),xpath:yt(t),computedStyles:s,ancestry:ut(t),componentHint:ht(t),rect:{x:n.x,y:n.y,width:n.width,height:n.height},parentStyles:a,siblings:i,childrenLayout:r,matchedCssRules:d,resolvedClasses:p,viewport:{width:window.innerWidth,height:window.innerHeight},ariaAttributes:c,eventHandlers:x,reactProps:M,themeState:h,cssVariables:m,stackingContext:D,visibilityState:E,activeBreakpoints:A,pseudoElements:V,formState:re}}function ut(t,e=5){let s=[],n=t.parentElement;for(;n&&n!==document.body&&s.length<e;){let a=n.tagName.toLowerCase(),i=(typeof n.className=="string"?n.className:"").split(/\s+/).filter(r=>r.length>1&&!r.startsWith("_")).slice(0,3).join(".");s.push(i?`${a}.${i}`:a),n=n.parentElement}return s}function ht(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 n=Object.keys(e);for(let a of n)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 ft(t){let e=t.cloneNode(!0);e.querySelectorAll("script, style, svg").forEach(a=>a.remove());let n=e.outerHTML;if(n.length>2e3){let a=t.tagName.toLowerCase(),i=Array.from(t.attributes).map(u=>`${u.name}="${u.value}"`).join(" "),r=Array.from(t.children).slice(0,5).map(u=>`<${u.tagName.toLowerCase()} .../>`).join(`
|
|
397
397
|
`);n=`<${a} ${i}>
|
|
398
398
|
${r}
|
|
399
399
|
${t.children.length>5?`<!-- +${t.children.length-5} more children -->`:""}
|
|
400
|
-
</${a}>`}return n}function gt(t){if(t.id)return`#${CSS.escape(t.id)}`;let e=[],s=t;for(;s&&s!==document.body;){let n=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&&(n+="."+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;n+=`:nth-of-type(${r})`}}e.unshift(n),s=s.parentElement}return e.join(" > ")}function yt(t){let e=[],s=t;for(;s&&s!==document;){if(s.nodeType===Node.ELEMENT_NODE){let n=s,a=1,i=n.previousElementSibling;for(;i;)i.tagName===n.tagName&&a++,i=i.previousElementSibling;e.unshift(`${n.tagName.toLowerCase()}[${a}]`)}s=s.parentNode}return"/"+e.join("/")}function bt(t){let e=[];try{for(let s of Array.from(document.styleSheets))try{let n=s.cssRules||s.rules;if(!n)continue;for(let a of Array.from(n))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 xt(t){try{let e=Object.keys(t);for(let s of e)if(s.startsWith("__reactFiber")||s.startsWith("__reactInternalInstance")){let n=t[s];if(!n?.memoizedProps)continue;let a=n.memoizedProps,i={},r=0;for(let[
|
|
400
|
+
</${a}>`}return n}function gt(t){if(t.id)return`#${CSS.escape(t.id)}`;let e=[],s=t;for(;s&&s!==document.body;){let n=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&&(n+="."+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;n+=`:nth-of-type(${r})`}}e.unshift(n),s=s.parentElement}return e.join(" > ")}function yt(t){let e=[],s=t;for(;s&&s!==document;){if(s.nodeType===Node.ELEMENT_NODE){let n=s,a=1,i=n.previousElementSibling;for(;i;)i.tagName===n.tagName&&a++,i=i.previousElementSibling;e.unshift(`${n.tagName.toLowerCase()}[${a}]`)}s=s.parentNode}return"/"+e.join("/")}function bt(t){let e=[];try{for(let s of Array.from(document.styleSheets))try{let n=s.cssRules||s.rules;if(!n)continue;for(let a of Array.from(n))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 xt(t){try{let e=Object.keys(t);for(let s of e)if(s.startsWith("__reactFiber")||s.startsWith("__reactInternalInstance")){let n=t[s];if(!n?.memoizedProps)continue;let a=n.memoizedProps,i={},r=0;for(let[u,d]of Object.entries(a)){if(r>=10)break;if(u==="children")continue;let p=typeof d;p==="string"||p==="number"||p==="boolean"||d===null?(i[u]=d,r++):p==="function"?(i[u]="[function]",r++):Array.isArray(d)&&(i[u]=`[Array(${d.length})]`,r++)}return Object.keys(i).length>0?i:null}}catch{}return null}function vt(t,e){let s=[],n=(t.className||"").toString().trim().split(/\s+/).filter(Boolean);for(let a of n){let i=CSS.escape(a);for(let r of e)if(r.includes(`.${i}`)&&r.length<200){s.push({className:a,css:r});break}if(s.length>=20)break}return s}var G=null;function Ve(t){G||(G=document.createElement("div"),G.style.cssText=`
|
|
401
401
|
position: fixed;
|
|
402
402
|
pointer-events: none;
|
|
403
403
|
z-index: 2147483646;
|
|
404
404
|
border: 2px solid #6c5ce7;
|
|
405
405
|
background: rgba(108, 92, 231, 0.1);
|
|
406
406
|
transition: all 0.1s ease;
|
|
407
|
-
`,
|
|
407
|
+
`,G.dataset.openmagic="highlight",document.body.appendChild(G)),G.style.left=`${t.x}px`,G.style.top=`${t.y}px`,G.style.width=`${t.width}px`,G.style.height=`${t.height}px`,G.style.display="block"}function Xe(){G&&(G.style.display="none")}async function Je(t){try{let e=t||document.body,s=await wt(e);if(s)return{data:s}}catch{}try{let e=await kt(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 wt(t){let e=t.getBoundingClientRect(),s=Math.min(e.width||window.innerWidth,1920),n=Math.min(e.height||window.innerHeight,1080),a=Ze(t,0,4);if(!a)return null;let i=`
|
|
408
408
|
<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${n}">
|
|
409
409
|
<foreignObject width="100%" height="100%">
|
|
410
410
|
<div xmlns="http://www.w3.org/1999/xhtml" style="width:${s}px;height:${n}px;overflow:hidden;">
|
|
411
411
|
${a.outerHTML}
|
|
412
412
|
</div>
|
|
413
413
|
</foreignObject>
|
|
414
|
-
</svg>`,r=new Blob([i],{type:"image/svg+xml;charset=utf-8"}),m=URL.createObjectURL(r);return new Promise(c=>{let u=new Image,p=document.createElement("canvas"),x=Math.min(window.devicePixelRatio||1,2);p.width=s*x,p.height=n*x,u.onload=()=>{URL.revokeObjectURL(m);let S=p.getContext("2d");if(!S){c(null);return}S.scale(x,x),S.drawImage(u,0,0);try{if(p.width>1280){let f=1280/p.width,g=document.createElement("canvas");g.width=1280,g.height=Math.round(p.height*f);let h=g.getContext("2d");if(h){h.drawImage(p,0,0,g.width,g.height),c(g.toDataURL("image/jpeg",.8));return}}c(p.toDataURL("image/jpeg",.8))}catch{c(null)}},u.onerror=()=>{URL.revokeObjectURL(m),c(null)},setTimeout(()=>{URL.revokeObjectURL(m),c(null)},5e3),u.src=m})}async function kt(t){let e=t||document.documentElement,s=e.getBoundingClientRect(),n=document.createElement("canvas");n.width=400,n.height=300;let a=n.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),n.toDataURL("image/png")):null}function Ze(t,e,s){if(e>s)return null;try{let n=t.cloneNode(!1);if(n.tagName==="SCRIPT"||n.tagName==="STYLE"||n.tagName==="SVG"||n.tagName==="CANVAS"||n.tagName==="VIDEO"||n.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 m of i){let c=a.getPropertyValue(m);c&&c!=="normal"&&c!=="none"&&c!=="auto"&&c!=="0px"&&(r+=`${m}:${c};`)}n.setAttribute("style",r);for(let m=0;m<t.children.length&&m<20;m++){let c=Ze(t.children[m],e+1,s);c&&n.appendChild(c)}return n}catch{return null}}var he=[];var Ye=!1;function et(){if(Ye)return;Ye=!0;let t=window.fetch;window.fetch=async function(...n){let a=new Request(...n),i={method:a.method,url:a.url,timestamp:Date.now()};try{let r=await t.apply(this,n);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 e=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(n,a,...i){return this.__om_method=n,this.__om_url=a,this.__om_start=Date.now(),e.apply(this,[n,a,...i])},XMLHttpRequest.prototype.send=function(...n){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,n)}}function He(t){t.url.includes("__openmagic__")||(he.push(t),he.length>50&&he.shift())}function ge(){return[...he]}var fe=[],$t=100,Qe=!1;function tt(){if(Qe)return;Qe=!0;let t=["log","warn","error","info","debug"];for(let e of t){let s=console[e];console[e]=function(...n){fe.push({level:e,args:n.map(a=>{try{return typeof a=="object"?JSON.stringify(a).slice(0,500):String(a)}catch{return String(a)}}),timestamp:Date.now()}),fe.length>$t&&fe.shift(),s.apply(console,n)}}}function ye(){return[...fe]}function nt(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:ge().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 _={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>'},Q={"claude-code":{name:"Claude Code (CLI)",keyPlaceholder:"not required",local:!0,models:[{id:"claude-code",name:"Claude Code"}]},"codex-cli":{name:"Codex CLI",keyPlaceholder:"not required",local:!0,models:[{id:"codex-cli",name:"Codex CLI"}]},"gemini-cli":{name:"Gemini CLI",keyPlaceholder:"not required",local:!0,models:[{id:"gemini-cli",name:"Gemini CLI"}]},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 xe(t){let e=new TextEncoder().encode(t),s="";for(let n=0;n<e.length;n+=32768)s+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(s)}function se(t){let e=atob(t),s=new Uint8Array(e.length);for(let n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return new TextDecoder().decode(s)}var Oe="0.43.1",o={connected:!1,panelOpen:!1,activePanel:"",selecting:!1,selectedElement:null,screenshot:null,messages:[],streaming:!1,streamContent:"",provider:"",model:"",hasApiKey:!1,configuredProviders:{},detectedClis:[],roots:[],updateAvailable:!1,latestVersion:"",saveStatus:"",networkCapture:!1,attachments:[],groundedFiles:[],minimized:!1},A,B,ee,lt,Ie,J;function ct(){try{let t=o.messages;t.length>50&&(t=[...t.slice(0,5),...t.slice(-45)]);let e=t.map(s=>{if(s.content.startsWith("__DIFF__")&&s.content.length>500)try{let n=JSON.parse(se(s.content.slice(8)));return{...s,content:`Applied ${n.type||"edit"} to ${n.file||"file"}`}}catch{return s}return s});sessionStorage.setItem("__om_state__",JSON.stringify({messages:e,provider:o.provider,model:o.model,panelOpen:o.panelOpen,activePanel:o.activePanel}))}catch{}}function St(){try{let t=JSON.parse(sessionStorage.getItem("__om_state__")||"{}");t.messages?.length&&(o.messages=t.messages),t.provider&&(o.provider=t.provider),t.model&&(o.model=t.model),t.panelOpen&&(o.panelOpen=t.panelOpen,o.activePanel=t.activePanel||"")}catch{}}function ot(){if(document.querySelector("openmagic-toolbar"))return;St();let t=document.createElement("openmagic-toolbar");t.dataset.openmagic="true",A=t.attachShadow({mode:"closed"});let e=document.createElement("style");e.textContent=ze,A.appendChild(e);let s=document.createElement("div");A.appendChild(s),s.innerHTML=Mt(),B=s.querySelector(".om-toolbar"),ee=s.querySelector(".om-prompt-input"),lt=s.querySelector(".om-prompt-context"),Ie=s.querySelector(".om-panel"),J=s.querySelector(".om-panel-body"),document.body.appendChild(t),Et(s),It();try{let r=JSON.parse(localStorage.getItem("__om_pos__")||"");r?.left&&r?.top&&(B.style.left=r.left,B.style.top=r.top,B.style.right="auto",B.style.bottom="auto")}catch{}et(),tt(),qt();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&&Ce(i,a).then(()=>(o.connected=!0,ve(),N("config.get"))).then(r=>{o.detectedClis=r.payload?.detectedClis||[];let m=r.payload?.provider||"",c=r.payload?.model||"";o.provider=o.provider||m,o.model=o.model||c,o.configuredProviders=r.payload?.apiKeys||{};for(let p of o.detectedClis)p.installed&&p.authenticated&&(o.configuredProviders[p.id]=!0);let u=Q[o.provider];o.hasApiKey=!!(o.configuredProviders[o.provider]||u?.local),o.roots=r.payload?.roots||[],o.panelOpen&&o.activePanel?te(o.activePanel):(!o.provider||!o.hasApiKey&&!Object.values(o.configuredProviders).some(Boolean)&&!u?.local)&&te("settings"),ue(),pt()}).catch(()=>{o.connected=!1,ve()})}function Mt(){return`
|
|
414
|
+
</svg>`,r=new Blob([i],{type:"image/svg+xml;charset=utf-8"}),u=URL.createObjectURL(r);return new Promise(d=>{let p=new Image,c=document.createElement("canvas"),x=Math.min(window.devicePixelRatio||1,2);c.width=s*x,c.height=n*x,p.onload=()=>{URL.revokeObjectURL(u);let M=c.getContext("2d");if(!M){d(null);return}M.scale(x,x),M.drawImage(p,0,0);try{if(c.width>1280){let f=1280/c.width,g=document.createElement("canvas");g.width=1280,g.height=Math.round(c.height*f);let h=g.getContext("2d");if(h){h.drawImage(c,0,0,g.width,g.height),d(g.toDataURL("image/jpeg",.8));return}}d(c.toDataURL("image/jpeg",.8))}catch{d(null)}},p.onerror=()=>{URL.revokeObjectURL(u),d(null)},setTimeout(()=>{URL.revokeObjectURL(u),d(null)},5e3),p.src=u})}async function kt(t){let e=t||document.documentElement,s=e.getBoundingClientRect(),n=document.createElement("canvas");n.width=400,n.height=300;let a=n.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),n.toDataURL("image/png")):null}function Ze(t,e,s){if(e>s)return null;try{let n=t.cloneNode(!1);if(n.tagName==="SCRIPT"||n.tagName==="STYLE"||n.tagName==="SVG"||n.tagName==="CANVAS"||n.tagName==="VIDEO"||n.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 u of i){let d=a.getPropertyValue(u);d&&d!=="normal"&&d!=="none"&&d!=="auto"&&d!=="0px"&&(r+=`${u}:${d};`)}n.setAttribute("style",r);for(let u=0;u<t.children.length&&u<20;u++){let d=Ze(t.children[u],e+1,s);d&&n.appendChild(d)}return n}catch{return null}}var fe=[];var Ye=!1;function et(){if(Ye)return;Ye=!0;let t=window.fetch;window.fetch=async function(...n){let a=new Request(...n),i={method:a.method,url:a.url,timestamp:Date.now()};try{let r=await t.apply(this,n);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 e=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(n,a,...i){return this.__om_method=n,this.__om_url=a,this.__om_start=Date.now(),e.apply(this,[n,a,...i])},XMLHttpRequest.prototype.send=function(...n){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,n)}}function He(t){t.url.includes("__openmagic__")||(fe.push(t),fe.length>50&&fe.shift())}function ye(){return[...fe]}var ge=[],$t=100,Qe=!1;function tt(){if(Qe)return;Qe=!0;let t=["log","warn","error","info","debug"];for(let e of t){let s=console[e];console[e]=function(...n){ge.push({level:e,args:n.map(a=>{try{return typeof a=="object"?JSON.stringify(a).slice(0,500):String(a)}catch{return String(a)}}),timestamp:Date.now()}),ge.length>$t&&ge.shift(),s.apply(console,n)}}}function be(){return[...ge]}function nt(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:ye().map(s=>({method:s.method,url:s.url,status:s.status,duration:s.duration,timestamp:s.timestamp})),consoleLogs:be().map(s=>({level:s.level,args:s.args,timestamp:s.timestamp}))}}var _={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>'},Q={"claude-code":{name:"Claude Code (CLI)",keyPlaceholder:"not required",local:!0,models:[{id:"claude-code",name:"Claude Code"}]},"codex-cli":{name:"Codex CLI",keyPlaceholder:"not required",local:!0,models:[{id:"codex-cli",name:"Codex CLI"}]},"gemini-cli":{name:"Gemini CLI",keyPlaceholder:"not required",local:!0,models:[{id:"gemini-cli",name:"Gemini CLI"}]},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 ve(t){let e=new TextEncoder().encode(t),s="";for(let n=0;n<e.length;n+=32768)s+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(s)}function ae(t){let e=atob(t),s=new Uint8Array(e.length);for(let n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return new TextDecoder().decode(s)}var Oe="0.43.2",o={connected:!1,panelOpen:!1,activePanel:"",selecting:!1,selectedElement:null,screenshot:null,messages:[],streaming:!1,streamContent:"",provider:"",model:"",hasApiKey:!1,configuredProviders:{},detectedClis:[],roots:[],updateAvailable:!1,latestVersion:"",saveStatus:"",networkCapture:!1,attachments:[],groundedFiles:[],minimized:!1},R,F,ee,lt,Ie,J;function ct(){try{let t=o.messages;t.length>50&&(t=[...t.slice(0,5),...t.slice(-45)]);let e=t.map(s=>{if(s.content.startsWith("__DIFF__")&&s.content.length>500)try{let n=JSON.parse(ae(s.content.slice(8)));return{...s,content:`Pending ${n.type||"edit"} for ${n.file||"file"} was not restored after reload.`}}catch{return s}return s});sessionStorage.setItem("__om_state__",JSON.stringify({messages:e,provider:o.provider,model:o.model,panelOpen:o.panelOpen,activePanel:o.activePanel}))}catch{}}function St(){try{let t=JSON.parse(sessionStorage.getItem("__om_state__")||"{}");t.messages?.length&&(o.messages=t.messages),t.provider&&(o.provider=t.provider),t.model&&(o.model=t.model),t.panelOpen&&(o.panelOpen=t.panelOpen,o.activePanel=t.activePanel||"")}catch{}}function ot(){if(document.querySelector("openmagic-toolbar"))return;St();let t=document.createElement("openmagic-toolbar");t.dataset.openmagic="true",R=t.attachShadow({mode:"closed"});let e=document.createElement("style");e.textContent=ze,R.appendChild(e);let s=document.createElement("div");R.appendChild(s),s.innerHTML=Mt(),F=s.querySelector(".om-toolbar"),ee=s.querySelector(".om-prompt-input"),lt=s.querySelector(".om-prompt-context"),Ie=s.querySelector(".om-panel"),J=s.querySelector(".om-panel-body"),document.body.appendChild(t),Et(s),It();try{let r=JSON.parse(localStorage.getItem("__om_pos__")||"");r?.left&&r?.top&&(F.style.left=r.left,F.style.top=r.top,F.style.right="auto",F.style.bottom="auto")}catch{}et(),tt(),qt();let n=document.querySelector("script[data-openmagic-token]"),a=(typeof __OPENMAGIC_TOKEN__<"u"?__OPENMAGIC_TOKEN__:"")||n?.dataset.openmagicToken||window.__OPENMAGIC_TOKEN__,i=parseInt(window.location.port,10)||(window.location.protocol==="https:"?443:80);a&&Ce(i,a).then(()=>(o.connected=!0,we(),N("config.get"))).then(r=>{o.detectedClis=r.payload?.detectedClis||[];let u=r.payload?.provider||"",d=r.payload?.model||"";o.provider=o.provider||u,o.model=o.model||d,o.configuredProviders=r.payload?.apiKeys||{};for(let c of o.detectedClis)c.installed&&c.authenticated&&(o.configuredProviders[c.id]=!0);let p=Q[o.provider];o.hasApiKey=!!(o.configuredProviders[o.provider]||p?.local),o.roots=r.payload?.roots||[],o.panelOpen&&o.activePanel?te(o.activePanel):(!o.provider||!o.hasApiKey&&!Object.values(o.configuredProviders).some(Boolean)&&!p?.local)&&te("settings"),ue(),pt()}).catch(()=>{o.connected=!1,we()})}function Mt(){return`
|
|
415
415
|
<div class="om-toolbar">
|
|
416
416
|
<div class="om-toolbar-header">
|
|
417
417
|
<span class="om-grab">${_.grip}</span>
|
|
@@ -454,14 +454,14 @@
|
|
|
454
454
|
<button class="om-prompt-send" data-action="prompt-send">${_.send}</button>
|
|
455
455
|
<input type="file" class="om-file-input om-hidden" accept="image/*" multiple />
|
|
456
456
|
</div>
|
|
457
|
-
</div>`}function Et(t){t.addEventListener("click",n=>{let a=n.target.closest("[data-action]");if(!a)return;n.preventDefault(),n.stopPropagation();let i=a.dataset.action;it(i,a)}),t.addEventListener("change",n=>{let a=n.target,i=a.dataset.field;i&&(i==="provider"?(o.provider=a.value,o.model=Q[o.provider]?.models[0]?.id||"",o.hasApiKey=o.configuredProviders[o.provider]||Q[o.provider]?.local||!1,o.saveStatus="",
|
|
457
|
+
</div>`}function Et(t){t.addEventListener("click",n=>{let a=n.target.closest("[data-action]");if(!a)return;n.preventDefault(),n.stopPropagation();let i=a.dataset.action;it(i,a)}),t.addEventListener("change",n=>{let a=n.target,i=a.dataset.field;i&&(i==="provider"?(o.provider=a.value,o.model=Q[o.provider]?.models[0]?.id||"",o.hasApiKey=o.configuredProviders[o.provider]||Q[o.provider]?.local||!1,o.saveStatus="",B()):i==="model"?o.model=a.value:i==="quick-model"&&(o.model=a.value,ct()))}),ee.addEventListener("keydown",n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),Ne())});let e=t.querySelector(".om-file-input");e&&e.addEventListener("change",()=>{Ae(e.files),e.value=""});let s=t.querySelector(".om-prompt-row");s&&(s.addEventListener("dragover",n=>{n.preventDefault(),s.style.borderColor="rgba(108, 92, 231, 0.5)"}),s.addEventListener("dragleave",()=>{s.style.borderColor=""}),s.addEventListener("drop",n=>{n.preventDefault(),s.style.borderColor="";let a=n.dataTransfer;a?.files?.length&&Ae(a.files)}),ee.addEventListener("paste",n=>{let a=n.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 u=new DataTransfer;u.items.add(r),Ae(u.files)}}}})),Ue(n=>{n.type==="reconnected"&&(o.connected=!0,we())}),document.addEventListener("keydown",n=>{if((n.ctrlKey||n.metaKey)&&n.shiftKey&&(n.key==="O"||n.key==="o")){if(n.preventDefault(),o.minimized){o.minimized=!1,F.querySelectorAll(".om-pill-btn:not([data-action='minimize']), .om-pill-divider, .om-status-dot").forEach(r=>r.style.display="");let i=R.querySelector(".om-prompt-row");i&&i.classList.remove("om-hidden")}else o.panelOpen?ke():te("chat");return}if((n.ctrlKey||n.metaKey)&&n.shiftKey&&(n.key==="k"||n.key==="K")){n.preventDefault(),o.panelOpen||te("chat"),ee.focus();return}if((n.ctrlKey||n.metaKey)&&(n.key==="z"||n.key==="Z")&&!n.shiftKey&&R.activeElement){let a=R.querySelector('[data-action="undo-diff"]');if(a){n.preventDefault(),dt(a);return}}if((n.ctrlKey||n.metaKey)&&n.key==="."){let a=R.querySelector('[data-action="apply-all"]');if(a&&!R.querySelector(".om-apply-bar.om-hidden")){n.preventDefault(),it("apply-all",a);return}}if(n.key==="Escape"){if(o.selecting)return;o.panelOpen&&(ke(),n.preventDefault())}}),ee.addEventListener("keydown",n=>{(n.ctrlKey||n.metaKey)&&n.key==="Enter"&&(n.preventDefault(),Ne())})}function De(t){return o.roots.length>0?o.roots[0]+"/"+t:t}function Lt(t,e){let s=e.split(`
|
|
458
458
|
`),n=s.map(l=>l.trim()).filter(l=>l.length>0);if(n.length===0)return null;let a=t.split(`
|
|
459
|
-
`);for(let l=0;l<=a.length-n.length;l++){let f=!0,g=0,h=0;for(let
|
|
460
|
-
`).toLowerCase(),
|
|
461
|
-
`).toLowerCase(),h=Ct(r,g);h>
|
|
462
|
-
`&&i--,{start:a,end:i}}function Ct(t,e){if(t===e)return 1;if(!t||!e)return 0;let s=new Set,n=new Set;for(let i=0;i<=t.length-3;i++)s.add(t.slice(i,i+3));for(let i=0;i<=e.length-3;i++)n.add(e.slice(i,i+3));if(s.size===0||n.size===0)return 0;let a=0;for(let i of s)n.has(i)&&a++;return a/(s.size+n.size-a)}async function ce(t){let e=t.dataset.file,s=t.dataset.search,n=t.dataset.replace;if(!e
|
|
459
|
+
`);for(let l=0;l<=a.length-n.length;l++){let f=!0,g=0,h=0;for(let m=l;m<a.length&&h<n.length;m++){if(a[m].trim()===""){g++;continue}if(a[m].trim()!==n[h]){f=!1;break}h++,g++}if(f&&h===n.length)return Pe(t,a,l,g)}let i=s.map(l=>l.trimStart());for(let l=0;l<=a.length-i.length;l++){let f=!0;for(let g=0;g<i.length;g++)if(i[g]!==""&&a[l+g].trimStart()!==i[g].trimEnd()){f=!1;break}if(f)return Pe(t,a,l,i.length)}let r=n.join(`
|
|
460
|
+
`).toLowerCase(),u=n.length,d=0,p=-1,c=0,x=Math.max(1,Math.floor(u*.8)),M=Math.min(a.length,Math.ceil(u*1.2));for(let l=x;l<=M;l++)for(let f=0;f<=a.length-l;f++){let g=a.slice(f,f+l).map(m=>m.trim()).filter(m=>m).join(`
|
|
461
|
+
`).toLowerCase(),h=Ct(r,g);h>d&&(d=h,p=f,c=l)}return d>=.8&&p>=0?Pe(t,a,p,c):null}function Pe(t,e,s,n){let a=0;for(let r=0;r<s;r++)a+=e[r].length+1;let i=a;for(let r=s;r<s+n;r++)i+=e[r].length+1;return i>0&&i<=t.length&&t[i-1]===`
|
|
462
|
+
`&&i--,{start:a,end:i}}function Ct(t,e){if(t===e)return 1;if(!t||!e)return 0;let s=new Set,n=new Set;for(let i=0;i<=t.length-3;i++)s.add(t.slice(i,i+3));for(let i=0;i<=e.length-3;i++)n.add(e.slice(i,i+3));if(s.size===0||n.size===0)return 0;let a=0;for(let i of s)n.has(i)&&a++;return a/(s.size+n.size-a)}async function ce(t){let e=t.dataset.file,s=t.dataset.search,n=t.dataset.replace;if(!e||s===void 0||n===void 0)return{ok:!1,file:e,error:"Missing diff data"};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=ae(s),r=ae(n)}catch{return o.messages.push({role:"system",content:`Failed to decode diff data for ${e}`}),B(),{ok:!1,file:e,error:"Failed to decode diff data"}}let u=De(e),d=!1,p="";try{if(!i&&r)if((await N("fs.write",{path:u,content:r}))?.payload?.ok===!1)p=`Write failed: ${e}`,o.messages.push({role:"system",content:p});else{d=!0;let x=a?.dataset.diffIdx;x!==void 0?o.messages[parseInt(x)]={role:"system",content:`Created ${e}`}:o.messages.push({role:"system",content:`Created ${e}`})}else{let c,x=u,M=[u];e!==u&&M.push(e);let l=e.split("/").pop()||e,f=o.roots[0]||"",g=f?`${f}/${l}`:l;g!==u&&g!==e&&M.push(g);for(let h of M){let v=(await N("fs.read",{path:h}).catch(()=>null))?.payload?.content;if(v!=null){c=String(v),x=h;break}}if(c===void 0)p=`Could not read ${e} \u2014 tried: ${M.join(", ")}`,o.messages.push({role:"system",content:p});else{let h=c.split(i).length-1;if(h===1){let m=await N("fs.write",{path:x,content:c.replace(i,r)});if(m?.payload?.ok===!1)p=`Write failed: ${e} - ${m.payload?.error||"unknown"}`,o.messages.push({role:"system",content:p});else{d=!0;let v=a?.dataset.diffIdx;v!==void 0?o.messages[parseInt(v)]={role:"system",content:`Applied change to ${e}. Reloading...`}:o.messages.push({role:"system",content:`Applied change to ${e}. Reloading...`})}}else if(h>1)p=`Found ${h} exact matches in ${e} \u2014 expected 1. Edit not applied.`,o.messages.push({role:"system",content:p});else{let m=Lt(c,i);if(m){let v=c.slice(0,m.start)+r+c.slice(m.end),b=await N("fs.write",{path:x,content:v});if(b?.payload?.ok===!1)p=`Write failed: ${e} - ${b.payload?.error||"unknown"}`,o.messages.push({role:"system",content:p});else{d=!0;let $=a?.dataset.diffIdx;$!==void 0?o.messages[parseInt($)]={role:"system",content:`Applied change to ${e} (fuzzy match). Reloading...`}:o.messages.push({role:"system",content:`Applied change to ${e} (fuzzy match). Reloading...`})}}else p=`No matching code found in ${e}. The file may have changed since the suggestion.`,o.messages.push({role:"system",content:p})}}}}catch(c){p=`Failed to apply: ${e} \u2014 ${c.message}`,o.messages.push({role:"system",content:p})}return B(),he(),d&&!ce._batchMode&&setTimeout(()=>{window.location.reload()},1500),{ok:d,file:e,error:p||void 0}}function st(t){t.disabled=!0,t.style.opacity="0.5";let e=t.dataset.idx;if(e!==void 0){let s=parseInt(e);try{let n=JSON.parse(ae(o.messages[s]?.content.slice(8)||"")),a=(n.search||"").split(`
|
|
463
463
|
`)[0].slice(0,80),i=(n.replace||"").split(`
|
|
464
|
-
`)[0].slice(0,80);o.messages[s]={role:"system",content:`Rejected change to ${n.file||"file"}: "${a}" \u2192 "${i}"`}}catch{o.messages[s]={role:"system",content:"Change rejected"}}}
|
|
464
|
+
`)[0].slice(0,80);o.messages[s]={role:"system",content:`Rejected change to ${n.file||"file"}: "${a}" \u2192 "${i}"`}}catch{o.messages[s]={role:"system",content:"Change rejected"}}}B(),he()}function Tt(t){let e=R.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 at(){let t=R.querySelector(".om-apply-bar");t&&t.classList.add("om-hidden")}async function dt(t){let e=t.dataset.file;if(!e)return;let s=De(e);try{(await N("fs.undo",{path:s}))?.payload?.ok?o.messages.push({role:"system",content:`Reverted change to ${e}`}):o.messages.push({role:"system",content:`No backup found for ${e}`})}catch{o.messages.push({role:"system",content:`Could not revert ${e} \u2014 backup may not exist`})}B()}async function it(t,e){switch(t){case"select":Rt();break;case"screenshot":Ot();break;case"chat":_e("chat");break;case"settings":_e("settings");break;case"close-panel":ke();break;case"prompt-send":Ne();break;case"save-settings":_t();break;case"get-key":{let s=e.dataset.url;s&&window.open(s,"_blank","noopener");break}case"change-key":{let s=R.querySelector("[data-key-change]");s&&s.classList.remove("om-hidden"),e.style.display="none";break}case"network":_e("chat"),At();break;case"attach-image":Nt();break;case"remove-attachment":{let s=parseInt(e.dataset.idx||"0",10);o.attachments.splice(s,1),je();break}case"apply-diff":ce(e);break;case"reject-diff":st(e);break;case"apply-all":{let s=Array.from(R.querySelectorAll('[data-action="apply-diff"]'));if(s.length===0)break;let n=new Set;for(let u of s){let d=u.dataset.file;d&&n.add(De(d))}let a=new Map;for(let u of n)try{let d=await N("fs.read",{path:u}).catch(()=>null);d?.payload&&d.payload.content!==void 0&&d.payload.content!==null?a.set(u,{exists:!0,content:String(d.payload.content)}):a.set(u,{exists:!1,content:""})}catch{}ce._batchMode=!0;let i=!1,r="";for(let u of s){let d=await ce(u);if(!d.ok){i=!0,r=d.error||`Failed to apply ${d.file||"change"}`;break}}if(ce._batchMode=!1,i&&a.size>0){for(let[u,d]of a)try{d.exists?await N("fs.write",{path:u,content:d.content}):await N("fs.delete",{path:u})}catch{}o.messages.push({role:"system",content:`Batch apply failed \u2014 all changes reverted. ${r}`.trim()}),B()}at(),i||setTimeout(()=>{window.location.reload()},1500);break}case"reject-all":{let s=R.querySelectorAll('[data-action="reject-diff"]');for(let n of Array.from(s))st(n);at();break}case"undo-diff":dt(e);break;case"clear-chat":{o.messages=[];try{sessionStorage.removeItem("__om_state__")}catch{}B();break}case"copy-msg":{let s=parseInt(e.dataset.idx||"0",10);e.innerHTML='<span class="om-spinner"></span>',rt(s).then(n=>{try{navigator.clipboard.writeText(n)}catch{}e.innerHTML=_.check,setTimeout(()=>{e.innerHTML=_.copy},1500)});break}case"report-issue":{e.innerHTML='<span class="om-spinner"></span>',rt().then(s=>{try{navigator.clipboard.writeText(s)}catch{}e.innerHTML=_.bug,window.open("https://github.com/Kalmuraee/OpenMagic/issues/new?template=bug_report.yml","_blank","noopener"),o.messages.push({role:"system",content:"Debug info copied to clipboard. Paste it in the Debug Info field on GitHub."}),o.panelOpen&&B()});break}case"clear-element":o.selectedElement=null,me();break;case"clear-screenshot":o.screenshot=null,me();break;case"minimize":{o.minimized=!o.minimized;let s=R.querySelector(".om-panel"),n=R.querySelector(".om-prompt-row"),a=R.querySelector(".om-prompt-attachments"),i=F.querySelectorAll(".om-pill-btn:not([data-action='minimize']), .om-pill-divider, .om-status-dot");o.minimized?(s&&s.classList.add("om-hidden"),n&&n.classList.add("om-hidden"),a&&a.classList.add("om-hidden"),i.forEach(r=>r.style.display="none")):(n&&n.classList.remove("om-hidden"),a&&a.classList.remove("om-hidden"),i.forEach(r=>r.style.display=""),o.panelOpen&&o.activePanel&&s&&s.classList.remove("om-hidden"));break}}}function we(){let t=R.querySelector(".om-status-dot");if(t){let e=o.updateAvailable?"outdated":o.connected?"connected":"disconnected";t.className=`om-status-dot ${e}`,t.setAttribute("title",o.updateAvailable?`v${o.latestVersion} available \u2014 run npx openmagic@latest`:o.connected?"Connected":"Disconnected")}}function ue(){R.querySelectorAll(".om-pill-btn").forEach(t=>{let e=t.dataset.action;t.classList.toggle("active",e===o.activePanel||e==="select"&&o.selecting)})}function pt(){let t=R.querySelector(".om-model-switcher");if(!t)return;let e=Q[o.provider];if(!e){t.innerHTML="";return}let s=e.models.map(n=>`<option value="${n.id}" ${o.model===n.id?"selected":""}>${n.name}</option>`).join("");t.innerHTML=s}function me(){let t=[];if(o.selectedElement){let s=`${o.selectedElement.tagName}${o.selectedElement.id?"#"+o.selectedElement.id:""}`;t.push(`<span class="om-prompt-chip">${z(s)} <button class="om-prompt-chip-x" data-action="clear-element">${_.x}</button></span>`)}o.screenshot&&t.push(`<span class="om-prompt-chip">Screenshot <button class="om-prompt-chip-x" data-action="clear-screenshot">${_.x}</button></span>`),o.attachments.length&&t.push(`<span class="om-prompt-chip">${o.attachments.length} image${o.attachments.length>1?"s":""}</span>`),o.groundedFiles.length&&t.push(`<span class="om-prompt-chip">${o.groundedFiles.length} files grounded</span>`);let e=(o.selectedElement?.outerHTML?.length||0)+(o.screenshot?1e3:0)+o.groundedFiles.length*4e3;if(e>2e3){let s=Math.round(e/4),n=s>1e4?`~${Math.round(s/1e3)}K tokens`:`~${s} tokens`;t.push(`<span class="om-prompt-chip om-prompt-chip-tokens">${n}</span>`)}lt.innerHTML=t.join("")}function te(t){o.panelOpen=!0,o.activePanel=t,Ie.classList.remove("om-hidden");let e=R.querySelector(".om-panel-title");e&&(e.textContent=t==="settings"?"Settings":"Chat"),B(),ue()}function ke(){o.panelOpen=!1,o.activePanel="",Ie.classList.add("om-hidden"),ue()}function _e(t){o.panelOpen&&o.activePanel===t?ke():te(t)}function B(){o.activePanel==="settings"?J.innerHTML=Ht():o.activePanel==="chat"&&(J.innerHTML=Pt(),he()),ct()}function Ht(){let t=Object.entries(Q).map(([l,f])=>{let g=o.detectedClis.find(m=>m.id===l),h="";return g?g.installed&&g.authenticated?h=" \u2713 ready":g.installed?h=" (not logged in)":h=" (not installed)":h=o.configuredProviders[l]||f.local?" \u2713":"",`<option value="${l}" ${o.provider===l?"selected":""}>${f.name}${h}</option>`}).join(""),e=Q[o.provider],s=e?e.models.map(l=>`<option value="${l.id}" ${o.model===l.id?"selected":""}>${l.name}</option>`).join(""):'<option value="">Select provider first</option>',n=e?.local||!1,a=e?.keyUrl||"",i=e?.keyPlaceholder||"Enter API key...",r=o.configuredProviders[o.provider]||!1,u=o.updateAvailable?`<div class="om-update-banner">v${o.latestVersion} available <code class="om-update-cmd">npx openmagic@latest</code></div>`:"",d=r||n?`<div class="om-status om-status-success">${_.check} ${e?.name||"Provider"} connected</div>`:"",p=o.saveStatus==="saving"?'<span class="om-spinner"></span> Saving...':o.saveStatus==="saved"?`${_.check} Saved`:"Save",c=o.saveStatus==="saving"?"om-btn om-btn-saving":o.saveStatus==="saved"?"om-btn om-btn-saved":"om-btn",x=o.saveStatus==="saving"?"disabled":"",M="";return!n&&o.provider&&(r?M=`
|
|
465
465
|
<div class="om-field">
|
|
466
466
|
<label class="om-label">API Key</label>
|
|
467
467
|
<div class="om-key-configured">
|
|
@@ -474,7 +474,7 @@
|
|
|
474
474
|
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${_.externalLink} Get key</button>`:""}
|
|
475
475
|
</div>
|
|
476
476
|
</div>
|
|
477
|
-
</div>`:
|
|
477
|
+
</div>`:M=`
|
|
478
478
|
<div class="om-field">
|
|
479
479
|
<label class="om-label">API Key</label>
|
|
480
480
|
<div class="om-key-row">
|
|
@@ -483,7 +483,7 @@
|
|
|
483
483
|
</div>
|
|
484
484
|
${a?`<div class="om-key-hint"><a data-action="get-key" data-url="${a}">Get your ${e?.name||""} API key here</a></div>`:""}
|
|
485
485
|
</div>`),`
|
|
486
|
-
${
|
|
486
|
+
${u}
|
|
487
487
|
<div class="om-settings">
|
|
488
488
|
<div class="om-field">
|
|
489
489
|
<label class="om-label">Provider</label>
|
|
@@ -493,33 +493,33 @@
|
|
|
493
493
|
<label class="om-label">Model</label>
|
|
494
494
|
<select class="om-select" data-field="model"><option value="">Select Model...</option>${s}</select>
|
|
495
495
|
</div>
|
|
496
|
-
${
|
|
497
|
-
<button class="${
|
|
498
|
-
${
|
|
499
|
-
</div>`}function Pt(){if(!o.provider||!o.hasApiKey&&!Q[o.provider]?.local)return'<div class="om-status om-status-error">Configure your provider in Settings first</div>';let t=o.messages.map((n,a)=>{if(n.content.startsWith("__DIFFGROUP__"))return"";if(n.content.startsWith("__DIFF__"))try{let r=JSON.parse(
|
|
500
|
-
<div class="om-diff-file">${
|
|
496
|
+
${M}
|
|
497
|
+
<button class="${c}" data-action="save-settings" ${x}>${p}</button>
|
|
498
|
+
${d}
|
|
499
|
+
</div>`}function Pt(){if(!o.provider||!o.hasApiKey&&!Q[o.provider]?.local)return'<div class="om-status om-status-error">Configure your provider in Settings first</div>';let t=o.messages.map((n,a)=>{if(n.content.startsWith("__DIFFGROUP__"))return"";if(n.content.startsWith("__DIFF__"))try{let r=JSON.parse(ae(n.content.slice(8))),u=r.type==="create"||!r.search&&r.replace,d=ve(r.search||""),p=ve(r.replace||""),c=u?"Create new file":"Edit",x=Dt(r.search||"",r.replace||"");return`<div class="om-diff-card" data-diff-idx="${a}">
|
|
500
|
+
<div class="om-diff-file">${z(c)}: ${z(r.file)}</div>
|
|
501
501
|
<div class="om-diff-lines">${x}</div>
|
|
502
502
|
<div class="om-diff-actions">
|
|
503
|
-
<button class="om-btn om-btn-sm" data-action="apply-diff" data-file="${
|
|
503
|
+
<button class="om-btn om-btn-sm" data-action="apply-diff" data-file="${z(r.file)}" data-search="${d}" data-replace="${p}">Apply</button>
|
|
504
504
|
<button class="om-btn-secondary om-btn-sm" data-action="reject-diff" data-idx="${a}">Reject</button>
|
|
505
505
|
</div>
|
|
506
|
-
</div>`}catch{return'<div class="om-msg om-msg-system">Malformed diff data</div>'}if(n.content.startsWith("Applied change to ")){let r=n.content.replace("Applied change to ","").replace(/ \(fuzzy match.*?\)/g,"").replace(". Reloading...","");return`<div class="om-msg om-msg-system">${
|
|
507
|
-
// [FILE TRUNCATED \u2014 showing ${
|
|
508
|
-
// [FILE TRUNCATED \u2014 showing ${O} of ${H.length} chars]`),
|
|
509
|
-
// [TRUNCATED]`),
|
|
510
|
-
// [FILE TRUNCATED \u2014 showing ${Z} of ${q.length} chars]`),
|
|
511
|
-
// [TRUNCATED]`),
|
|
512
|
-
/* [TRUNCATED] */`),
|
|
513
|
-
All network requests (${
|
|
514
|
-
Fetch/XHR requests (${a.length}):`);for(let
|
|
515
|
-
Console errors: ${
|
|
516
|
-
Slowest resources:`);for(let
|
|
517
|
-
`)}),
|
|
506
|
+
</div>`}catch{return'<div class="om-msg om-msg-system">Malformed diff data</div>'}if(n.content.startsWith("Applied change to ")){let r=n.content.replace("Applied change to ","").replace(/ \(fuzzy match.*?\)/g,"").replace(". Reloading...","");return`<div class="om-msg om-msg-system">${z(n.content)} <button class="om-undo-btn" data-action="undo-diff" data-file="${z(r)}">Undo</button></div>`}let i=n.role==="user"||n.role==="assistant"?`<button class="om-copy-btn" data-action="copy-msg" data-idx="${a}" title="Copy">${_.copy}</button>`:"";return n.role==="assistant"?`<div class="om-msg om-msg-assistant" dir="auto">${jt(n.content)}${i}</div>`:`<div class="om-msg om-msg-${n.role}" dir="auto">${z(n.content)}${i}</div>`}).join(""),e=o.streaming?'<div class="om-msg om-msg-assistant"><span class="om-spinner"></span> Generating response...</div>':"";return`<div class="om-chat-messages">${!o.messages.length&&!o.streaming?'<div class="om-chat-empty">Select an element or type below to start</div>':""}${t}${e}</div>`}function he(){requestAnimationFrame(()=>{let t=J.querySelector(".om-chat-messages");t&&(t.scrollTop=t.scrollHeight)})}async function _t(){let e=J.querySelector('[data-field="apiKey"]')?.value||"";if(!o.provider){o.saveStatus="error",xe(),setTimeout(()=>{o.saveStatus="",B()},2e3);return}if(!Te()){o.saveStatus="error",xe();let n=J.querySelector('[data-action="save-settings"]');n&&(n.innerHTML="Not connected - check terminal"),setTimeout(()=>{o.saveStatus="",B()},3e3);return}let s={provider:o.provider,model:o.model};e&&(s.apiKey=e),o.saveStatus="saving",xe();try{let n=await Promise.race([N("config.set",s),new Promise((a,i)=>setTimeout(()=>i(new Error("Save timed out")),8e3))]);e&&o.provider&&(o.configuredProviders[o.provider]=!0),o.hasApiKey=!!(e||o.configuredProviders[o.provider]),o.saveStatus="saved",xe(),pt(),setTimeout(()=>{o.saveStatus="",o.activePanel==="settings"&&te("chat")},1200)}catch(n){o.saveStatus="error";let a=J.querySelector('[data-action="save-settings"]'),i=(n?.message||"").includes("timeout")?"Connection timeout - is the CLI running?":(n?.message||"").includes("connected")?"Not connected to OpenMagic server":`Save failed: ${n?.message||"Unknown error"}`;a&&(a.innerHTML=i,a.className="om-btn",a.disabled=!1),setTimeout(()=>{o.saveStatus="",B()},4e3)}}function xe(){let t=J.querySelector('[data-action="save-settings"]');t&&(o.saveStatus==="saving"?(t.innerHTML='<span class="om-spinner"></span> Saving...',t.className="om-btn om-btn-saving",t.disabled=!0):o.saveStatus==="saved"?(t.innerHTML=`${_.check} Saved`,t.className="om-btn om-btn-saved",t.disabled=!1):o.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 Ne(){let t=ee.value.trim();if(!t||o.streaming)return;if(!o.provider||!o.hasApiKey&&!Q[o.provider]?.local){te("settings");return}o.messages.push({role:"user",content:t}),o.streaming=!0,o.streamContent="",ee.value="",te("chat");let e=nt(o.selectedElement,o.screenshot);e.pageUrl=window.location.href,e.pageTitle=document.title,o.attachments.length>0&&(e.screenshot||(e.screenshot=o.attachments[0]),e.attachments=[...o.attachments]);let s=8,n=48e3,a=/\.(?:[cm]?[jt]sx?|svelte|vue|astro|html?|css|scss|less|php|py)$/i,i=J.querySelector(".om-msg-assistant:last-child");i&&(i.innerHTML='<span class="om-spinner"></span> Reading project files...');try{let p=await N("fs.list",{});p?.payload?.projectTree&&(e.projectTree=p.payload.projectTree);let x=(p?.payload?.files||[]).filter(y=>y.type==="file"&&a.test(y.path)),M=[t];if(o.selectedElement&&(o.selectedElement.id&&M.push(o.selectedElement.id),o.selectedElement.className&&M.push(o.selectedElement.className),o.selectedElement.textContent&&M.push(o.selectedElement.textContent.slice(0,100)),o.selectedElement.componentHint&&M.push(o.selectedElement.componentHint),o.selectedElement.ancestry))for(let y of o.selectedElement.ancestry)M.push(y);let l=M.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)),h="";if(o.selectedElement?.componentHint||g.length){let y=(o.selectedElement?.componentHint||"").toLowerCase(),k=new Map;for(let A of x){let C=A.path.split("/")[0];if(!C||C.includes("."))continue;let W=A.path.toLowerCase(),U=k.get(C)||0;y&&W.includes(y)&&(U+=10);for(let V of g)W.includes(V.toLowerCase())&&(U+=5);/(component|page|route|layout)/.test(W)&&(U+=1),k.set(C,U)}let E=0;for(let[A,C]of k)C>E&&(E=C,h=A)}let m=x.map(y=>{let k=0,E=y.path.toLowerCase(),A=E.replace(/\([^)]+\)\//g,"");if(h){let C=y.path.split("/")[0];C===h?k+=20:C!==h&&!y.path.includes("/")?k+=0:k-=15}for(let C of g)A.includes(C.toLowerCase())&&(k+=15);if(o.selectedElement?.componentHint){let C=o.selectedElement.componentHint.toLowerCase();E.includes(C)&&(k+=12)}for(let C of l)E.includes(C)&&(k+=5);return/(component|page|route|layout|template|view)/.test(E)&&(k+=3),/page\.[jt]sx?$|layout\.[jt]sx?$|\+page\.svelte$/.test(E)&&(k+=5),{...y,score:k}}).sort((y,k)=>k.score-y.score),v=[],b=new Set,$=0,j=m.slice(0,s).filter(y=>y.score>0),D=o.roots[0]||"",ne=await Promise.all(j.map(y=>{let k=D?`${D}/${y.path}`:y.path;return N("fs.read",{path:k}).catch(()=>null)}));for(let y=0;y<j.length;y++){let k=j[y];if($>=n)break;try{let E=String(ne[y]?.payload?.content||"");if(!E)continue;let A=Math.min(12e3,n-$),C=E.slice(0,A);E.length>A&&(C+=`
|
|
507
|
+
// [FILE TRUNCATED \u2014 showing ${A} of ${E.length} chars]`),v.push({path:k.path,content:C}),b.add(k.path),$+=C.length;let W=k.path.replace(/\.[^.]+$/,""),U=[".module.css",".module.scss",".css",".scss",".styles.ts"];for(let L of U){let w=W+L;if(b.has(w)||$>=n)continue;if(x.find(P=>P.path===w)){try{let P=await N("fs.read",{path:D?`${D}/${w}`:w}),H=String(P?.payload?.content||"");if(H){let O=Math.min(4e3,n-$),I=H.slice(0,O);H.length>O&&(I+=`
|
|
508
|
+
// [FILE TRUNCATED \u2014 showing ${O} of ${H.length} chars]`),v.push({path:w,content:I}),b.add(w),$+=I.length}}catch{}break}}if(v.length<=2&&$<n){let L=["layout.tsx","layout.jsx","layout.js","layout.ts"],w=k.path.replace(/\/[^/]+$/,""),T=0;for(;w&&T<4&&$<n;){let P=!1;for(let O of L){let I=`${w}/${O}`;if(b.has(I)){P=!0;break}try{let q=await N("fs.read",{path:D?`${D}/${I}`:I}).catch(()=>null),Z=String(q?.payload?.content||"");if(Z){let Y=Math.min(4e3,n-$),oe=Z.slice(0,Y);Z.length>Y&&(oe+=`
|
|
509
|
+
// [TRUNCATED]`),v.push({path:I,content:oe}),b.add(I),$+=oe.length,P=!0;break}}catch{}}let H=w.replace(/\/[^/]+$/,"");if(H===w||!H)break;w=H,T++}}let V={},re=v.find(L=>L.path==="tsconfig.json"||L.path==="tsconfig.app.json");if(re)try{let L=JSON.parse(re.content.replace(/\/\/.*$/gm,"").replace(/,\s*([}\]])/g,"$1")),w=L?.compilerOptions?.paths||{},T=L?.compilerOptions?.baseUrl||".";for(let[P,H]of Object.entries(w)){let O=H?.[0];if(P&&O){let I=P.replace(/\/\*$/,"/"),q=O.replace(/\/\*$/,"/"),Z=T==="."?q:`${T}/${q}`;V[I]=Z}}}catch{}let S=E.matchAll(/(?:import|from)\s+['"]\.?\.\/([\w/.-]+)['"]/g);for(let L of S){if($>=n)break;let w=L[1],T=k.path.replace(/\/[^/]+$/,""),P=[`${T}/${w}`,`${T}/${w}.tsx`,`${T}/${w}.ts`,`${T}/${w}.jsx`,`${T}/${w}.js`,`${T}/${w}/index.tsx`,`${T}/${w}/index.ts`];for(let H of P){if(b.has(H))break;if(x.find(I=>I.path===H)){try{let I=await N("fs.read",{path:D?`${D}/${H}`:H}),q=String(I?.payload?.content||"");if(q){let Z=Math.min(8e3,n-$),Y=q.slice(0,Z);q.length>Z&&(Y+=`
|
|
510
|
+
// [FILE TRUNCATED \u2014 showing ${Z} of ${q.length} chars]`),v.push({path:H,content:Y}),b.add(H),$+=Y.length}}catch{}break}}}if(Object.keys(V).length>0){let L=E.matchAll(/(?:import|from)\s+['"]([^.'"]\S+)['"]/g);for(let w of L){if($>=n)break;let T=w[1];for(let[P,H]of Object.entries(V)){if(!T.startsWith(P))continue;let O=T.replace(P,H),I=[O,`${O}.tsx`,`${O}.ts`,`${O}.jsx`,`${O}.js`,`${O}/index.tsx`,`${O}/index.ts`];for(let q of I){if(b.has(q))break;if(x.find(Y=>Y.path===q)){try{let Y=await N("fs.read",{path:D?`${D}/${q}`:q}),oe=String(Y?.payload?.content||"");if(oe){let qe=Math.min(8e3,n-$),Se=oe.slice(0,qe);oe.length>qe&&(Se+=`
|
|
511
|
+
// [TRUNCATED]`),v.push({path:q,content:Se}),b.add(q),$+=Se.length}}catch{}break}}break}}}}catch{}}if($<n)try{let y=o.roots[0]||"",k=await N("fs.read",{path:y?`${y}/package.json`:"package.json"}),E=String(k?.payload?.content||"");if(E)try{let A=JSON.parse(E),C={...A.dependencies,...A.devDependencies},W=JSON.stringify(C,null,2);v.push({path:"package.json (dependencies)",content:W.slice(0,2e3)})}catch{v.push({path:"package.json",content:E.slice(0,2e3)})}}catch{}if($<n){let y=o.roots[0]||"",k=["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","tsconfig.json","tsconfig.app.json","next.config.js","next.config.mjs","next.config.ts","vite.config.ts","vite.config.js","astro.config.mjs","astro.config.ts"];for(let E of k)if(!($>=n||b.has(E)))try{let A=y?`${y}/${E}`:E,C=await N("fs.read",{path:A}).catch(()=>null),W=String(C?.payload?.content||"");if(W){let U=Math.min(12e3,n-$),V=W.slice(0,U);W.length>U&&(V+=`
|
|
512
|
+
/* [TRUNCATED] */`),v.push({path:E,content:V}),b.add(E),$+=V.length}}catch{}}if(v.length){e.files=v;let y=v.map(k=>k.path.split("/").pop()).join(", ");i&&(i.innerHTML=`<span class="om-spinner"></span> ${z(`Thinking... (${v.length} files: ${y})`)}`)}o.groundedFiles=v.map(y=>y.path)}catch{}let r=4,u=0,d=new Set;try{for(;u<=r;){o.streamContent="";let p=await We("llm.chat",{provider:o.provider,model:o.model,messages:o.messages.map(m=>({role:m.role,content:m.content})),context:e},m=>{o.streamContent+=m}),c=o.streamContent||p?.content||"",x=c;try{let m=JSON.parse(c);m.explanation&&(x=m.explanation)}catch{let m=c.match(/```(?:json)?\s*([\s\S]*?)```/);if(m)try{let v=JSON.parse(m[1]);v.explanation&&(x=v.explanation)}catch{}}let M=p?.modifications?.some(m=>m.type==="edit"&&m.file&&m.search&&m.replace||m.type==="create"&&m.file&&m.content),l=!M&&(x.match(/NEED_FILE:\s*"?([^\s"}\]]+)"?/)||x.match(/(?:need|provide|show|read|see|contents?\s+of)\s+(?:the\s+)?(?:file\s+)?[`"']?([a-zA-Z0-9_/.@-]+\.[a-z]{1,5})[`"']?/i)||x.match(/(?:source\s+(?:file|code)\s+(?:for|of|at))\s+[`"']?([a-zA-Z0-9_/.@-]+\.[a-z]{1,5})[`"']?/i)||c.match(/NEED_FILE:\s*\\?"?([^\s"\\}\]]+)"?/));if(l&&u<r&&!d.has(l[1].trim())){let m=l[1].trim();d.add(m),u++;let v=J.querySelector(".om-msg-assistant:last-child");v&&(v.innerHTML=`<span class="om-spinner"></span> ${z(`Reading ${m}...`)}`);try{let b=o.roots[0]||"",$=b?`${b}/${m}`:m,j,D=[$];m!==$&&D.push(m);let ne=m.split("/").pop()||m,y=b?`${b}/${ne}`:ne;y!==$&&y!==m&&D.push(y);for(let k of D){let E=await N("fs.read",{path:k}).catch(()=>null);if(E?.payload?.content){j=String(E.payload.content);break}}if(j){e.files||(e.files=[]);let k=e.files.findIndex(A=>A.path===m||A.path.endsWith("/"+m)||m.endsWith("/"+A.path)),E=j.slice(0,16e3);k>=0?e.files[k]={path:m,content:E}:e.files.push({path:m,content:E})}else{o.messages.push({role:"system",content:`Could not read ${m}`});break}}catch{o.messages.push({role:"system",content:`File not found: ${m}`});break}continue}let f=!M&&(x.match(/SEARCH_FILES:\s*"([^"]+)"(?:\s+in\s+(\S+))?/)||c.match(/SEARCH_FILES:\s*\\?"([^"\\]+)\\?"(?:\s+in\s+(\S+))?/)),g=e.searchResults?.some(m=>m.query===f?.[1]);if(f&&u<r&&!g){let m=f[1],v=f[2]||"";u++;let b=J.querySelector(".om-msg-assistant:last-child");b&&(b.innerHTML=`<span class="om-spinner"></span> ${z(`Searching: "${m}"...`)}`);try{let j=(await Promise.race([N("fs.grep",{pattern:m,path:v}),new Promise((D,ne)=>setTimeout(()=>ne(new Error("grep timeout")),5e3))]))?.payload?.results||[];j.length&&(e.searchResults||(e.searchResults=[]),e.searchResults.push({query:m,matches:j}))}catch{}continue}let h=x.replace(/^NEED_FILE:\s*\S+\s*/gm,"").replace(/^SEARCH_FILES:\s*"[^"]*"(?:\s+in\s+\S+)?\s*/gm,"").trim();if(h||(h="I couldn't determine the exact change from the available files. Try selecting a more specific element or giving more detail."),o.messages.push({role:"assistant",content:h}),p?.modifications?.length){let m=Math.random().toString(36).slice(2),v=p.modifications.filter(b=>b.type==="edit"&&b.file&&b.search&&b.replace||b.type==="create"&&b.file&&b.content);Tt(v.length);for(let b of p.modifications)if(b.type==="edit"&&b.file&&b.search&&b.replace){let $=Math.random().toString(36).slice(2),j=JSON.stringify({id:$,file:b.file,search:b.search,replace:b.replace,groupId:m});o.messages.push({role:"system",content:`__DIFF__${ve(j)}`})}else if(b.type==="create"&&b.file&&b.content){let $=Math.random().toString(36).slice(2),j=JSON.stringify({id:$,file:b.file,search:"",replace:b.content,type:"create",groupId:m});o.messages.push({role:"system",content:`__DIFF__${ve(j)}`})}else b.type==="delete"&&b.file&&o.messages.push({role:"system",content:`LLM proposed deleting ${b.file} \u2014 skipped (use edit with search/replace instead)`})}break}}catch(p){o.streamContent.trim().length>20?(o.messages.push({role:"assistant",content:o.streamContent.trim()}),o.messages.push({role:"system",content:`Response interrupted: ${p.message}. Partial response shown above.`})):o.messages.push({role:"system",content:`Error: ${p.message}`})}o.streaming=!1,o.streamContent="",o.attachments=[],je(),B(),he()}function At(){let t=window.performance,e=t.getEntriesByType("navigation")[0],s=t.getEntriesByType("paint"),n=t.getEntriesByType("resource").slice(-20),a=ye(),i=be(),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 u=s.find(d=>d.name==="first-contentful-paint");if(u&&r.push(`FCP: ${Math.round(u.startTime)}ms`),n.length){let d=n.filter(c=>c.initiatorType==="fetch"||c.initiatorType==="xmlhttprequest"),p=d.length>0?d:n;r.push(`
|
|
513
|
+
All network requests (${p.length}):`);for(let c of p.slice(-30)){let x=c.name.length>80?"..."+c.name.slice(-77):c.name,M=c.responseStatus||"";r.push(` ${Math.round(c.duration)}ms ${M?`[${M}]`:""} ${x}`)}}if(a.length){r.push(`
|
|
514
|
+
Fetch/XHR requests (${a.length}):`);for(let d of a.slice(-20))r.push(` ${d.method} ${d.url.slice(0,80)} \u2192 ${d.status||"pending"} (${d.duration||"?"}ms)`)}if(i.length){let d=i.filter(c=>c.level==="error"),p=i.filter(c=>c.level==="warn");d.length&&r.push(`
|
|
515
|
+
Console errors: ${d.length}`),p.length&&r.push(`Console warnings: ${p.length}`)}if(n.length>5){let d=[...n].sort((p,c)=>c.duration-p.duration).slice(0,5);r.push(`
|
|
516
|
+
Slowest resources:`);for(let p of d)r.push(` ${Math.round(p.duration)}ms \u2014 ${p.name.split("/").pop()?.slice(0,60)}`)}o.messages.push({role:"system",content:r.join(`
|
|
517
|
+
`)}),B(),he(),me()}function Nt(){let t=R.querySelector(".om-file-input");t&&t.click()}function Ae(t){if(t)for(let e=0;e<t.length&&o.attachments.length<5;e++){let s=t[e];if(!s.type.startsWith("image/")||s.size>10*1024*1024)continue;let n=new FileReader;n.onload=()=>{typeof n.result=="string"&&(o.attachments.push(n.result),je())},n.readAsDataURL(s)}}function je(){let t=R.querySelector(".om-prompt-attachments");if(t){if(!o.attachments.length){t.innerHTML="",t.classList.add("om-hidden");return}t.classList.remove("om-hidden"),t.innerHTML=o.attachments.map((e,s)=>`<div class="om-attachment-thumb">
|
|
518
518
|
<img src="${e}" alt="attachment" />
|
|
519
519
|
<button class="om-attachment-remove" data-action="remove-attachment" data-idx="${s}">${_.x}</button>
|
|
520
|
-
</div>`).join("")}}var de=null,pe=null;function
|
|
520
|
+
</div>`).join("")}}var de=null,pe=null;function Rt(){o.selecting?Re():$e()}function $e(){o.selecting=!0,document.body.style.cursor="crosshair",ue(),pe=e=>{let s=e.target;if(s.closest("openmagic-toolbar")||s.dataset?.openmagic)return;let n=s.getBoundingClientRect();Ve({x:n.x,y:n.y,width:n.width,height:n.height})},de=e=>{e.preventDefault(),e.stopPropagation();let s=e.target;s.closest("openmagic-toolbar")||s.dataset?.openmagic||(o.selectedElement=Ge(s),Re(),me(),ee.focus())};let t=e=>{e.key==="Escape"&&Re()};document.addEventListener("mousemove",pe,!0),document.addEventListener("click",de,!0),document.addEventListener("keydown",t,!0),$e._escHandler=t}function Re(){o.selecting=!1,document.body.style.cursor="",Xe(),pe&&(document.removeEventListener("mousemove",pe,!0),pe=null),de&&(document.removeEventListener("click",de,!0),de=null);let t=$e._escHandler;t&&(document.removeEventListener("keydown",t,!0),$e._escHandler=null),ue()}async function Ot(){let t;try{let n=o.selectedElement?.cssSelector?.trim();n&&(t=document.querySelector(n)||void 0)}catch{}let e=await Je(t||void 0);e.data&&e.data.length>5e3?(o.screenshot=e.data,me(),ee.focus()):(o.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."}),te("chat"),B())}function It(){let t=!1,e=0,s=0,n=0,a=0;F.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 u=F.getBoundingClientRect();n=u.left,a=u.top,i.preventDefault()}),document.addEventListener("mousemove",i=>{t&&(F.style.left=n+i.clientX-e+"px",F.style.top=a+i.clientY-s+"px",F.style.right="auto",F.style.bottom="auto")}),document.addEventListener("mouseup",()=>{if(t){t=!1;try{localStorage.setItem("__om_pos__",JSON.stringify({left:F.style.left,top:F.style.top}))}catch{}}})}function z(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}function Dt(t,e){let s=t.split(`
|
|
521
521
|
`),n=e.split(`
|
|
522
|
-
`),a=[],i=30,r=Math.min(s.length,i),
|
|
523
|
-
`),s=
|
|
524
|
-
`)}function qt(){fetch("https://registry.npmjs.org/openmagic/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout?AbortSignal.timeout(5e3):void 0}).then(t=>t.ok?t.json():null).then(t=>{if(!t||typeof t.version!="string"||!/^\d+\.\d+\.\d+/.test(t.version))return;let e=t.version.split(".").map(Number),s=Oe.split(".").map(Number);for(let n=0;n<3;n++){if((e[n]||0)>(s[n]||0)){o.updateAvailable=!0,o.latestVersion=t.version,zt();return}if((e[n]||0)<(s[n]||0))return}}).catch(()=>{})}function zt(){
|
|
522
|
+
`),a=[],i=30,r=Math.min(s.length,i),u=Math.min(n.length,i),d=0;for(;d<r&&d<u&&s[d]===n[d];)d++;let p=0;for(;p<r-d&&p<u-d&&s[r-1-p]===n[u-1-p];)p++;for(let c=0;c<d;c++)a.push(`<div class="om-diff-line om-diff-ctx"><span class="om-diff-ln">${c+1}</span><span class="om-diff-sign"> </span>${z(s[c])}</div>`);for(let c=d;c<r-p;c++)a.push(`<div class="om-diff-line om-diff-del"><span class="om-diff-ln">${c+1}</span><span class="om-diff-sign">-</span>${z(s[c])}</div>`);for(let c=d;c<u-p;c++)a.push(`<div class="om-diff-line om-diff-ins"><span class="om-diff-ln"> </span><span class="om-diff-sign">+</span>${z(n[c])}</div>`);for(let c=r-p;c<r;c++)a.push(`<div class="om-diff-line om-diff-ctx"><span class="om-diff-ln">${c+1}</span><span class="om-diff-sign"> </span>${z(s[c])}</div>`);return s.length>i&&a.push(`<div class="om-diff-line om-diff-ctx">... ${s.length-i} more lines</div>`),a.join("")||`<div class="om-diff-line om-diff-ins">${z(e.slice(0,500))}</div>`}function jt(t){let e=t.replace(/\\n/g,`
|
|
523
|
+
`),s=z(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,"• $1"),s=s.replace(/\n/g,"<br>"),s}async function rt(t){let e=[],s=null;try{Te()&&(s=(await Promise.race([N("debug.logs"),new Promise((f,g)=>setTimeout(()=>g(new Error("timeout")),3e3))]))?.payload||null)}catch{}e.push("## Environment"),e.push(""),e.push(`- **OpenMagic**: v${Oe}${o.updateAvailable?` (v${o.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**: ${o.connected?"connected":"disconnected"}`),e.push(`- **Provider**: ${Q[o.provider]?.name||o.provider||"not set"}`),e.push(`- **Model**: ${o.model||"not set"}`),e.push(`- **API Key Set**: ${o.hasApiKey?"yes":"no"}`);let n=Object.entries(o.configuredProviders).filter(([,l])=>l).map(([l])=>Q[l]?.name||l);if(n.length&&e.push(`- **Configured Providers**: ${n.join(", ")}`),o.roots.length&&e.push(`- **Project Roots**: ${o.roots.join(", ")}`),o.selectedElement){let l=o.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(o.groundedFiles.length){e.push(""),e.push("## Files Sent to LLM"),e.push("");for(let l of o.groundedFiles)e.push(`- \`${l}\``)}let a=[];for(let l of o.messages)if(l.content.startsWith("__DIFF__"))try{let f=JSON.parse(ae(l.content.slice(8)));a.push({file:f.file,type:f.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=o.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,u=r.getEntriesByType("navigation")[0],d=r.getEntriesByType("paint");if(u){e.push(""),e.push("## Page Performance"),e.push(""),e.push(`- **Page Load**: ${Math.round(u.loadEventEnd-u.startTime)}ms`),e.push(`- **DOM Ready**: ${Math.round(u.domContentLoadedEventEnd-u.startTime)}ms`),e.push(`- **TTFB**: ${Math.round(u.responseStart-u.startTime)}ms`);let l=d.find(f=>f.name==="first-contentful-paint");l&&e.push(`- **FCP**: ${Math.round(l.startTime)}ms`)}let p=be();if(p.length){let l=p.filter(h=>h.level==="error"),f=p.filter(h=>h.level==="warn"),g=p.filter(h=>h.level==="log"||h.level==="info"||h.level==="debug");if(e.push(""),e.push("## Browser Console"),e.push(""),e.push(`Total: ${p.length} entries (${l.length} errors, ${f.length} warnings, ${g.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(m=>String(m)).join(" ").slice(0,300)}`);e.push("```")}if(f.length){e.push(""),e.push(`### Warnings (${f.length})`),e.push("```");for(let h of f.slice(-10))e.push(`[${new Date(h.timestamp).toISOString()}] ${h.args.map(m=>String(m)).join(" ").slice(0,200)}`);e.push("```")}if(g.length){e.push(""),e.push("<details><summary>Log/Info/Debug ("+g.length+" entries)</summary>"),e.push(""),e.push("```");for(let h of g.slice(-30))e.push(`[${new Date(h.timestamp).toISOString()}] [${h.level}] ${h.args.map(m=>String(m)).join(" ").slice(0,200)}`);e.push("```"),e.push("</details>")}}let c=ye(),x=c.filter(l=>l.status&&l.status>=400),M=c.filter(l=>l.duration&&l.duration>2e3);if(x.length||M.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(M.length){e.push(`### Slow Requests >2s (${M.length})`),e.push("```");for(let l of M.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,f=l.filter(m=>m.level==="error"),g=l.filter(m=>m.level==="warn"),h=l.filter(m=>m.level==="log"||m.level==="info");if(e.push(""),e.push("## Server Logs (Terminal)"),e.push(""),e.push(`Total: ${l.length} entries (${f.length} errors, ${g.length} warnings, ${h.length} log/info)`),f.length){e.push(""),e.push(`### Server Errors (${f.length})`),e.push("```");for(let m of f.slice(-15))e.push(`[${new Date(m.ts).toISOString()}] ${m.msg.slice(0,300)}`);e.push("```")}if(g.length){e.push(""),e.push(`### Server Warnings (${g.length})`),e.push("```");for(let m of g.slice(-10))e.push(`[${new Date(m.ts).toISOString()}] ${m.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 m of l.slice(-50))e.push(`[${new Date(m.ts).toISOString()}] [${m.level}] ${m.msg.slice(0,200)}`);e.push("```"),e.push("</details>")}if(o.messages.length){e.push(""),e.push("## Chat History"),e.push(""),e.push("<details><summary>Full conversation ("+o.messages.length+" messages)</summary>"),e.push(""),e.push("```");for(let l of o.messages)if(!l.content.startsWith("__DIFFGROUP__")){if(l.content.startsWith("__DIFF__")){try{let f=JSON.parse(ae(l.content.slice(8)));e.push(`[diff] ${f.type||"edit"}: ${f.file}`),f.search&&e.push(` - search: ${f.search.slice(0,100)}...`),f.replace&&e.push(` + replace: ${f.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=o.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(`
|
|
524
|
+
`)}function qt(){fetch("https://registry.npmjs.org/openmagic/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout?AbortSignal.timeout(5e3):void 0}).then(t=>t.ok?t.json():null).then(t=>{if(!t||typeof t.version!="string"||!/^\d+\.\d+\.\d+/.test(t.version))return;let e=t.version.split(".").map(Number),s=Oe.split(".").map(Number);for(let n=0;n<3;n++){if((e[n]||0)>(s[n]||0)){o.updateAvailable=!0,o.latestVersion=t.version,zt();return}if((e[n]||0)<(s[n]||0))return}}).catch(()=>{})}function zt(){we()}typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ot):ot());})();
|
|
525
525
|
//# sourceMappingURL=index.global.js.map
|