openmagic 0.37.0 → 0.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var OpenMagicToolbar=(()=>{var
|
|
2
|
+
"use strict";var OpenMagicToolbar=(()=>{var Ie=`
|
|
3
3
|
:host {
|
|
4
4
|
all: initial;
|
|
5
5
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
@@ -142,6 +142,7 @@
|
|
|
142
142
|
font-size: 11px; line-height: 1; padding: 0 1px; opacity: 0.5;
|
|
143
143
|
}
|
|
144
144
|
.om-prompt-chip-x:hover { opacity: 1; }
|
|
145
|
+
.om-prompt-chip-tokens { color: #888; background: transparent; border: 1px solid rgba(255,255,255,0.06); font-size: 9px; }
|
|
145
146
|
|
|
146
147
|
.om-prompt-input {
|
|
147
148
|
flex: 1;
|
|
@@ -176,6 +177,14 @@
|
|
|
176
177
|
}
|
|
177
178
|
.om-prompt-attach:hover { color: #a29bfe; background: rgba(108, 92, 231, 0.1); }
|
|
178
179
|
|
|
180
|
+
.om-model-switcher {
|
|
181
|
+
background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08);
|
|
182
|
+
color: #888; font-size: 10px; padding: 2px 4px; border-radius: 4px;
|
|
183
|
+
max-width: 90px; flex-shrink: 0; cursor: pointer; outline: none;
|
|
184
|
+
}
|
|
185
|
+
.om-model-switcher:hover { border-color: rgba(108, 92, 231, 0.3); color: #a29bfe; }
|
|
186
|
+
.om-model-switcher:focus { border-color: #6c5ce7; }
|
|
187
|
+
|
|
179
188
|
/* \u2500\u2500 Attachments \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
|
|
180
189
|
.om-prompt-attachments {
|
|
181
190
|
display: flex; gap: 6px; padding: 4px 8px; flex-wrap: wrap;
|
|
@@ -316,6 +325,15 @@
|
|
|
316
325
|
.om-diff-file { color: #a29bfe; font-size: 11px; font-weight: 600; margin-bottom: 6px; font-family: 'SF Mono', Consolas, monospace; }
|
|
317
326
|
.om-diff-removed { background: rgba(233,69,96,0.08); color: #fab1a0; padding: 4px 8px; border-radius: 4px; font-family: 'SF Mono', Consolas, monospace; font-size: 11px; white-space: pre-wrap; word-break: break-all; margin-bottom: 4px; }
|
|
318
327
|
.om-diff-added { background: rgba(0,184,148,0.08); color: #55efc4; padding: 4px 8px; border-radius: 4px; font-family: 'SF Mono', Consolas, monospace; font-size: 11px; white-space: pre-wrap; word-break: break-all; margin-bottom: 6px; }
|
|
328
|
+
.om-diff-lines { max-height: 300px; overflow-y: auto; border-radius: 6px; background: rgba(0,0,0,0.2); margin-bottom: 6px; font-family: 'SF Mono', Consolas, monospace; font-size: 11px; line-height: 1.5; }
|
|
329
|
+
.om-diff-line { display: flex; white-space: pre; padding: 0 8px; }
|
|
330
|
+
.om-diff-ln { color: #555; min-width: 28px; text-align: right; padding-right: 8px; user-select: none; flex-shrink: 0; }
|
|
331
|
+
.om-diff-sign { min-width: 14px; flex-shrink: 0; font-weight: bold; user-select: none; }
|
|
332
|
+
.om-diff-ctx { color: #888; }
|
|
333
|
+
.om-diff-del { background: rgba(233,69,96,0.12); color: #fab1a0; }
|
|
334
|
+
.om-diff-del .om-diff-sign { color: #e94560; }
|
|
335
|
+
.om-diff-ins { background: rgba(0,184,148,0.12); color: #55efc4; }
|
|
336
|
+
.om-diff-ins .om-diff-sign { color: #00b894; }
|
|
319
337
|
.om-diff-actions { display: flex; gap: 6px; }
|
|
320
338
|
.om-btn-sm { padding: 4px 10px; font-size: 11px; border-radius: 6px; }
|
|
321
339
|
.om-btn-secondary { background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.08); color: #888; cursor: pointer; font-family: inherit; }
|
|
@@ -372,48 +390,48 @@
|
|
|
372
390
|
.om-msg:hover .om-copy-btn { opacity: 1; }
|
|
373
391
|
.om-copy-btn:hover { color: #ccc; background: rgba(0,0,0,0.5); }
|
|
374
392
|
.om-msg { position: relative; }
|
|
375
|
-
`;var
|
|
376
|
-
`);
|
|
377
|
-
${
|
|
393
|
+
`;var U=null,B=new Map,ae=[],ke=[],oe=!1,Oe=!1,ve=null,we=0;function Se(){return Math.random().toString(36).slice(2)+Date.now().toString(36)}function $e(t,e){return Oe=!0,new Promise((s,n)=>{let a=!1,i=setTimeout(()=>{a||(a=!0,n(new Error("Handshake timeout")),U?.close())},1e4);try{let r=window.location.hostname||"127.0.0.1",m=window.location.protocol==="https:"?"wss:":"ws:";U=new WebSocket(`${m}//${r}:${t}/__openmagic__/ws`),U.onopen=()=>{let c=Se();U.send(JSON.stringify({id:c,type:"handshake",payload:{token:e}})),B.set(c,u=>{if(u.type==="handshake.ok"){clearTimeout(i),oe=!0,we=0;for(let p of ke)U?.send(p);ke=[],a||(a=!0,s())}else u.type==="error"&&(clearTimeout(i),a||(a=!0,n(new Error(u.payload?.message||"Handshake failed"))))})},U.onmessage=c=>{try{let u=JSON.parse(c.data);u.id&&B.has(u.id)&&(B.get(u.id)(u),(u.type==="llm.done"||u.type==="llm.error"||!u.type.startsWith("llm."))&&B.delete(u.id));for(let p of ae)p(u)}catch{}},U.onclose=()=>{let c=oe;if(oe=!1,B.forEach((u,p)=>{u({type:"error",id:p,payload:{message:"Connection lost"}})}),B.clear(),!c&&!a){clearTimeout(i),a=!0,n(new Error("WebSocket closed before handshake"));return}if(c&&Oe&&!ve){let u=Math.min(2e3*Math.pow(1.5,we),3e4);we++,ve=setTimeout(()=>{ve=null,$e(t,e).then(()=>{for(let p of ae)p({type:"reconnected",payload:{}})}).catch(()=>{})},u)}},U.onerror=()=>{!oe&&!a&&(clearTimeout(i),a=!0,n(new Error("WebSocket connection failed")))}}catch(r){clearTimeout(i),a||(a=!0,n(r))}})}function De(t){let e=JSON.stringify(t);U&&U.readyState===WebSocket.OPEN&&oe?U.send(e):ke.push(e)}function A(t,e){return new Promise((s,n)=>{let a=Se(),i=setTimeout(()=>{B.delete(a),n(new Error("Request timeout"))},3e4);B.set(a,r=>{clearTimeout(i),r.type==="error"?n(new Error(r.payload?.message||"Unknown error")):s(r)}),De({id:a,type:t,payload:e})})}function qe(t,e,s){return new Promise((n,a)=>{let i=Se(),r=3e5,m=setTimeout(c,r);function c(){B.delete(i),a(new Error("Stream timeout"))}function u(){clearTimeout(m),m=setTimeout(c,r)}B.set(i,p=>{p.type==="llm.chunk"?(u(),s(p.payload?.delta||"")):p.type==="llm.done"?(clearTimeout(m),B.delete(i),n(p.payload)):(p.type==="llm.error"||p.type==="error")&&(clearTimeout(m),B.delete(i),a(new Error(p.payload?.message||"Stream error")))}),De({id:i,type:t,payload:e})})}function je(t){return ae.push(t),()=>{ae=ae.filter(e=>e!==t)}}function Me(){return oe}var ze=["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 Be(t){let e=window.getComputedStyle(t),s={};for(let y of ze)s[y]=e.getPropertyValue(y);let n=t.getBoundingClientRect(),a={};if(t.parentElement&&t.parentElement!==document.body){let y=window.getComputedStyle(t.parentElement);for(let E of ze)a[E]=y.getPropertyValue(E)}let i=[];if(t.parentElement){let y=Array.from(t.parentElement.children),E=y.indexOf(t),_=Math.max(0,E-3),T=Math.min(y.length,E+4);_>0&&i.push(`... ${_} elements before ...`);for(let N=_;N<T;N++){let R=y[N],J=R.tagName.toLowerCase(),G=(R.className||"").toString().slice(0,60);R===t?i.push(`[SELECTED] <${J} class="${G}">`):i.push(`<${J} class="${G}">`)}T<y.length&&i.push(`... ${y.length-T} elements after ...`)}let r=[],m=Array.from(t.children).slice(0,12);for(let y=0;y<m.length;y++){let E=m[y],_=E.getBoundingClientRect(),T=window.getComputedStyle(E),N=null;if(y<m.length-1){let R=m[y+1].getBoundingClientRect();N={vertical:Math.round(R.top-_.bottom),horizontal:Math.round(R.left-_.right)}}r.push({tag:E.tagName.toLowerCase(),className:(E.className||"").toString().slice(0,80),rect:{x:Math.round(_.x),y:Math.round(_.y),width:Math.round(_.width),height:Math.round(_.height)},gapToNext:N,margin:T.margin,padding:T.padding})}let c=ht(t),u=gt(t,c),p={};for(let y of Array.from(t.attributes))(y.name.startsWith("aria-")||y.name==="role"||y.name==="tabindex")&&(p[y.name]=y.value);let v=[];for(let y of Array.from(t.attributes))y.name.startsWith("on")&&v.push(y.name);let k=ft(t),l=document.documentElement,f=window.getComputedStyle(l),g={};for(let y of Object.keys(l.dataset))g[y]=l.dataset[y]||"";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},d={};try{for(let E of c){let _=E.matchAll(/var\((--[a-zA-Z0-9_-]+)/g);for(let T of _){let N=T[1];d[N]||(d[N]=e.getPropertyValue(N).trim()||"(unset)")}}let y=(t.getAttribute("style")||"").matchAll(/var\((--[a-zA-Z0-9_-]+)/g);for(let E of y)d[E[1]]||(d[E[1]]=e.getPropertyValue(E[1]).trim()||"(unset)")}catch{}let $=e.zIndex,M=e.position!=="static"&&$!=="auto"||e.opacity!=="1"||e.transform!=="none"||e.filter!=="none",I=t.parentElement?window.getComputedStyle(t.parentElement).zIndex:"auto",D={zIndex:$,createsContext:M,parentZIndex:I},Q=n.top<window.innerHeight&&n.bottom>0&&n.left<window.innerWidth&&n.right>0,b=!0;try{b=t.checkVisibility?.({checkOpacity:!0,checkVisibilityCSS:!0})??!0}catch{b=e.display!=="none"&&e.visibility!=="hidden"}let w=t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth,S={isVisible:b,isInViewport:Q,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft,isScrollable:w},H=[],L=["(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 y of L)try{window.matchMedia(y).matches&&H.push(y)}catch{}let j="",z="";try{j=window.getComputedStyle(t,"::before").content||""}catch{}try{z=window.getComputedStyle(t,"::after").content||""}catch{}let X={before:j,after:z},ee=null;return(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLButtonElement)&&(ee={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:pt(t),cssSelector:mt(t),xpath:ut(t),computedStyles:s,ancestry:ct(t),componentHint:dt(t),rect:{x:n.x,y:n.y,width:n.width,height:n.height},parentStyles:a,siblings:i,childrenLayout:r,matchedCssRules:c,resolvedClasses:u,viewport:{width:window.innerWidth,height:window.innerHeight},ariaAttributes:p,eventHandlers:v,reactProps:k,themeState:h,cssVariables:d,stackingContext:D,visibilityState:S,activeBreakpoints:H,pseudoElements:X,formState:ee}}function ct(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 dt(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 pt(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(m=>`${m.name}="${m.value}"`).join(" "),r=Array.from(t.children).slice(0,5).map(m=>`<${m.tagName.toLowerCase()} .../>`).join(`
|
|
394
|
+
`);n=`<${a} ${i}>
|
|
395
|
+
${r}
|
|
378
396
|
${t.children.length>5?`<!-- +${t.children.length-5} more children -->`:""}
|
|
379
|
-
</${a}>`}return
|
|
397
|
+
</${a}>`}return n}function mt(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 ut(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 ht(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 ft(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[m,c]of Object.entries(a)){if(r>=10)break;if(m==="children")continue;let u=typeof c;u==="string"||u==="number"||u==="boolean"||c===null?(i[m]=c,r++):u==="function"?(i[m]="[function]",r++):Array.isArray(c)&&(i[m]=`[Array(${c.length})]`,r++)}return Object.keys(i).length>0?i:null}}catch{}return null}function gt(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 F=null;function Fe(t){F||(F=document.createElement("div"),F.style.cssText=`
|
|
380
398
|
position: fixed;
|
|
381
399
|
pointer-events: none;
|
|
382
400
|
z-index: 2147483646;
|
|
383
401
|
border: 2px solid #6c5ce7;
|
|
384
402
|
background: rgba(108, 92, 231, 0.1);
|
|
385
403
|
transition: all 0.1s ease;
|
|
386
|
-
`,
|
|
387
|
-
<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${
|
|
404
|
+
`,F.dataset.openmagic="highlight",document.body.appendChild(F)),F.style.left=`${t.x}px`,F.style.top=`${t.y}px`,F.style.width=`${t.width}px`,F.style.height=`${t.height}px`,F.style.display="block"}function We(){F&&(F.style.display="none")}async function Ue(t){try{let e=t||document.body,s=await yt(e);if(s)return{data:s}}catch{}try{let e=await bt(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 yt(t){let e=t.getBoundingClientRect(),s=Math.min(e.width||window.innerWidth,1920),n=Math.min(e.height||window.innerHeight,1080),a=Ke(t,0,4);if(!a)return null;let i=`
|
|
405
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${n}">
|
|
388
406
|
<foreignObject width="100%" height="100%">
|
|
389
|
-
<div xmlns="http://www.w3.org/1999/xhtml" style="width:${s}px;height:${
|
|
407
|
+
<div xmlns="http://www.w3.org/1999/xhtml" style="width:${s}px;height:${n}px;overflow:hidden;">
|
|
390
408
|
${a.outerHTML}
|
|
391
409
|
</div>
|
|
392
410
|
</foreignObject>
|
|
393
|
-
</svg>`,i=new Blob([r],{type:"image/svg+xml;charset=utf-8"}),u=URL.createObjectURL(i);return new Promise(c=>{let p=new Image,m=document.createElement("canvas"),k=Math.min(window.devicePixelRatio||1,2);m.width=s*k,m.height=o*k,p.onload=()=>{URL.revokeObjectURL(u);let S=m.getContext("2d");if(!S){c(null);return}S.scale(k,k),S.drawImage(p,0,0);try{if(m.width>1280){let y=1280/m.width,b=document.createElement("canvas");b.width=1280,b.height=Math.round(m.height*y);let g=b.getContext("2d");if(g){g.drawImage(m,0,0,b.width,b.height),c(b.toDataURL("image/jpeg",.8));return}}c(m.toDataURL("image/jpeg",.8))}catch{c(null)}},p.onerror=()=>{URL.revokeObjectURL(u),c(null)},setTimeout(()=>{URL.revokeObjectURL(u),c(null)},5e3),p.src=u})}async function mt(t){let e=t||document.documentElement,s=e.getBoundingClientRect(),o=document.createElement("canvas");o.width=400,o.height=300;let a=o.getContext("2d");return a?(a.fillStyle="#1a1a2e",a.fillRect(0,0,400,300),a.fillStyle="#e0e0e0",a.font="14px system-ui",a.fillText(`Element: <${e.tagName.toLowerCase()}>`,20,30),a.fillStyle="#888",a.font="12px system-ui",a.fillText(`Size: ${Math.round(s.width)}x${Math.round(s.height)}`,20,55),a.fillText(`Classes: ${(e.className||"").toString().slice(0,40)}`,20,75),a.fillText(`Page: ${window.location.pathname}`,20,95),a.fillStyle="#6c5ce7",a.font="11px system-ui",a.fillText("(Full screenshot unavailable \u2014 context sent as metadata)",20,130),o.toDataURL("image/png")):null}function Fe(t,e,s){if(e>s)return null;try{let o=t.cloneNode(!1);if(o.tagName==="SCRIPT"||o.tagName==="STYLE"||o.tagName==="SVG"||o.tagName==="CANVAS"||o.tagName==="VIDEO"||o.tagName==="IFRAME")return null;let a=window.getComputedStyle(t),r=["display","position","width","height","margin","padding","color","background-color","background","font-size","font-weight","font-family","border","border-radius","flex-direction","justify-content","align-items","gap","grid-template-columns","text-align","overflow"],i="";for(let u of r){let c=a.getPropertyValue(u);c&&c!=="normal"&&c!=="none"&&c!=="auto"&&c!=="0px"&&(i+=`${u}:${c};`)}o.setAttribute("style",i);for(let u=0;u<t.children.length&&u<20;u++){let c=Fe(t.children[u],e+1,s);c&&o.appendChild(c)}return o}catch{return null}}var ce=[];var We=!1;function Ge(){if(We)return;We=!0;let t=window.fetch;window.fetch=async function(...o){let a=new Request(...o),r={method:a.method,url:a.url,timestamp:Date.now()};try{let i=await t.apply(this,o);return r.status=i.status,r.duration=Date.now()-r.timestamp,Ee(r),i}catch(i){throw r.status=0,r.duration=Date.now()-r.timestamp,Ee(r),i}};let e=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(o,a,...r){return this.__om_method=o,this.__om_url=a,this.__om_start=Date.now(),e.apply(this,[o,a,...r])},XMLHttpRequest.prototype.send=function(...o){return this.addEventListener("loadend",()=>{Ee({method:this.__om_method||"GET",url:this.__om_url||"",status:this.status,duration:Date.now()-(this.__om_start||Date.now()),timestamp:this.__om_start||Date.now()})}),s.apply(this,o)}}function Ee(t){t.url.includes("__openmagic__")||(ce.push(t),ce.length>50&&ce.shift())}function pe(){return[...ce]}var de=[],ut=100,Ue=!1;function Ve(){if(Ue)return;Ue=!0;let t=["log","warn","error","info","debug"];for(let e of t){let s=console[e];console[e]=function(...o){de.push({level:e,args:o.map(a=>{try{return typeof a=="object"?JSON.stringify(a).slice(0,500):String(a)}catch{return String(a)}}),timestamp:Date.now()}),de.length>ut&&de.shift(),s.apply(console,o)}}}function me(){return[...de]}function Ke(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:pe().map(s=>({method:s.method,url:s.url,status:s.status,duration:s.duration,timestamp:s.timestamp})),consoleLogs:me().map(s=>({level:s.level,args:s.args,timestamp:s.timestamp}))}}var T={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>'},X={"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 he(t){let e=new TextEncoder().encode(t),s="";for(let o=0;o<e.length;o+=32768)s+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(s)}function Q(t){let e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);return new TextDecoder().decode(s)}var He="0.37.0",n={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},I,D,J,et,Pe,W;function ht(){try{let t=n.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 o=JSON.parse(Q(s.content.slice(8)));return{...s,content:`Applied ${o.type||"edit"} to ${o.file||"file"}`}}catch{return s}return s});sessionStorage.setItem("__om_state__",JSON.stringify({messages:e,provider:n.provider,model:n.model,panelOpen:n.panelOpen,activePanel:n.activePanel}))}catch{}}function gt(){try{let t=JSON.parse(sessionStorage.getItem("__om_state__")||"{}");t.messages?.length&&(n.messages=t.messages),t.provider&&(n.provider=t.provider),t.model&&(n.model=t.model),t.panelOpen&&(n.panelOpen=t.panelOpen,n.activePanel=t.activePanel||"")}catch{}}function Xe(){if(document.querySelector("openmagic-toolbar"))return;gt();let t=document.createElement("openmagic-toolbar");t.dataset.openmagic="true",I=t.attachShadow({mode:"closed"});let e=document.createElement("style");e.textContent=Re,I.appendChild(e);let s=document.createElement("div");I.appendChild(s),s.innerHTML=ft(),D=s.querySelector(".om-toolbar"),J=s.querySelector(".om-prompt-input"),et=s.querySelector(".om-prompt-context"),Pe=s.querySelector(".om-panel"),W=s.querySelector(".om-panel-body"),document.body.appendChild(t),yt(s),Tt();try{let i=JSON.parse(localStorage.getItem("__om_pos__")||"");i?.left&&i?.top&&(D.style.left=i.left,D.style.top=i.top,D.style.right="auto",D.style.bottom="auto")}catch{}Ge(),Ve(),Pt();let a=document.querySelector("script[data-openmagic-token]")?.dataset.openmagicToken||window.__OPENMAGIC_TOKEN__,r=parseInt(window.location.port,10)||(window.location.protocol==="https:"?443:80);a&&Se(r,a).then(()=>(n.connected=!0,ge(),A("config.get"))).then(i=>{n.detectedClis=i.payload?.detectedClis||[];let u=i.payload?.provider||"",c=i.payload?.model||"";n.provider=n.provider||u,n.model=n.model||c,n.configuredProviders=i.payload?.apiKeys||{};for(let m of n.detectedClis)m.installed&&m.authenticated&&(n.configuredProviders[m.id]=!0);let p=X[n.provider];n.hasApiKey=!!(n.configuredProviders[n.provider]||p?.local),n.roots=i.payload?.roots||[],n.panelOpen&&n.activePanel?Z(n.activePanel):(!n.provider||!n.hasApiKey&&!Object.values(n.configuredProviders).some(Boolean)&&!p?.local)&&Z("settings"),ie()}).catch(()=>{n.connected=!1,ge()})}function ft(){return`
|
|
411
|
+
</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"),v=Math.min(window.devicePixelRatio||1,2);p.width=s*v,p.height=n*v,u.onload=()=>{URL.revokeObjectURL(m);let k=p.getContext("2d");if(!k){c(null);return}k.scale(v,v),k.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 bt(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 Ke(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=Ke(t.children[m],e+1,s);c&&n.appendChild(c)}return n}catch{return null}}var de=[];var Ge=!1;function Xe(){if(Ge)return;Ge=!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,Ee(i),r}catch(r){throw i.status=0,i.duration=Date.now()-i.timestamp,Ee(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",()=>{Ee({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 Ee(t){t.url.includes("__openmagic__")||(de.push(t),de.length>50&&de.shift())}function me(){return[...de]}var pe=[],xt=100,Ve=!1;function Je(){if(Ve)return;Ve=!0;let t=["log","warn","error","info","debug"];for(let e of t){let s=console[e];console[e]=function(...n){pe.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()}),pe.length>xt&&pe.shift(),s.apply(console,n)}}}function ue(){return[...pe]}function Ze(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:me().map(s=>({method:s.method,url:s.url,status:s.status,duration:s.duration,timestamp:s.timestamp})),consoleLogs:ue().map(s=>({level:s.level,args:s.args,timestamp:s.timestamp}))}}var C={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>'},V={"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 fe(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 te(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 _e="0.39.0",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},P,q,Z,st,Re,K;function at(){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(te(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 vt(){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 Ye(){if(document.querySelector("openmagic-toolbar"))return;vt();let t=document.createElement("openmagic-toolbar");t.dataset.openmagic="true",P=t.attachShadow({mode:"closed"});let e=document.createElement("style");e.textContent=Ie,P.appendChild(e);let s=document.createElement("div");P.appendChild(s),s.innerHTML=wt(),q=s.querySelector(".om-toolbar"),Z=s.querySelector(".om-prompt-input"),st=s.querySelector(".om-prompt-context"),Re=s.querySelector(".om-panel"),K=s.querySelector(".om-panel-body"),document.body.appendChild(t),kt(s),Rt();try{let r=JSON.parse(localStorage.getItem("__om_pos__")||"");r?.left&&r?.top&&(q.style.left=r.left,q.style.top=r.top,q.style.right="auto",q.style.bottom="auto")}catch{}Xe(),Je(),It();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&&$e(i,a).then(()=>(o.connected=!0,ge(),A("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=V[o.provider];o.hasApiKey=!!(o.configuredProviders[o.provider]||u?.local),o.roots=r.payload?.roots||[],o.panelOpen&&o.activePanel?Y(o.activePanel):(!o.provider||!o.hasApiKey&&!Object.values(o.configuredProviders).some(Boolean)&&!u?.local)&&Y("settings"),ce(),rt()}).catch(()=>{o.connected=!1,ge()})}function wt(){return`
|
|
394
412
|
<div class="om-toolbar">
|
|
395
413
|
<div class="om-toolbar-header">
|
|
396
|
-
<span class="om-grab">${
|
|
414
|
+
<span class="om-grab">${C.grip}</span>
|
|
397
415
|
<span class="om-pill-brand">
|
|
398
416
|
<span class="om-pill-text">\u2728OpenMagic\u{1FA84}</span>
|
|
399
417
|
</span>
|
|
400
418
|
<span class="om-pill-divider"></span>
|
|
401
|
-
<button class="om-pill-btn" data-action="select" title="Select element">${
|
|
402
|
-
<button class="om-pill-btn" data-action="screenshot" title="Screenshot">${
|
|
403
|
-
<button class="om-pill-btn" data-action="network" title="Network & Performance">${
|
|
419
|
+
<button class="om-pill-btn" data-action="select" title="Select element">${C.crosshair}</button>
|
|
420
|
+
<button class="om-pill-btn" data-action="screenshot" title="Screenshot">${C.camera}</button>
|
|
421
|
+
<button class="om-pill-btn" data-action="network" title="Network & Performance">${C.activity}</button>
|
|
404
422
|
<span class="om-pill-divider"></span>
|
|
405
|
-
<button class="om-pill-btn" data-action="chat" title="Chat">${
|
|
406
|
-
<button class="om-pill-btn" data-action="settings" title="Settings">${
|
|
407
|
-
<button class="om-pill-btn" data-action="minimize" title="Minimize">${
|
|
423
|
+
<button class="om-pill-btn" data-action="chat" title="Chat">${C.chat}</button>
|
|
424
|
+
<button class="om-pill-btn" data-action="settings" title="Settings">${C.settings}</button>
|
|
425
|
+
<button class="om-pill-btn" data-action="minimize" title="Minimize">${C.minus}</button>
|
|
408
426
|
<span class="om-status-dot disconnected"></span>
|
|
409
427
|
</div>
|
|
410
428
|
<div class="om-panel om-hidden">
|
|
411
429
|
<div class="om-panel-header">
|
|
412
430
|
<span class="om-panel-title"></span>
|
|
413
|
-
<span class="om-panel-version">v${
|
|
414
|
-
<button class="om-panel-bug" data-action="report-issue" title="Report a bug on GitHub">${
|
|
415
|
-
<button class="om-panel-clear" data-action="clear-chat" title="Clear chat">${
|
|
416
|
-
<button class="om-panel-close" data-action="close-panel">${
|
|
431
|
+
<span class="om-panel-version">v${_e}</span>
|
|
432
|
+
<button class="om-panel-bug" data-action="report-issue" title="Report a bug on GitHub">${C.bug}</button>
|
|
433
|
+
<button class="om-panel-clear" data-action="clear-chat" title="Clear chat">${C.trash}</button>
|
|
434
|
+
<button class="om-panel-close" data-action="close-panel">${C.x}</button>
|
|
417
435
|
</div>
|
|
418
436
|
<div class="om-panel-body"></div>
|
|
419
437
|
</div>
|
|
@@ -427,39 +445,42 @@
|
|
|
427
445
|
<div class="om-prompt-attachments"></div>
|
|
428
446
|
<div class="om-prompt-row">
|
|
429
447
|
<div class="om-prompt-context"></div>
|
|
430
|
-
<
|
|
448
|
+
<select class="om-model-switcher" data-field="quick-model" title="Switch model"></select>
|
|
449
|
+
<button class="om-prompt-attach" data-action="attach-image" title="Attach image">${C.paperclip}</button>
|
|
431
450
|
<input class="om-prompt-input" type="text" placeholder="Describe what to change..." autocomplete="off" />
|
|
432
|
-
<button class="om-prompt-send" data-action="prompt-send">${
|
|
451
|
+
<button class="om-prompt-send" data-action="prompt-send">${C.send}</button>
|
|
433
452
|
<input type="file" class="om-file-input om-hidden" accept="image/*" multiple />
|
|
434
453
|
</div>
|
|
435
|
-
</div>`}function
|
|
436
|
-
`).map(
|
|
437
|
-
`)
|
|
438
|
-
|
|
439
|
-
`)
|
|
440
|
-
|
|
454
|
+
</div>`}function kt(t){t.addEventListener("click",n=>{let a=n.target.closest("[data-action]");if(!a)return;n.preventDefault(),n.stopPropagation();let i=a.dataset.action;nt(i,a)}),t.addEventListener("change",n=>{let a=n.target,i=a.dataset.field;i&&(i==="provider"?(o.provider=a.value,o.model=V[o.provider]?.models[0]?.id||"",o.hasApiKey=o.configuredProviders[o.provider]||V[o.provider]?.local||!1,o.saveStatus="",O()):i==="model"?o.model=a.value:i==="quick-model"&&(o.model=a.value,at()))}),Z.addEventListener("keydown",n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),He())});let e=t.querySelector(".om-file-input");e&&e.addEventListener("change",()=>{Te(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&&Te(a.files)}),Z.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 m=new DataTransfer;m.items.add(r),Te(m.files)}}}})),je(n=>{n.type==="reconnected"&&(o.connected=!0,ge())}),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,q.querySelectorAll(".om-pill-btn:not([data-action='minimize']), .om-pill-divider, .om-status-dot").forEach(r=>r.style.display="");let i=P.querySelector(".om-prompt-row");i&&i.classList.remove("om-hidden")}else o.panelOpen?ye():Y("chat");return}if((n.ctrlKey||n.metaKey)&&(n.key==="k"||n.key==="K")&&!n.shiftKey){n.preventDefault(),o.panelOpen||Y("chat"),Z.focus();return}if((n.ctrlKey||n.metaKey)&&(n.key==="z"||n.key==="Z")&&!n.shiftKey&&(P.activeElement||o.panelOpen)){let a=P.querySelector('[data-action="undo-diff"]');if(a){n.preventDefault(),it(a);return}}if((n.ctrlKey||n.metaKey)&&n.key==="."){let a=P.querySelector('[data-action="apply-all"]');if(a&&!P.querySelector(".om-apply-bar.om-hidden")){n.preventDefault(),nt("apply-all",a);return}}if(n.key==="Escape"){if(o.selecting)return;o.panelOpen&&(ye(),n.preventDefault())}}),Z.addEventListener("keydown",n=>{(n.ctrlKey||n.metaKey)&&n.key==="Enter"&&(n.preventDefault(),He())})}function Ae(t){return o.roots.length>0?o.roots[0]+"/"+t:t}function St(t,e){let s=e.split(`
|
|
455
|
+
`),n=s.map(l=>l.trim()).filter(l=>l.length>0);if(n.length===0)return null;let a=t.split(`
|
|
456
|
+
`);for(let l=0;l<=a.length-n.length;l++){let f=!0,g=0,h=0;for(let d=l;d<a.length&&h<n.length;d++){if(a[d].trim()===""){g++;continue}if(a[d].trim()!==n[h]){f=!1;break}h++,g++}if(f&&h===n.length)return Le(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 Le(t,a,l,i.length)}let r=n.join(`
|
|
457
|
+
`).toLowerCase(),m=n.length,c=0,u=-1,p=0,v=Math.max(1,Math.floor(m*.8)),k=Math.min(a.length,Math.ceil(m*1.2));for(let l=v;l<=k;l++)for(let f=0;f<=a.length-l;f++){let g=a.slice(f,f+l).map(d=>d.trim()).filter(d=>d).join(`
|
|
458
|
+
`).toLowerCase(),h=$t(r,g);h>c&&(c=h,u=f,p=l)}return c>=.8&&u>=0?Le(t,a,u,p):null}function Le(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]===`
|
|
459
|
+
`&&i--,{start:a,end:i}}function $t(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 Qe(t){let e=t.dataset.file,s=t.dataset.search,n=t.dataset.replace;if(!e||!s||!n)return;t.disabled=!0,t.innerHTML='<span class="om-spinner"></span>',t.style.opacity="0.5",t.style.pointerEvents="none";let a=t.closest(".om-diff-card");if(a){let c=a.querySelector(".om-diff-actions");c&&(c.innerHTML='<span class="om-spinner"></span> Applying...')}await new Promise(c=>requestAnimationFrame(c));let i,r;try{i=te(s),r=te(n)}catch{o.messages.push({role:"system",content:`Failed to decode diff data for ${e}`}),O();return}let m=Ae(e);try{if(!i&&r){if((await A("fs.write",{path:m,content:r}))?.payload?.ok===!1)o.messages.push({role:"system",content:`Write failed: ${e}`});else{let g=a?.dataset.diffIdx;g!==void 0?o.messages[parseInt(g)]={role:"system",content:`Created ${e}`}:o.messages.push({role:"system",content:`Created ${e}`})}O(),se();return}let c,u=m,p=[m];e!==m&&p.push(e);let v=e.split("/").pop()||e,k=o.roots[0]||"",l=k?`${k}/${v}`:v;l!==m&&l!==e&&p.push(l);for(let f of p){let h=(await A("fs.read",{path:f}).catch(()=>null))?.payload?.content;if(h!=null&&String(h).length>0){c=String(h),u=f;break}}if(!c)o.messages.push({role:"system",content:`Could not read ${e} \u2014 tried: ${p.join(", ")}`});else{let f=c.split(i).length-1;if(f===1){let g=await A("fs.write",{path:u,content:c.replace(i,r)});if(g?.payload?.ok===!1)o.messages.push({role:"system",content:`Write failed: ${e} - ${g.payload?.error||"unknown"}`});else{let h=a?.dataset.diffIdx;h!==void 0?o.messages[parseInt(h)]={role:"system",content:`Applied change to ${e}. Reloading...`}:o.messages.push({role:"system",content:`Applied change to ${e}. Reloading...`})}}else if(f>1)o.messages.push({role:"system",content:`Found ${f} exact matches in ${e} \u2014 expected 1. Edit not applied.`});else{let g=St(c,i);if(g){let h=c.slice(0,g.start)+r+c.slice(g.end),d=await A("fs.write",{path:u,content:h});if(d?.payload?.ok===!1)o.messages.push({role:"system",content:`Write failed: ${e} - ${d.payload?.error||"unknown"}`});else{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 o.messages.push({role:"system",content:`No matching code found in ${e}. The file may have changed since the suggestion.`})}}}catch(c){o.messages.push({role:"system",content:`Failed to apply: ${e} \u2014 ${c.message}`})}O(),se(),setTimeout(()=>{window.location.reload()},1500)}function et(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(te(o.messages[s]?.content.slice(8)||"")),a=(n.search||"").split(`
|
|
460
|
+
`)[0].slice(0,80),i=(n.replace||"").split(`
|
|
461
|
+
`)[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"}}}O(),se()}function Mt(t){let e=P.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 tt(){let t=P.querySelector(".om-apply-bar");t&&t.classList.add("om-hidden")}async function it(t){let e=t.dataset.file;if(!e)return;let s=Ae(e);try{(await A("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`})}O()}async function nt(t,e){switch(t){case"select":Pt();break;case"screenshot":_t();break;case"chat":Ce("chat");break;case"settings":Ce("settings");break;case"close-panel":ye();break;case"prompt-send":He();break;case"save-settings":Ct();break;case"get-key":{let s=e.dataset.url;s&&window.open(s,"_blank","noopener");break}case"change-key":{let s=P.querySelector("[data-key-change]");s&&s.classList.remove("om-hidden"),e.style.display="none";break}case"network":Ce("chat"),Tt();break;case"attach-image":Ht();break;case"remove-attachment":{let s=parseInt(e.dataset.idx||"0",10);o.attachments.splice(s,1),Ne();break}case"apply-diff":Qe(e);break;case"reject-diff":et(e);break;case"apply-all":{let s=Array.from(P.querySelectorAll('[data-action="apply-diff"]'));if(s.length===0)break;let n=new Set;for(let r of s){let m=r.dataset.file;m&&n.add(Ae(m))}let a=new Map;for(let r of n)try{let m=await A("fs.read",{path:r}).catch(()=>null);m?.payload?.content&&a.set(r,String(m.payload.content))}catch{}let i=!1;for(let r of s)try{await Qe(r)}catch{i=!0;break}if(i&&a.size>0){for(let[r,m]of a)try{await A("fs.write",{path:r,content:m})}catch{}o.messages.push({role:"system",content:"Batch apply failed \u2014 all changes reverted."}),O()}tt();break}case"reject-all":{let s=P.querySelectorAll('[data-action="reject-diff"]');for(let n of Array.from(s))et(n);tt();break}case"undo-diff":it(e);break;case"clear-chat":{o.messages=[];try{sessionStorage.removeItem("__om_state__")}catch{}O();break}case"copy-msg":{let s=parseInt(e.dataset.idx||"0",10);e.innerHTML='<span class="om-spinner"></span>',ot(s).then(n=>{try{navigator.clipboard.writeText(n)}catch{}e.innerHTML=C.check,setTimeout(()=>{e.innerHTML=C.copy},1500)});break}case"report-issue":{e.innerHTML='<span class="om-spinner"></span>',ot().then(s=>{try{navigator.clipboard.writeText(s)}catch{}e.innerHTML=C.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&&O()});break}case"clear-element":o.selectedElement=null,le();break;case"clear-screenshot":o.screenshot=null,le();break;case"minimize":{o.minimized=!o.minimized;let s=P.querySelector(".om-panel"),n=P.querySelector(".om-prompt-row"),a=P.querySelector(".om-prompt-attachments"),i=q.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 ge(){let t=P.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 ce(){P.querySelectorAll(".om-pill-btn").forEach(t=>{let e=t.dataset.action;t.classList.toggle("active",e===o.activePanel||e==="select"&&o.selecting)})}function rt(){let t=P.querySelector(".om-model-switcher");if(!t)return;let e=V[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 le(){let t=[];o.selectedElement&&t.push(`<span class="om-prompt-chip">${o.selectedElement.tagName}${o.selectedElement.id?"#"+o.selectedElement.id:""} <button class="om-prompt-chip-x" data-action="clear-element">${C.x}</button></span>`),o.screenshot&&t.push(`<span class="om-prompt-chip">Screenshot <button class="om-prompt-chip-x" data-action="clear-screenshot">${C.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>`)}st.innerHTML=t.join("")}function Y(t){o.panelOpen=!0,o.activePanel=t,Re.classList.remove("om-hidden");let e=P.querySelector(".om-panel-title");e&&(e.textContent=t==="settings"?"Settings":"Chat"),O(),ce()}function ye(){o.panelOpen=!1,o.activePanel="",Re.classList.add("om-hidden"),ce()}function Ce(t){o.panelOpen&&o.activePanel===t?ye():Y(t)}function O(){o.activePanel==="settings"?K.innerHTML=Et():o.activePanel==="chat"&&(K.innerHTML=Lt(),se()),at()}function Et(){let t=Object.entries(V).map(([l,f])=>{let g=o.detectedClis.find(d=>d.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=V[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,m=o.updateAvailable?`<div class="om-update-banner">v${o.latestVersion} available <code class="om-update-cmd">npx openmagic@latest</code></div>`:"",c=r||n?`<div class="om-status om-status-success">${C.check} ${e?.name||"Provider"} connected</div>`:"",u=o.saveStatus==="saving"?'<span class="om-spinner"></span> Saving...':o.saveStatus==="saved"?`${C.check} Saved`:"Save",p=o.saveStatus==="saving"?"om-btn om-btn-saving":o.saveStatus==="saved"?"om-btn om-btn-saved":"om-btn",v=o.saveStatus==="saving"?"disabled":"",k="";return!n&&o.provider&&(r?k=`
|
|
441
462
|
<div class="om-field">
|
|
442
463
|
<label class="om-label">API Key</label>
|
|
443
464
|
<div class="om-key-configured">
|
|
444
|
-
${
|
|
465
|
+
${C.check} <span>Key configured</span>
|
|
445
466
|
<button class="om-btn-change-key" data-action="change-key">Change</button>
|
|
446
467
|
</div>
|
|
447
468
|
<div class="om-key-change-row om-hidden" data-key-change>
|
|
448
469
|
<div class="om-key-row">
|
|
449
|
-
<input type="text" class="om-input om-key-input" data-field="apiKey" placeholder="${
|
|
450
|
-
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${
|
|
470
|
+
<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" />
|
|
471
|
+
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${C.externalLink} Get key</button>`:""}
|
|
451
472
|
</div>
|
|
452
473
|
</div>
|
|
453
|
-
</div>`:
|
|
474
|
+
</div>`:k=`
|
|
454
475
|
<div class="om-field">
|
|
455
476
|
<label class="om-label">API Key</label>
|
|
456
477
|
<div class="om-key-row">
|
|
457
|
-
<input type="text" class="om-input om-key-input" data-field="apiKey" placeholder="${
|
|
458
|
-
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${
|
|
478
|
+
<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" />
|
|
479
|
+
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${C.externalLink} Get key</button>`:""}
|
|
459
480
|
</div>
|
|
460
481
|
${a?`<div class="om-key-hint"><a data-action="get-key" data-url="${a}">Get your ${e?.name||""} API key here</a></div>`:""}
|
|
461
482
|
</div>`),`
|
|
462
|
-
${
|
|
483
|
+
${m}
|
|
463
484
|
<div class="om-settings">
|
|
464
485
|
<div class="om-field">
|
|
465
486
|
<label class="om-label">Provider</label>
|
|
@@ -469,31 +490,32 @@
|
|
|
469
490
|
<label class="om-label">Model</label>
|
|
470
491
|
<select class="om-select" data-field="model"><option value="">Select Model...</option>${s}</select>
|
|
471
492
|
</div>
|
|
472
|
-
${
|
|
473
|
-
<button class="${
|
|
493
|
+
${k}
|
|
494
|
+
<button class="${p}" data-action="save-settings" ${v}>${u}</button>
|
|
474
495
|
${c}
|
|
475
|
-
</div>`}function
|
|
476
|
-
<div class="om-diff-file">${
|
|
477
|
-
|
|
478
|
-
<div class="om-diff-added">${K((i.replace||"").slice(0,300))}</div>
|
|
496
|
+
</div>`}function Lt(){if(!o.provider||!o.hasApiKey&&!V[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(te(n.content.slice(8))),m=r.type==="create"||!r.search&&r.replace,c=fe(r.search||""),u=fe(r.replace||""),p=m?"Create new file":"Edit",v=At(r.search||"",r.replace||"");return`<div class="om-diff-card" data-diff-idx="${a}">
|
|
497
|
+
<div class="om-diff-file">${W(p)}: ${W(r.file)}</div>
|
|
498
|
+
<div class="om-diff-lines">${v}</div>
|
|
479
499
|
<div class="om-diff-actions">
|
|
480
|
-
<button class="om-btn om-btn-sm" data-action="apply-diff" data-file="${
|
|
500
|
+
<button class="om-btn om-btn-sm" data-action="apply-diff" data-file="${W(r.file)}" data-search="${c}" data-replace="${u}">Apply</button>
|
|
481
501
|
<button class="om-btn-secondary om-btn-sm" data-action="reject-diff" data-idx="${a}">Reject</button>
|
|
482
502
|
</div>
|
|
483
|
-
</div>`}catch{return'<div class="om-msg om-msg-system">Malformed diff data</div>'}if(
|
|
484
|
-
// [FILE TRUNCATED \u2014 showing ${
|
|
485
|
-
// [FILE TRUNCATED \u2014 showing ${
|
|
486
|
-
// [TRUNCATED]`),$.push({path:
|
|
487
|
-
// [FILE TRUNCATED \u2014 showing ${
|
|
488
|
-
/* [TRUNCATED] */`),$.push({path:
|
|
489
|
-
All network requests (${
|
|
490
|
-
Fetch/XHR requests (${a.length}):`);for(let c of a.slice(-20))
|
|
491
|
-
Console errors: ${c.length}`),
|
|
492
|
-
Slowest resources:`);for(let
|
|
493
|
-
`)}),
|
|
503
|
+
</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">${W(n.content)} <button class="om-undo-btn" data-action="undo-diff" data-file="${W(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">${C.copy}</button>`:"";return n.role==="assistant"?`<div class="om-msg om-msg-assistant">${Nt(n.content)}${i}</div>`:`<div class="om-msg om-msg-${n.role}">${W(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 se(){requestAnimationFrame(()=>{let t=K.querySelector(".om-chat-messages");t&&(t.scrollTop=t.scrollHeight)})}async function Ct(){let e=K.querySelector('[data-field="apiKey"]')?.value||"";if(!o.provider){o.saveStatus="error",he(),setTimeout(()=>{o.saveStatus="",O()},2e3);return}if(!Me()){o.saveStatus="error",he();let n=K.querySelector('[data-action="save-settings"]');n&&(n.innerHTML="Not connected - check terminal"),setTimeout(()=>{o.saveStatus="",O()},3e3);return}let s={provider:o.provider,model:o.model};e&&(s.apiKey=e),o.saveStatus="saving",he();try{let n=await Promise.race([A("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",he(),rt(),setTimeout(()=>{o.saveStatus="",o.activePanel==="settings"&&Y("chat")},1200)}catch(n){o.saveStatus="error";let a=K.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="",O()},4e3)}}function he(){let t=K.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=`${C.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 He(){let t=Z.value.trim();if(!t||o.streaming)return;if(!o.provider||!o.hasApiKey&&!V[o.provider]?.local){Y("settings");return}o.messages.push({role:"user",content:t}),o.streaming=!0,o.streamContent="",Z.value="",Y("chat");let e=Ze(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=K.querySelector(".om-msg-assistant:last-child");i&&(i.innerHTML='<span class="om-spinner"></span> Reading project files...');try{let u=await A("fs.list",{});u?.payload?.projectTree&&(e.projectTree=u.payload.projectTree);let v=(u?.payload?.files||[]).filter(b=>b.type==="file"&&a.test(b.path)),k=[t];if(o.selectedElement&&(o.selectedElement.id&&k.push(o.selectedElement.id),o.selectedElement.className&&k.push(o.selectedElement.className),o.selectedElement.textContent&&k.push(o.selectedElement.textContent.slice(0,100)),o.selectedElement.componentHint&&k.push(o.selectedElement.componentHint),o.selectedElement.ancestry))for(let b of o.selectedElement.ancestry)k.push(b);let l=k.filter(Boolean).join(" ").toLowerCase().split(/[^a-z0-9_-]+/).filter(b=>b.length>=2&&!["the","to","in","of","and","div","span","class","style"].includes(b)),g=window.location.pathname.split("/").filter(b=>b.length>1&&!/^\d+$/.test(b)),h="";if(o.selectedElement?.componentHint||g.length){let b=(o.selectedElement?.componentHint||"").toLowerCase(),w=new Map;for(let H of v){let L=H.path.split("/")[0];if(!L||L.includes("."))continue;let j=H.path.toLowerCase(),z=w.get(L)||0;b&&j.includes(b)&&(z+=10);for(let X of g)j.includes(X.toLowerCase())&&(z+=5);/(component|page|route|layout)/.test(j)&&(z+=1),w.set(L,z)}let S=0;for(let[H,L]of w)L>S&&(S=L,h=H)}let d=v.map(b=>{let w=0,S=b.path.toLowerCase(),H=S.replace(/\([^)]+\)\//g,"");if(h){let L=b.path.split("/")[0];L===h?w+=20:L!==h&&!b.path.includes("/")?w+=0:w-=15}for(let L of g)H.includes(L.toLowerCase())&&(w+=15);if(o.selectedElement?.componentHint){let L=o.selectedElement.componentHint.toLowerCase();S.includes(L)&&(w+=12)}for(let L of l)S.includes(L)&&(w+=5);return/(component|page|route|layout|template|view)/.test(S)&&(w+=3),/page\.[jt]sx?$|layout\.[jt]sx?$|\+page\.svelte$/.test(S)&&(w+=5),{...b,score:w}}).sort((b,w)=>w.score-b.score),$=[],x=new Set,M=0,I=d.slice(0,s).filter(b=>b.score>0),D=o.roots[0]||"",Q=await Promise.all(I.map(b=>{let w=D?`${D}/${b.path}`:b.path;return A("fs.read",{path:w}).catch(()=>null)}));for(let b=0;b<I.length;b++){let w=I[b];if(M>=n)break;try{let S=String(Q[b]?.payload?.content||"");if(!S)continue;let H=Math.min(12e3,n-M),L=S.slice(0,H);S.length>H&&(L+=`
|
|
504
|
+
// [FILE TRUNCATED \u2014 showing ${H} of ${S.length} chars]`),$.push({path:w.path,content:L}),x.add(w.path),M+=L.length;let j=w.path.replace(/\.[^.]+$/,""),z=[".module.css",".module.scss",".css",".scss",".styles.ts"];for(let ee of z){let y=j+ee;if(x.has(y)||M>=n)continue;if(v.find(_=>_.path===y)){try{let _=await A("fs.read",{path:D?`${D}/${y}`:y}),T=String(_?.payload?.content||"");if(T){let N=Math.min(4e3,n-M),R=T.slice(0,N);T.length>N&&(R+=`
|
|
505
|
+
// [FILE TRUNCATED \u2014 showing ${N} of ${T.length} chars]`),$.push({path:y,content:R}),x.add(y),M+=R.length}}catch{}break}}if($.length<=2&&M<n){let ee=["layout.tsx","layout.jsx","layout.js","layout.ts"],y=w.path.replace(/\/[^/]+$/,""),E=0;for(;y&&E<4&&M<n;){let _=!1;for(let N of ee){let R=`${y}/${N}`;if(x.has(R)){_=!0;break}try{let J=await A("fs.read",{path:D?`${D}/${R}`:R}).catch(()=>null),G=String(J?.payload?.content||"");if(G){let ne=Math.min(4e3,n-M),xe=G.slice(0,ne);G.length>ne&&(xe+=`
|
|
506
|
+
// [TRUNCATED]`),$.push({path:R,content:xe}),x.add(R),M+=xe.length,_=!0;break}}catch{}}let T=y.replace(/\/[^/]+$/,"");if(T===y||!T)break;y=T,E++}}let X=S.matchAll(/(?:import|from)\s+['"]\.?\.\/([\w/.-]+)['"]/g);for(let ee of X){if(M>=n)break;let y=ee[1],E=w.path.replace(/\/[^/]+$/,""),_=[`${E}/${y}`,`${E}/${y}.tsx`,`${E}/${y}.ts`,`${E}/${y}.jsx`,`${E}/${y}.js`,`${E}/${y}/index.tsx`,`${E}/${y}/index.ts`];for(let T of _){if(x.has(T))break;if(v.find(R=>R.path===T)){try{let R=await A("fs.read",{path:D?`${D}/${T}`:T}),J=String(R?.payload?.content||"");if(J){let G=Math.min(8e3,n-M),ne=J.slice(0,G);J.length>G&&(ne+=`
|
|
507
|
+
// [FILE TRUNCATED \u2014 showing ${G} of ${J.length} chars]`),$.push({path:T,content:ne}),x.add(T),M+=ne.length}}catch{}break}}}}catch{}}if(M<n)try{let b=o.roots[0]||"",w=await A("fs.read",{path:b?`${b}/package.json`:"package.json"}),S=String(w?.payload?.content||"");if(S)try{let H=JSON.parse(S),L={...H.dependencies,...H.devDependencies},j=JSON.stringify(L,null,2);$.push({path:"package.json (dependencies)",content:j.slice(0,2e3)})}catch{$.push({path:"package.json",content:S.slice(0,2e3)})}}catch{}if(M<n){let b=o.roots[0]||"",w=["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 S of w)if(!(M>=n||x.has(S)))try{let H=b?`${b}/${S}`:S,L=await A("fs.read",{path:H}).catch(()=>null),j=String(L?.payload?.content||"");if(j){let z=Math.min(12e3,n-M),X=j.slice(0,z);j.length>z&&(X+=`
|
|
508
|
+
/* [TRUNCATED] */`),$.push({path:S,content:X}),x.add(S),M+=X.length}}catch{}}if($.length){e.files=$;let b=$.map(w=>w.path.split("/").pop()).join(", ");i&&(i.innerHTML=`<span class="om-spinner"></span> Thinking... (${$.length} files: ${b})`)}o.groundedFiles=$.map(b=>b.path)}catch{}let r=4,m=0,c=new Set;try{for(;m<=r;){o.streamContent="";let u=await qe("llm.chat",{provider:o.provider,model:o.model,messages:o.messages.map(d=>({role:d.role,content:d.content})),context:e},d=>{o.streamContent+=d}),p=o.streamContent||u?.content||"",v=p;try{let d=JSON.parse(p);d.explanation&&(v=d.explanation)}catch{let d=p.match(/```(?:json)?\s*([\s\S]*?)```/);if(d)try{let $=JSON.parse(d[1]);$.explanation&&(v=$.explanation)}catch{}}let k=u?.modifications?.some(d=>d.type==="edit"&&d.file&&d.search&&d.replace||d.type==="create"&&d.file&&d.content),l=!k&&(v.match(/NEED_FILE:\s*"?([^\s"}\]]+)"?/)||v.match(/(?:need|provide|show|read|see|contents?\s+of)\s+(?:the\s+)?(?:file\s+)?[`"']?([a-zA-Z0-9_/.@-]+\.[a-z]{1,5})[`"']?/i)||v.match(/(?:source\s+(?:file|code)\s+(?:for|of|at))\s+[`"']?([a-zA-Z0-9_/.@-]+\.[a-z]{1,5})[`"']?/i)||p.match(/NEED_FILE:\s*\\?"?([^\s"\\}\]]+)"?/));if(l&&m<r&&!c.has(l[1].trim())){let d=l[1].trim();c.add(d),m++;let $=K.querySelector(".om-msg-assistant:last-child");$&&($.innerHTML=`<span class="om-spinner"></span> Reading ${d}...`);try{let x=o.roots[0]||"",M=x?`${x}/${d}`:d,I,D=[M];d!==M&&D.push(d);let Q=d.split("/").pop()||d,b=x?`${x}/${Q}`:Q;b!==M&&b!==d&&D.push(b);for(let w of D){let S=await A("fs.read",{path:w}).catch(()=>null);if(S?.payload?.content){I=String(S.payload.content);break}}if(I){e.files||(e.files=[]);let w=e.files.findIndex(H=>H.path===d||H.path.endsWith("/"+d)||d.endsWith("/"+H.path)),S=I.slice(0,16e3);w>=0?e.files[w]={path:d,content:S}:e.files.push({path:d,content:S})}else{o.messages.push({role:"system",content:`Could not read ${d}`});break}}catch{o.messages.push({role:"system",content:`File not found: ${d}`});break}continue}let f=!k&&(v.match(/SEARCH_FILES:\s*"([^"]+)"(?:\s+in\s+(\S+))?/)||p.match(/SEARCH_FILES:\s*\\?"([^"\\]+)\\?"(?:\s+in\s+(\S+))?/)),g=e.searchResults?.some(d=>d.query===f?.[1]);if(f&&m<r&&!g){let d=f[1],$=f[2]||"";m++;let x=K.querySelector(".om-msg-assistant:last-child");x&&(x.innerHTML=`<span class="om-spinner"></span> Searching: "${d}"...`);try{let I=(await Promise.race([A("fs.grep",{pattern:d,path:$}),new Promise((D,Q)=>setTimeout(()=>Q(new Error("grep timeout")),5e3))]))?.payload?.results||[];I.length&&(e.searchResults||(e.searchResults=[]),e.searchResults.push({query:d,matches:I}))}catch{}continue}let h=v.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}),u?.modifications?.length){let d=Math.random().toString(36).slice(2),$=u.modifications.filter(x=>x.type==="edit"&&x.file&&x.search&&x.replace||x.type==="create"&&x.file&&x.content);Mt($.length);for(let x of u.modifications)if(x.type==="edit"&&x.file&&x.search&&x.replace){let M=Math.random().toString(36).slice(2),I=JSON.stringify({id:M,file:x.file,search:x.search,replace:x.replace,groupId:d});o.messages.push({role:"system",content:`__DIFF__${fe(I)}`})}else if(x.type==="create"&&x.file&&x.content){let M=Math.random().toString(36).slice(2),I=JSON.stringify({id:M,file:x.file,search:"",replace:x.content,type:"create",groupId:d});o.messages.push({role:"system",content:`__DIFF__${fe(I)}`})}else x.type==="delete"&&x.file&&o.messages.push({role:"system",content:`LLM proposed deleting ${x.file} \u2014 skipped (use edit with search/replace instead)`})}break}}catch(u){o.streamContent.trim().length>20?(o.messages.push({role:"assistant",content:o.streamContent.trim()}),o.messages.push({role:"system",content:`Response interrupted: ${u.message}. Partial response shown above.`})):o.messages.push({role:"system",content:`Error: ${u.message}`})}o.streaming=!1,o.streamContent="",o.attachments=[],Ne(),O(),se()}function Tt(){let t=window.performance,e=t.getEntriesByType("navigation")[0],s=t.getEntriesByType("paint"),n=t.getEntriesByType("resource").slice(-20),a=me(),i=ue(),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 m=s.find(c=>c.name==="first-contentful-paint");if(m&&r.push(`FCP: ${Math.round(m.startTime)}ms`),n.length){let c=n.filter(p=>p.initiatorType==="fetch"||p.initiatorType==="xmlhttprequest"),u=c.length>0?c:n;r.push(`
|
|
509
|
+
All network requests (${u.length}):`);for(let p of u.slice(-30)){let v=p.name.length>80?"..."+p.name.slice(-77):p.name,k=p.responseStatus||"";r.push(` ${Math.round(p.duration)}ms ${k?`[${k}]`:""} ${v}`)}}if(a.length){r.push(`
|
|
510
|
+
Fetch/XHR requests (${a.length}):`);for(let c of a.slice(-20))r.push(` ${c.method} ${c.url.slice(0,80)} \u2192 ${c.status||"pending"} (${c.duration||"?"}ms)`)}if(i.length){let c=i.filter(p=>p.level==="error"),u=i.filter(p=>p.level==="warn");c.length&&r.push(`
|
|
511
|
+
Console errors: ${c.length}`),u.length&&r.push(`Console warnings: ${u.length}`)}if(n.length>5){let c=[...n].sort((u,p)=>p.duration-u.duration).slice(0,5);r.push(`
|
|
512
|
+
Slowest resources:`);for(let u of c)r.push(` ${Math.round(u.duration)}ms \u2014 ${u.name.split("/").pop()?.slice(0,60)}`)}o.messages.push({role:"system",content:r.join(`
|
|
513
|
+
`)}),O(),se(),le()}function Ht(){let t=P.querySelector(".om-file-input");t&&t.click()}function Te(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),Ne())},n.readAsDataURL(s)}}function Ne(){let t=P.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">
|
|
494
514
|
<img src="${e}" alt="attachment" />
|
|
495
|
-
<button class="om-attachment-remove" data-action="remove-attachment" data-idx="${s}">${
|
|
496
|
-
</div>`).join("")}}var
|
|
497
|
-
`),
|
|
498
|
-
`)
|
|
515
|
+
<button class="om-attachment-remove" data-action="remove-attachment" data-idx="${s}">${C.x}</button>
|
|
516
|
+
</div>`).join("")}}var ie=null,re=null;function Pt(){o.selecting?Pe():be()}function be(){o.selecting=!0,document.body.style.cursor="crosshair",ce(),re=e=>{let s=e.target;if(s.closest("openmagic-toolbar")||s.dataset?.openmagic)return;let n=s.getBoundingClientRect();Fe({x:n.x,y:n.y,width:n.width,height:n.height})},ie=e=>{e.preventDefault(),e.stopPropagation();let s=e.target;s.closest("openmagic-toolbar")||s.dataset?.openmagic||(o.selectedElement=Be(s),Pe(),le(),Z.focus())};let t=e=>{e.key==="Escape"&&Pe()};document.addEventListener("mousemove",re,!0),document.addEventListener("click",ie,!0),document.addEventListener("keydown",t,!0),be._escHandler=t}function Pe(){o.selecting=!1,document.body.style.cursor="",We(),re&&(document.removeEventListener("mousemove",re,!0),re=null),ie&&(document.removeEventListener("click",ie,!0),ie=null);let t=be._escHandler;t&&(document.removeEventListener("keydown",t,!0),be._escHandler=null),ce()}async function _t(){let t;try{let n=o.selectedElement?.cssSelector?.trim();n&&(t=document.querySelector(n)||void 0)}catch{}let e=await Ue(t||void 0);e.data&&e.data.length>5e3?(o.screenshot=e.data,le(),Z.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."}),Y("chat"),O())}function Rt(){let t=!1,e=0,s=0,n=0,a=0;q.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 m=q.getBoundingClientRect();n=m.left,a=m.top,i.preventDefault()}),document.addEventListener("mousemove",i=>{t&&(q.style.left=n+i.clientX-e+"px",q.style.top=a+i.clientY-s+"px",q.style.right="auto",q.style.bottom="auto")}),document.addEventListener("mouseup",()=>{if(t){t=!1;try{localStorage.setItem("__om_pos__",JSON.stringify({left:q.style.left,top:q.style.top}))}catch{}}})}function W(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}function At(t,e){let s=t.split(`
|
|
517
|
+
`),n=e.split(`
|
|
518
|
+
`),a=[],i=30,r=Math.min(s.length,i),m=Math.min(n.length,i),c=0;for(;c<r&&c<m&&s[c]===n[c];)c++;let u=0;for(;u<r-c&&u<m-c&&s[r-1-u]===n[m-1-u];)u++;for(let p=0;p<c;p++)a.push(`<div class="om-diff-line om-diff-ctx"><span class="om-diff-ln">${p+1}</span><span class="om-diff-sign"> </span>${W(s[p])}</div>`);for(let p=c;p<r-u;p++)a.push(`<div class="om-diff-line om-diff-del"><span class="om-diff-ln">${p+1}</span><span class="om-diff-sign">-</span>${W(s[p])}</div>`);for(let p=c;p<m-u;p++)a.push(`<div class="om-diff-line om-diff-ins"><span class="om-diff-ln"> </span><span class="om-diff-sign">+</span>${W(n[p])}</div>`);for(let p=r-u;p<r;p++)a.push(`<div class="om-diff-line om-diff-ctx"><span class="om-diff-ln">${p+1}</span><span class="om-diff-sign"> </span>${W(s[p])}</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">${W(e.slice(0,500))}</div>`}function Nt(t){let e=t.replace(/\\n/g,`
|
|
519
|
+
`),s=W(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 ot(t){let e=[],s=null;try{Me()&&(s=(await Promise.race([A("debug.logs"),new Promise((f,g)=>setTimeout(()=>g(new Error("timeout")),3e3))]))?.payload||null)}catch{}e.push("## Environment"),e.push(""),e.push(`- **OpenMagic**: v${_e}${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**: ${V[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])=>V[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(te(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,m=r.getEntriesByType("navigation")[0],c=r.getEntriesByType("paint");if(m){e.push(""),e.push("## Page Performance"),e.push(""),e.push(`- **Page Load**: ${Math.round(m.loadEventEnd-m.startTime)}ms`),e.push(`- **DOM Ready**: ${Math.round(m.domContentLoadedEventEnd-m.startTime)}ms`),e.push(`- **TTFB**: ${Math.round(m.responseStart-m.startTime)}ms`);let l=c.find(f=>f.name==="first-contentful-paint");l&&e.push(`- **FCP**: ${Math.round(l.startTime)}ms`)}let u=ue();if(u.length){let l=u.filter(h=>h.level==="error"),f=u.filter(h=>h.level==="warn"),g=u.filter(h=>h.level==="log"||h.level==="info"||h.level==="debug");if(e.push(""),e.push("## Browser Console"),e.push(""),e.push(`Total: ${u.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(d=>String(d)).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(d=>String(d)).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(d=>String(d)).join(" ").slice(0,200)}`);e.push("```"),e.push("</details>")}}let p=me(),v=p.filter(l=>l.status&&l.status>=400),k=p.filter(l=>l.duration&&l.duration>2e3);if(v.length||k.length){if(e.push(""),e.push("## Network Issues"),e.push(""),v.length){e.push(`### Failed Requests (${v.length})`),e.push("```");for(let l of v.slice(-15))e.push(`${l.method} ${l.url.slice(0,120)} \u2192 ${l.status} (${l.duration||"?"}ms)`);e.push("```")}if(k.length){e.push(`### Slow Requests >2s (${k.length})`),e.push("```");for(let l of k.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(d=>d.level==="error"),g=l.filter(d=>d.level==="warn"),h=l.filter(d=>d.level==="log"||d.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 d of f.slice(-15))e.push(`[${new Date(d.ts).toISOString()}] ${d.msg.slice(0,300)}`);e.push("```")}if(g.length){e.push(""),e.push(`### Server Warnings (${g.length})`),e.push("```");for(let d of g.slice(-10))e.push(`[${new Date(d.ts).toISOString()}] ${d.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 d of l.slice(-50))e.push(`[${new Date(d.ts).toISOString()}] [${d.level}] ${d.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(te(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(`
|
|
520
|
+
`)}function It(){fetch("https://registry.npmjs.org/openmagic/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)}).then(t=>t.ok?t.json():null).then(t=>{if(!t||typeof t.version!="string"||!/^\d+\.\d+\.\d+/.test(t.version))return;let e=t.version.split(".").map(Number),s=_e.split(".").map(Number);for(let n=0;n<3;n++){if((e[n]||0)>(s[n]||0)){o.updateAvailable=!0,o.latestVersion=t.version,Ot();return}if((e[n]||0)<(s[n]||0))return}}).catch(()=>{})}function Ot(){ge()}typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ye):Ye());})();
|
|
499
521
|
//# sourceMappingURL=index.global.js.map
|