-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMine.auto.min.js
More file actions
1 lines (1 loc) · 45.7 KB
/
Mine.auto.min.js
File metadata and controls
1 lines (1 loc) · 45.7 KB
1
const buildMine=()=>{const e={click:t=>e.qs(t)?e.qs(t).click():null,clickLast:t=>{const n=e.qsaa(t);return!!n.length&&(n[n.length-1].click(),!0)},autoLogin:()=>{const t=e.qsaa("input[type=password]").filter(e=>!!e.offsetParent);if(1!==t.length)return;const n=t[0];n.value.length>3&&n?.closest("form")?.querySelector("[type=submit]")?.click()},updateReactTypableFormValue:(e,t)=>{const n={INPUT:"HTMLInputElement",TEXTAREA:"HTMLTextAreaElement",SELECT:"HTMLSelectElement"};if(!(e.tagName in n))return;Object.getOwnPropertyDescriptor(window[n[e.tagName]].prototype,"value").set.call(e,t);const o="numeric"===e.inputMode||"number"===e.type?new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertFromPaste",data:t}):"SELECT"===e.tagName?new Event("input",{bubbles:!0,cancelable:!0}):new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t});e.dispatchEvent(o),e.dispatchEvent(new Event("change",{bubbles:!0,cancelable:!0}))},Utils:{allLetterCombinations:(e,t=[])=>{if("number"!=typeof e)throw Error("numLetters must be a number");if(e<0)throw Error("numLetters must be greater than or equal to zero");if(0===e)return[];const n="abcdefghijklmnopqrstuvwxyz".split(""),o=e=>n.map(t=>e+t),s=(e,t=n,a=1)=>e==a?t:s(e,(e=>e.map(o).reduce((e,t)=>e.concat(t),[]))(t),a+1);return s(e).filter(e=>!t.length||t.includes(e[0]))},findGalleries:()=>e.qsaa("span,div").filter(e=>{const t=Array.from(e.children).filter(e=>e.offsetHeight>0&&e.offsetWidth>0);if(t.length<3)return!1;const n=new Set;return t.map(e=>`${e.offsetHeight}x${e.offsetWidth}`).forEach(e=>n.add(e)),Array.from(n).every(e=>e.split("x").map(e=>Number(e)).every(e=>e>100))}),animateGalleryPreviews:t=>{Array.from(t.children).map(e=>e.querySelector("img")).filter(e=>!!e).forEach(e.simulateHover)},getIsElementVisible:e=>e.offsetWidth>0&&e.offsetHeight>0,openTemporaryWindow:e=>{const t=window.open(e);return!t||t.closed||void 0===t.closed?(alert("[noop] couln't open window to send message"),!1):(setTimeout(()=>t.close(),1e4),!0)},addCssLinkIfNeeded:e=>{if(Array.from(document.head.querySelectorAll("link")).map(e=>e.href).includes(e))return;const t=window.document.createElement("link");t.rel="stylesheet",t.type="text/css",t.href=e,document.getElementsByTagName("HEAD")[0].appendChild(t)},getMostCommonUnitElements:(e,t)=>{const n={};e.map(t).filter(e=>!!e).forEach(e=>n[e]=(n[e]||0)+1);const o=Object.keys(n).reduce((e,t)=>n[e]>n[t]?e:t);return e.filter(e=>t(e)===o)}},qs:(e,t=document)=>t.querySelector(e),qsa:(e,t=document)=>t.querySelectorAll(e),qsaArray:(t,n=document)=>Array.from(e.qsa(t,n)),qsaa:(t,n=document)=>e.qsaArray(t,n),qsOnly:(t,n=document)=>{const o=e.qsaa(t,n);return 1===o.length?o[0]:null},qso:(t,n=document)=>e.qsOnly(t,n),lmkr:async e=>{const t=`https://sum-notifier.vercel.app/api/v1/notify?message=${encodeURIComponent(e)}&title=Chrome%20Helper`;return await fetch(t,{mode:"no-cors"}),!0},runSteps:async(t,n="",o=1e3)=>{try{for(let n=0;n<t.length;n++)t[n](),await e.sleep(o)}catch(e){n&&alert(n)}},lmkrWhenSelectedElementChanges:()=>{const t=()=>Math.round((new Date).getTime()/1e3),n=t(),o=$0;if(!o)return alert("[noop] select an element using element inspector an try again."),!1;const s=e=>[e.value||"",e.outerHTML||""].join(":"),a=s(o),r=e=>e.length>30?e.substr(0,29)+"…":e,i=(o,a)=>{const c=s(o);if(o&&c===a){const e=t()-n;e%60==0&&console.log(`[${Math.round(e/60)}m] still checking every 500ms...`),setTimeout(()=>i(o,a),500)}else e.lmkr(`Watched element changed:\n🏁: ${r(c)}\n🏳: ${r(a)}`),console.log("notified element change")};return e.lmkr(`Watching for element changes:\n🏳: ${r(a)}`)?(i(o,a),window.MineElement=o,o):(alert("Unable to send messages. Fix that and try again."),!1)},colorElementsByValue:(e,t,n={})=>{const o=(e=e.filter(e=>!isNaN(t(e)))).map(t),s=n.filterOutliers?((e=[])=>{if(e.length<4)return{};let t,n,o,s,a;return t=e.slice().sort((e,t)=>e-t),t.length/4%1==0?(n=.5*(t[t.length/4]+t[t.length/4+1]),o=.5*(t[t.length*(3/4)]+t[t.length*(3/4)+1])):(n=t[Math.floor(t.length/4+1)],o=t[Math.ceil(t.length*(3/4)+1)]),s=o-n,a=1.5,{min:n-1.5*s,max:o+1.5*s}})(o):{},a=Math.min(...o),r=(s.max||Math.max(...o))-a;e.forEach(e=>{const o=[255,0,0],s=[0,255,0],i=n.invertColors?o:s,c=n.invertColors?s:o,l=(t(e)-a)/r,m=((e,t=[],n=[])=>{const o=(2*(1-e)-1+1)/2,s=1-o;return[parseInt(t[0]*o+n[0]*s),parseInt(t[1]*o+n[1]*s),parseInt(t[2]*o+n[2]*s)]})(l,i,c),d=0===l||l>=1;e.style[d?"border":"borderBottom"]=`4px RGB(${m.join(",")}) solid`,d&&(e.style.background=`RGB(${m.join(",")})`),d&&(e.style.color="white"),e.style.borderRadius="3px";const u=`Relative efficiency: ${Math.round(100*(n.invertColors?l:1-l))}%\n`;e.title=`${u}${e.title}`.trim()})},sleep:async(e=1e3)=>new Promise(t=>setTimeout(t,e)),colorColumnByValue:(t,n="",o,s={})=>{if(!t)return!1;const a=Array.from(t?.tHead?.children[0]?.children||[]).findIndex(e=>e.innerText.trim().toLowerCase()===n.trim().toLowerCase()),r=Array.from(t.querySelectorAll(`tbody tr td:nth-child(${a+1})`));e.colorElementsByValue(r,o,s)},scrollToTop:(e=!1)=>window.scroll({top:0,left:0,behavior:e?"auto":"smooth"}),scrollToBottom:(e=!1)=>window.scroll({top:document.body.scrollHeight,left:0,behavior:e?"auto":"smooth"}),scrollToElement:(e,t=0)=>new Promise(n=>{const o=(window.pageYOffset||document.documentElement.scrollTop)+e.getBoundingClientRect().top-100+t;Math.round(window.scrollY)!==Math.round(o)?(window.scrollTo({top:o,left:0,behavior:"smooth"}),((e=()=>{})=>{const t=(n=null)=>{clearTimeout(n),n=setTimeout(()=>{n=null,removeEventListener("scroll",t),e()},100)};addEventListener("scroll",t);const n=window.scrollY;setTimeout(()=>{window.scrollY===n&&(removeEventListener("scroll",t),e())},100)})(n)):n()}),miniSpotlightElementWithCallback:async(t,n=e.noop)=>{if(!t)return;await e.scrollToElement(t);const o="__CommandBarMine_circler__";e._activeMiniSpotlightDispose?.(),e.qs(`#${o}`)?.remove();const s=document.createElement("div");s.id=o,Object.assign(s.style,{position:"fixed",boxSizing:"border-box",border:"10px solid slateblue",borderRadius:"20px",boxShadow:"rgba(0, 0, 0, 0.45) 0px 0px 50px",pointerEvents:"none",opacity:"0",transition:"opacity 500ms",zIndex:"100000000"}),document.body.append(s);let a=!1,r=null;const i=()=>{a||(a=!0,r?.(),s.remove(),e._activeMiniSpotlightDispose===i&&(e._activeMiniSpotlightDispose=null))};e._activeMiniSpotlightDispose=i,r=e._trackElementRect(t,{onChange:e=>{s.style.width=`${e.width+35}px`,s.style.height=`${e.height+35}px`,s.style.top=e.top-17.5+"px",s.style.left=e.left-17.5+"px"},onGone:i});try{if(s.style.opacity="1",await e.sleep(500),a)return;if(await n(),a)return;await e.sleep(200),s.style.opacity="0",await e.sleep(500)}finally{i()}},simulateClickWithHint:async t=>{t&&await e.miniSpotlightElementWithCallback(t,()=>e.simulateClick(t))},simulateRightClick:e=>{const t=new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,view:window,button:2,buttons:2,clientX:e.getBoundingClientRect().left+e.offsetWidth/2,clientY:e.getBoundingClientRect().top+e.offsetHeight/2});e.dispatchEvent(t)},simulateClick:(e,t=[])=>{if(!e)return;const n=t.includes("left_quarter"),o=e.getBoundingClientRect(),s=o.left+(o.right-o.left)*(n?.2:.5),a=o.top+.5*(o.bottom-o.top);["mousedown","mouseup","click"].forEach(t=>((e,t,n,o)=>e.dispatchEvent(new MouseEvent(t,{view:window,bubbles:!0,cancelable:!0,clientX:n,clientY:o,button:0})))(e,t,s,a))},simulateHover:e=>e.dispatchEvent(new Event("mouseover",{view:window,bubbles:!0,cancelable:!1})),assertTruthy:e=>{if(e)return e;throw"assertion failed"},waitFor:async(t,{timeoutMs:n=5e3,recheckIntervalMs:o=null,shouldPadDelay:s=!1,debugMsg:a=""}={})=>{const r=Date.now();for(;;){const i=await t();if(i)return s&&await e.sleep(25),i;const c=Date.now()-r;if(c>=n)throw new Error("Timeout"+(a.trim()?`: ${a.trim()}`:""));if(null==o){const t=c<=500;await e.sleep(t?0:5)}else await e.sleep(Number(o))}},waitForQs:async(t,n={})=>await e.waitFor(()=>e.qs(t),n),waitForQsaa:async(t,n={})=>await e.waitFor(()=>{const e=document.querySelectorAll(t);return e.length?[...e]:null},n),getQueryParam:e=>{const t=window.location.search,n=new URLSearchParams(t);return n.has(e)?n.get(e):null},noop:()=>{},injectStylesheetIdempotent:(t="")=>{const n=t.trim();if(e.qsaa("style").map(e=>e.textContent).some(e=>e===n))return e.noop;const o=document.createElement("style");return o.textContent=n,document.head.appendChild(o),()=>o.remove()},injectStylesheetIdempotentCspFriendly:(t="")=>{const n=t.trim(),o=`style-${s=n,s.split("").reduce((e,t)=>(e<<5)-e+t.charCodeAt(0),0)}`;var s;if(document.getElementById(o))return e.noop;const a=document.createElement("style");a.id=o;const r=new Blob([n],{type:"text/css"}),i=URL.createObjectURL(r);return a.href=i,document.head.appendChild(a),()=>{URL.revokeObjectURL(i),document.getElementById(o)?.remove()}},injectScriptIdempotent:async(t,n=!1,o="")=>new Promise((s,a)=>{if(e.qsaa("script").map(e=>e.src).some(e=>e===t))return s();const r=document.createElement("script");r.type="text/javascript",r.async=!0,r.onload=s,r.onerror=a,o&&(r.integrity=o,r.crossOrigin="anonymous");try{r.src=t}catch(e){if(!n)throw e;if(!window.trustedTypes||!trustedTypes.createPolicy)throw new Error("[Mine] [Pepper] Trusted Types not supported and direct assignment failed");{const e=trustedTypes.createPolicy("injectPolicy",{createScriptURL:e=>e});r.src=e.createScriptURL(t)}}document.getElementsByTagName("head")[0].appendChild(r)}),wrapAddEventListenerWithBlockers:(e=[])=>{Object.getOwnPropertyNames(window).filter(e=>/^HTML/.test(e)).map(e=>window[e]).forEach(t=>{var n;n=t.prototype.addEventListener,t.prototype.addEventListener=function(t,o,s){const a=this;if(!e.some(e=>t===e.type&&a.matches(e.querySelector)))return n.apply(this,arguments)}})},BridgeAgent:class{constructor(e,t=[],n={}){this.name=e,this.commands=t,this.connectionFailed=!1,this.serverUrl=n.url,this.authApiKey=n.authApiKey,this.agentName=n.agentName||"BridgeAgent",this.serverUrl?(this.#e(),this.#t()):console.error(`[${this.agentName}] no server url provided`)}#e(){this.commands.push({title:"restart",description:"",run:async()=>{setTimeout(()=>location.reload(),3e3)}})}async#t(){const t=["https://www.youtube.com","https://open.spotify.com"].includes(window.location.origin)&&["personal","personal-assistant"].includes(e.Environment?.Profile?.name),n=window.define;window.define=void 0;const o=await e.injectScriptIdempotent("https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.8.1/socket.io.min.js",t).catch(()=>!1);return window.define=n,o?(this.socket=io(this.serverUrl,{auth:{apiKey:this.authApiKey},query:{name:this.name},transports:["websocket"],reconnectionDelayMax:3e4}),this.socket.on("connect",()=>{this.connectionFailed=!1,console.log(`[Mine] [${this.agentName}] connected`),this.socket.emit("register-commands",this.commands)}),this.socket.on("connect_error",e=>{console.log(`[Mine] [${this.agentName}] connection error:`,e.message)}),this.socket.on("disconnect",e=>{console.log(`[Mine] [${this.agentName}] disconnected:`),"io server disconnect"!==e||this.connectionFailed?this.connectionFailed&&console.log(`[Mine] [${this.agentName}] not reconnecting due to previous connection failure`):(console.log(`[Mine] [${this.agentName}] trying to reconnect...`),this.socket.connect())}),this.commands.forEach(({title:e,run:t})=>{this.socket.on(e,async(n,o)=>{try{o(await t(n??{})||{success:!0})}catch(t){console.error(`[Mine] [${this.agentName}] command "${e}" failed:`,t),o({error:t.message})}})}),window.addEventListener("focus",()=>{this.socket&&this.socket.connected&&!this.connectionFailed&&(this.socket.disconnect(),this.socket.connect())}),!0):(console.log(`[Mine] [${this.agentName}] aborted due to script injection failure`),this.connectionFailed=!0,!1)}async ask(e,t=[],n=()=>{},o=6e4){if(this.connectionFailed||!this.socket||!this.socket.connected)return void n({error:"Connection unavailable"});const s={questionObj:e,responseOptions:t,timeoutMs:o};this.socket.timeout(o).emit("ask",s,n)}},PepperAgent:class{constructor(t,n=[],o={}){const s={url:"https://pepperpotts.fly.dev:443",authApiKey:o.authApiKey||e?.Environment?.Profile?.pagentSocketAuthApiKey,agentName:"PepperAgent"};if(s.authApiKey)return new e.BridgeAgent(t,n,s);console.error("no pagent auth info")}},randomItemFromArray:e=>e[Math.floor(Math.random()*e.length)],setIntervalAndNow:(e,t=1e3)=>{e(),setInterval(e,t)},_getPuiDataKey:e=>"data-mine-processed"+(e?`-${e}`:""),processUnprocessedItems:(t=[],n,o="")=>{const s=e._getPuiDataKey(o),a=Array.from(t).filter(Boolean).filter(e=>!("true"===e.getAttribute(s))),r=e=>e.setAttribute(s,"true"),i=e=>"AsyncFunction"===e.constructor.name;for(let t=0;t<a.length;t++){const o=a[t];if(i(o))n(o).then(()=>r(o)).catch(e.noop);else{try{n(o)}catch(e){continue}r(o)}}},setQueryParam:(e,t)=>{const n=new URL(window.location);n.searchParams.set(e,t),window.location=n.href},setQueryParams:(e={})=>{const t=new URL(window.location);Object.entries(e).forEach(([e,n])=>{null==n?t.searchParams.delete(e):t.searchParams.set(e,n)}),window.location=t.href},dim:(e,{hoverDelayMs:t=500}={})=>{if(!e)return;(e=>{const t=e.style.transition.split(",").map(e=>e.trim()).filter(e=>e.length).filter(e=>!e.includes("opacity"));t.push("opacity 0.2s ease"),e.style.transition=t.join(", ")})(e);const n="0.05";let o;const s=()=>{o=setTimeout(()=>{e.style.removeProperty("opacity")},t)},a=()=>{clearTimeout(o),e.style.opacity=n},r="data-mine-dimmed";return e.setAttribute(r,"true"),e.style.setProperty("opacity",n),e.addEventListener("mouseover",s),e.addEventListener("mouseout",a),()=>{e.removeAttribute(r),e.style.removeProperty("opacity"),e.removeEventListener("mouseover",s),e.removeEventListener("mouseout",a)}}};e.updateElementValueWithLifecycles=e.updateReactTypableFormValue,e.quietElement=e.dim,e.quietElementCompletelyAsync=async e=>{if(e&&e instanceof Element)return e.style.transition="opacity 200ms ease-out",e.style.opacity="0",new Promise(t=>{setTimeout(()=>{e.style.visibility="hidden",t(e)},200)})},e.getIndexedDbCountAsync=async(e,t)=>new Promise((n,o)=>{const s=indexedDB.open(e);s.onerror=e=>o(`An error occurred while accessing the database: ${e.target.errorCode}`),s.onsuccess=e=>{const s=e.target.result.transaction([t],"readonly").objectStore(t).count();s.onerror=e=>o(`An error occurred while counting items: ${e.target.errorCode}`),s.onsuccess=e=>n(e.target.result)}}),e.getIndexedDbValueAsync=async(e,t,n)=>new Promise((o,s)=>{const a=indexedDB.open(t);a.onerror=e=>s(`An error occurred while accessing the database: ${e.target.errorCode}`),a.onsuccess=t=>{const a=t.target.result.transaction([n],"readonly").objectStore(n).get(e);a.onerror=e=>s(`An error occurred while retrieving the data: ${e.target.errorCode}`),a.onsuccess=e=>o(e.target.result)}}),e.getIndexedDbValue=e.getIndexedDbValueAsync,e.DELETE_SENTINEL=Symbol("IndexedDB Delete Sentinel"),e.setIndexedDbValueAsync=async(t,n,o,s)=>new Promise((a,r)=>{if(!t||!o||!s)return r("Required arguments missing");const i=indexedDB.open(o);i.onerror=e=>r(`Database access error: ${e.target.error}`),i.onsuccess=o=>{const i=o.target.result,c=i.transaction([s],"readwrite"),l=c.objectStore(s),m=n===e.DELETE_SENTINEL?l.delete(t):l.put(n,t);m.onerror=e=>r(`Operation error: ${e.target.error}`),m.onsuccess=()=>a(n===e.DELETE_SENTINEL?`Key ${t} deleted`:`Key ${t} set`),c.oncomplete=()=>i.close()}}),e.setIndexedDbValue=e.setIndexedDbValueAsync,e.deleteIndexedDbValueAsync=async(t,n,o)=>await e.setIndexedDbValueAsync(t,e.DELETE_SENTINEL,n,o),e.addEventListenerForSubtreeAddOrRemove=(e,t)=>{const n=new MutationObserver((e,n)=>{for(let n of e)"childList"===n.type&&t()});return n.observe(e,{childList:!0,subtree:!0}),()=>n.disconnect()},e.onElementRemoval=(e,t)=>{new MutationObserver((n,o)=>{e.isConnected||(o.disconnect(),t())}).observe(document,{childList:!0,subtree:!0})},e.onElementRemove=e.onElementRemoval,e.colorizeByContent=(t=[],n=e=>e.innerText,o="content")=>e.pui(t,async t=>{const o=n(t),s=await e.getHashedStringToHexAsync(o);t.style.transition||(t.style.transition="color 0.1s ease-in-out"),t.style.setProperty("color",s,"important")},`${o}-colorizer`),e.colorizeElementsByContent=e.colorizeByContent,e.colorizeElementByContent=(t,...n)=>e.colorizeByContent([t],...n),e.withCacheInSession=e=>{const t=e.name||e.toString().slice(0,100);return async(...n)=>{const o=`mine.cached.${encodeURIComponent(t)}.${encodeURIComponent(JSON.stringify(n))}`,s=window.sessionStorage.getItem(o);if(s)return JSON.parse(s);const a=await e(...n);return void 0!==a&&window.sessionStorage.setItem(o,JSON.stringify(a)),a}},e.isi=e.injectStylesheetIdempotent,e.withCacheInMemory=e=>{const t=new Map;return async(...n)=>{const o=JSON.stringify(n);if(t.has(o))return t.get(o);const s=await e(...n);return t.set(o,s),s}};const t=e.withCacheInMemory(e=>{if("string"!=typeof e)throw new Error("Color input must be a string");const t=e=>{const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null},n={black:"#000000",white:"#ffffff",red:"#ff0000",lime:"#00ff00",blue:"#0000ff",yellow:"#ffff00",cyan:"#00ffff",magenta:"#ff00ff",silver:"#c0c0c0",gray:"#808080",maroon:"#800000",olive:"#808000",green:"#008000",purple:"#800080",teal:"#008080",navy:"#000080"};if(e.startsWith("#"))return t(e);if(e.toLowerCase().startsWith("rgb("))return(e=>{const t=/rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(e);return t?{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}:null})(e.toLowerCase());if(e.toLowerCase()in n)return(e=>{const o=n[e.toLowerCase()];return o?t(o):null})(e);if(e.toLowerCase().startsWith("rgba("))return(e=>{const t=/rgba\((\d+),\s*(\d+),\s*(\d+),\s*[\d.]+\)/i.exec(e);return t?{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}:null})(e.toLowerCase());throw new Error(`Invalid color format provided: ${e}. Accepts hex string, RGB string, or named HTML color.`)}),n=e.withCacheInMemory(e=>{const t=[e.r,e.g,e.b].map(e=>e/255).map(e=>e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4));return.2126*t[0]+.7152*t[1]+.0722*t[2]}),o=e.withCacheInMemory(async(e,t)=>{const o=await n(e),s=await n(t);return(Math.max(o,s)+.05)/(Math.min(o,s)+.05)}),s=e.withCacheInMemory(e=>{let t=0;for(let n=0;n<e.length;n++)t=Math.imul(31,t)+e.charCodeAt(n)|0;let n="#";for(let e=0;e<3;e++)n+=(t>>8*e&255).toString(16).padStart(2,"0");return n});e.getHashedStringToHexAsync=e.withCacheInMemory(async(e,n)=>{let a=await s(e);if(n){const r=4.5;let i=0;const c=10,l=await t(n);let m=0,d=a;const u=async e=>{const n=await o(await t(e),l);return n>m&&(m=n,d=e),n};let p=await u(a);for(;p<r&&i<c;)i++,a=await s(e+i),p=await u(a);a=d}return a}),e.getCssToHide=t=>e.normalizeSpaceIndents(`\n ${t} {\n display: none !important;\n }\n `),e.getCssToQuietQs=(t,{delayMs:n=1e3}={})=>e.normalizeSpaceIndents(`\n ${t} {\n opacity: 0.2;\n transition: opacity 0.2s ease-in-out !important;\n }\n ${t}:hover {\n transition-delay: ${n/1e3}s !important;\n opacity: 1;\n }\n `).trim(),e.bindHotkey=(e,t=document,n)=>{const o=e.split("+").map(e=>e.trim().toLowerCase());let s="";const a={shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1};o.forEach(e=>{const t=Object.keys(a).find(t=>t.toLowerCase()===e);t?a[t]=!0:s=e});const r=e=>{const o=t!==document||!["input","textarea","select","button"].includes(e.target.tagName?.toLowerCase())&&!e.target.isContentEditable,r=e.key.toLowerCase()===s;Object.keys(a).every(t=>a[t]===e[t])&&r&&o&&n(e)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},e.Ollama={getIsStatementTrueOrFalse:async t=>await e.Ollama.getDoesPassageAnswerQuestion(t,"Is this true?"),getDoesPassageAnswerQuestion:async(t="I like apples",n="Do they like fruits?")=>{const o=`\n ${n} Respond with "YES" or "NO".\n\n Passage (in triple quotes):\n """\n ${(t=String(t)).split("\n").map(e=>`> ${e}`).join("\n")}\n """\n `.trim();return((e="")=>{const t=e.trim().toLowerCase().startsWith("yes,"),n="yes"===e.replace(/[^a-zA-Z]/g,"").toLowerCase().split(" ")[0];return t||n})(await e.Ollama.getResponseText(o).then(e=>e.trim()))},_getResponseTextUnmanagedAsync:async(t,{model:n="phi4:latest",systemPrompt:o="",jsonMode:s=!1,startResponseWith:a="",keep_alive:r=9e5}={})=>{const i=[{role:"user",content:t}];o&&i.unshift({role:"system",content:o}),a&&i.push({role:"assistant",content:a});const c={model:n,messages:i,stream:!1,options:{temperature:0},keep_alive:r};s&&(c.format="json");const l=JSON.stringify(c),m=await e.Extension.fetchText("http://127.0.0.1:11434/api/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:l});if(!m)throw new Error("error fetching");return a+m.split("\n").filter(Boolean).map(e=>JSON.parse(e))[0].message.content},_getResponseJsonUnmanagedAsync:async(t,n={})=>{n.jsonMode=!0;const o=await e.Ollama._getResponseTextUnmanagedAsync(t,n);let s=null;try{s=JSON.parse(o.trim())}catch(e){}return s},getResponseText:async(t,n={})=>await e.withCacheInSession(e.Ollama._getResponseTextUnmanagedAsync)(t,n),getResponseJsonAsync:async(t,n={})=>await e.withCacheInSession(e.Ollama._getResponseJsonUnmanagedAsync)(t,n),_getResponseObjs:async(t="",n=!0)=>{const o=JSON.stringify({model:"openhermes:7b-mistral-v2.5-q6_K",prompt:t,temperature:0}),s=await e.Extension.fetchText("http://127.0.0.1:11434/api/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:o});if(!s)throw new Error("error fetching");return s.split("\n").filter(Boolean).map(e=>JSON.parse(e))}},e.Ai={getResponseText:async(...t)=>await e.withCacheInSession(e.Ai._getResponseTextRaw)(...t),_getResponseTextRaw:async(t,n="",{imageDataBase64:o=null,brand:s="anthropic",options:a={}}={})=>{let r=t;o&&(r=[{type:"text",text:t},{type:"image",source:{type:"base64",media_type:"image/png",data:o}}]);const i=[{role:"user",content:r}];let c="";const l=await(async t=>"anthropic"===t?await e.Extension.getItem("commandbar-anthropic-key").catch(()=>null):"cerebras"===t?await e.Extension.getItem("commandbar-cerebras-key").catch(()=>null):"groq"===t?(c=e.randomItemFromArray(["commandbar-groq-key"]),await e.Extension.getItem(c).catch(()=>null)):"sambanova"===t?await e.Extension.getItem("commandbar-sambanova-key").catch(()=>null):null)(s);if(!l)return e.toastError(`No AI key for "${s}"`);let m;return"anthropic"===s?m=await(async t=>{const o={model:"claude-sonnet-4-0",temperature:1,stream:!1,messages:t,max_tokens:4096,system:n,...a};return(await e.Extension.fetchJson("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json",accept:"*/*","accept-language":"en-US,en;q=0.9","anthropic-beta":"max-tokens-3-5-sonnet-2024-07-15,prompt-caching-2024-07-31","anthropic-dangerous-direct-browser-access":"true","anthropic-version":"2023-06-01","x-api-key":l},body:JSON.stringify(o)})).content[0].text})(i):"cerebras"===s?m=await(async t=>{const n=await e.Extension.fetchJson("https://api.cerebras.ai/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({model:"llama3.1-70b",temperature:1,stream:!1,messages:t,max_completion_tokens:-1,seed:0,top_p:1,...a})});if("too_many_requests_error"===n.type)throw"too_many_requests_error";const o=n.choices?.[0]?.message;if(!o)throw"no message in response";return o.content})(i):"groq"===s?m=await(async t=>{const n=await e.Extension.fetchJson("https://api.groq.com/openai/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({model:"llama-3.2-90b-vision-preview",temperature:1,stream:!1,messages:t,seed:0,top_p:1,...a})});if(n.type)throw`error "${n.type}"`;const o=n.choices?.[0]?.message;if(!o)throw console.log(`ai failed w key '${c}'`,n),"unexpected ai response";return o.content})(i):"sambanova"===s&&(m=await(async t=>{const n=await e.Extension.fetchJson("https://api.sambanova.ai/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({stream:!1,model:"Meta-Llama-3.1-405B-Instruct",messages:t,...a})}),o=n.choices?.[0]?.message;if(!o)throw"no message in response";return o.content})(i)),m}},e._trackElementRect=(e,{onChange:t,onGone:n}={})=>{if(!(e&&e instanceof Element))return()=>{};let o=null,s=null,a=!1;function r(){a||(a=!0,null!=o&&cancelAnimationFrame(o),window.removeEventListener("scroll",c,{capture:!0}),window.removeEventListener("resize",c),l.disconnect())}function i(){if(a)return;if(!document.body.contains(e))return n?.(),void r();const o=e.getBoundingClientRect();s&&o.top===s.top&&o.left===s.left&&o.width===s.width&&o.height===s.height||(s=o,t?.(o))}function c(){a||null!=o||(o=requestAnimationFrame(()=>{o=null,i()}))}window.addEventListener("scroll",c,{passive:!0,capture:!0}),window.addEventListener("resize",c);const l=new ResizeObserver(c);return l.observe(e),i(),r},e.spotlightElement=(t,{opacity:n=.8,blurPx:o=0,autoScroll:s=!0}={})=>{if(!(t&&t instanceof Element))return console.error("Spotlight target must be a valid DOM Element"),()=>{};s&&t.scrollIntoView({block:"center",behavior:"smooth"});const a=document.createElement("div");a.classList.add("mine-wall"),Object.assign(a.style,{position:"fixed",top:"0",left:"0",width:"100vw",height:"100vh",background:`rgba(0, 0, 0, ${n})`,backdropFilter:`blur(${o}px)`,webkitBackdropFilter:`blur(${o}px)`,zIndex:"10000",opacity:"0",transition:"\n opacity 200ms ease,\n clip-path 0.25s cubic-bezier(0.4, 0, 0.2, 1),\n backdrop-filter 200ms ease\n ",pointerEvents:"auto"}),document.body.append(a);let r=!1,i=null;const c=()=>{r||(r=!0,i?.(),a.style.opacity="0",a.style.backdropFilter="blur(0px)",a.style.webkitBackdropFilter="blur(0px)",setTimeout(()=>a.remove(),300))};return i=e._trackElementRect(t,{onChange:e=>{a.style.clipPath=(e=>`polygon(\n 0px 0px, 100% 0px,\n 100% ${e.top}px,\n ${e.left}px ${e.top}px,\n ${e.left}px ${e.bottom}px,\n ${e.right}px ${e.bottom}px,\n ${e.right}px ${e.top}px,\n 100% ${e.top}px,\n 100% 100%, 0px 100%\n )`)(e)},onGone:c}),a.addEventListener("click",c),requestAnimationFrame(()=>requestAnimationFrame(()=>{r||(a.style.opacity="1")})),c},e.pui=e.processUnprocessedItems,e.normalizeSpaceIndents=e=>{if(!e)return e;const t=e.split("\n"),n=Math.min(...t.filter(e=>e.trim()).map(e=>e.match(/^\s*/)[0].length));return t.map(e=>e.slice(n)).join("\n")},e.nsi=e.normalizeSpaceIndents,e.addEventListenerForDirectChildrenChange=(e,t)=>{const n=new MutationObserver(e=>{for(let n of e)if("childList"===n.type){const e=[],o=[];for(let t of n.addedNodes)t.nodeType===Node.ELEMENT_NODE&&e.push(t);for(let e of n.removedNodes)e.nodeType===Node.ELEMENT_NODE&&o.push(e);(e.length>0||o.length>0)&&t({added:e,removed:o,mutation:n})}});return n.observe(e,{childList:!0}),()=>n.disconnect()};let a=0;e.processUnprocessedItemsContinuallyAsync=async(t,n,o="")=>{o=o||`puic-${a++}-${Date.now()}`;const s=`not([${e._getPuiDataKey(o)}])`,r=[];let i=500;const c=()=>{const a=t({nypf:s});return e.pui(a,n,o),a.length};let l=!0;const m=async()=>{if(l){try{const e=c();r.push({count:e}),r.length>5&&r.shift(),i=(()=>{if(r.length<3)return i;const e=r.reduce((e,t)=>e+t.count,0)/r.length,t=Math.max(200,Math.min(1e3,1e3-80*e));return 50*Math.round(t/50)})()}catch(e){}setTimeout(m,i)}};return m(),{deconstruct:()=>l=!1,trigger:c}},e.processUnprocessedItemsContinually=e.processUnprocessedItemsContinuallyAsync,e.puic=e.processUnprocessedItemsContinually,e.puica=e.processUnprocessedItemsContinuallyAsync,e.hideQs=t=>e.isi(e.getCssToHide(t)),e.hqs=e.hideQs,e.quietQs=(t,n={})=>e.isi(e.getCssToQuietQs(t,n)),e.qqs=e.quietQs,e.removeElementAsync=async e=>new Promise(t=>{if(!e)return void t();const n=window.getComputedStyle(e),o=n.height;e.style.width=n.width,e.style.height=o,requestAnimationFrame(()=>{e.style.transition="opacity 150ms, width 150ms, height 150ms",e.style.opacity="0",e.style.width="0",e.style.height="0",e.style.overflow="hidden",e.addEventListener("transitionend",function n(o){"opacity"===o.propertyName&&(e.removeEventListener("transitionend",n),e.remove(),t())})})}),e.removeElement=e.removeElementAsync,e.removeEle=e.removeElement,e.collapse=(e,t="100px")=>{if(!e)return;const n=document.createElement("div");n.style="position: relative; overflow: hidden; transition: max-height 0.1s ease;",n.style.maxHeight=`${e.offsetHeight}px`;const o=document.createElement("div");o.title="Expand collapsed item",o.style="position: absolute; bottom: 0; left: 0; right: 0; height: 100%; background: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.2)); cursor: pointer; border-radius: 5px;",e.parentNode.insertBefore(n,e),n.appendChild(e),n.appendChild(o),setTimeout(()=>n.style.maxHeight=t,0),o.addEventListener("click",()=>{const e=n.style.maxHeight===t;n.style.maxHeight=e?`${n.scrollHeight}px`:t,o.style.display=e?"none":"block"});const s=new MutationObserver(e=>{e.forEach(e=>{if("childList"===e.type){for(o.remove();n.firstChild;)n.parentNode.insertBefore(n.firstChild,n);n.parentNode.removeChild(n),s.disconnect()}})});s.observe(n,{childList:!0})},e.attachToElementContinuouslyAsync=async(t=()=>{},n=()=>{},o={})=>{const s=async()=>{const a=await t().catch(()=>null);if(!a)return void(o.onElementNotFound&&await o.onElementNotFound());const r=await n(a);e.onElementRemoval(a,async()=>{o.onElementGone&&await o.onElementGone(a),r&&await r(),s()})};await s()},e.attachToElementContinuously=e.attachToElementContinuouslyAsync,e.throttle=(e,t=1e3)=>{let n=0;return(...o)=>{const s=Date.now();s-n<t||(n=s,e(...o))}},e.debounce=(e,t=1e3,n=null)=>(...o)=>(clearTimeout(n),n=setTimeout(()=>e(...o),t)),e.throttleAndDebounce=(t=e.noop,{throttleMs:n=100,debounceMs:o=250}={})=>{let s,a=0;return(...e)=>{const r=Date.now();r-a>n&&(t(...e),a=r),clearTimeout(s),s=setTimeout(()=>t(...e),o)}};const r=[];return e.toastAsync=(e="",t,n={})=>new Promise(o=>{e=e.toString(),t||(t=Math.min(3e3+1e3*e.split(" ").length*.75,2e4));const{severity:s="none"}=n,a=s.toLowerCase();let i="";"none"!==a&&(i=`box-shadow: inset 0 0 0 2px ${{info:"lightblue",error:"red",warning:"orange",success:"limegreen"}[a]||"transparent"};`);const c=document.createElement("div");c.className="mine-hud-msg",c.textContent=e,c.style.cssText=`\n position: fixed;\n bottom: 20px;\n right: 20px;\n padding: 10px 20px;\n background: rgba(0,0,0,0.9);\n color: white;\n ${i}\n border-radius: 5px;\n transition: all 0.3s;\n opacity: 0;\n transform: translateY(100%);\n z-index: 10000;\n max-width: 300px;\n word-wrap: break-word;\n user-select: text;\n touch-action: pan-x;\n text-align: left;\n `,document.body.appendChild(c);const l=()=>{r.forEach((e,t)=>{e.style.bottom=20+t*(e.offsetHeight+10)+"px"})},m=()=>{if(document.hidden)return void setTimeout(m,1e3);c.style.transition="all 0.3s",c.style.transform="translateX(100%)",c.style.opacity="0";const e=r.indexOf(c);e>-1&&r.splice(e,1),l(),setTimeout(()=>{c.remove(),o()},300)};let d,u;const p=()=>{const e=window.getSelection();return e.toString().length>0&&c.contains(e.anchorNode)};c.addEventListener("touchstart",e=>{p()||(d=e.touches[0].clientX,u=Date.now(),c.style.transition="none")}),c.addEventListener("touchmove",e=>{if(!d||p())return;const t=e.touches[0].clientX-d;t>0&&(e.preventDefault(),c.style.transform=`translateX(${t}px)`)}),c.addEventListener("touchend",e=>{if(!d||p())return;const t=e.changedTouches[0].clientX-d,n=Date.now()-u;t>50&&n<300?m():(c.style.transition="transform 0.3s",c.style.transform="translateY(0)"),d=null}),r.push(c),l(),requestAnimationFrame(()=>{c.style.opacity="1",c.style.transform="translateY(0)"}),setTimeout(m,t)}),e.toast=(t,n)=>e.toastAsync(t,n,{severity:""}),e.toastInfo=(t,n)=>e.toastAsync(t,n,{severity:"info"}),e.toastWarning=(t,n)=>e.toastAsync(t,n,{severity:"warning"}),e.toastError=(t,n)=>e.toastAsync(t,n,{severity:"error"}),e.toastSuccess=(t,n)=>e.toastAsync(t,n,{severity:"success"}),e.toastGlobalAsync=async e=>{try{return(await fetch("http://localhost:3305/alert",{method:"POST",headers:{"Content-Type":"application/json"},body:e})).ok}catch(e){return!1}},e.getAnimationFrameAsync=async()=>new Promise(e=>requestAnimationFrame(e)),e.deduplicate=e=>[...new Set(e)],e.Obfuscator={_key:71,_xor:(()=>{const t=new Map;return n=>{if(t.has(n))return t.get(n);const o=String.fromCharCode(...n.split("").map(t=>t.charCodeAt(0)^e.Obfuscator._key));return t.set(n,o),o}})(),_process:t=>{if("string"==typeof t)return e.Obfuscator._xor(t);if("object"!=typeof t||null===t)return t;const n=Object.entries(t);for(let o=n.length-1;o>=0;o--){const[s,a]=n[o];delete t[s],t[e.Obfuscator._xor(s)]="object"==typeof a&&null!==a?e.Obfuscator._process(a):"string"==typeof a?e.Obfuscator._xor(a):a}return t},obfuscate:t=>e.Obfuscator._process(t),deobfuscate:t=>e.Obfuscator._process(t)},e.Extension={_remoteDistachedFunctionRequestCounter:0,serveRemoteDispatchedFunction:(t,n)=>{document.addEventListener(e.Obfuscator.obfuscate(t),async o=>{const s=e.Obfuscator.deobfuscate(o.detail);let a,r;try{r=await n(s)}catch(o){a=o}const i={data:r,_requestId:s._requestId,error:a};document.dispatchEvent(new CustomEvent(e.Obfuscator.obfuscate(`${t}Response`),{bubbles:!1,detail:e.Obfuscator.obfuscate(i)}))})},callRemoteDispatchedFunction:async(t,n={})=>new Promise((o,s)=>{const a=e.Extension._remoteDistachedFunctionRequestCounter++,r=e.Obfuscator.obfuscate(`${t}Response`),i=async t=>{const n=e.Obfuscator.deobfuscate(t.detail);return n._requestId===a?(document.removeEventListener(r,i),n.error?s(n.error):o(n.data)):null};document.addEventListener(r,i),document.dispatchEvent(new CustomEvent(e.Obfuscator.obfuscate(t),{bubbles:!1,detail:e.Obfuscator.obfuscate({...n,_requestId:a})}))}),runCommand:async(t,n={})=>await e.Extension.callRemoteDispatchedFunction("executeMineForExtensionCommand",{commandName:t,commandConfig:n}),getCurrentFocusedTabUrl:t=>e.Extension.runCommand("getCurrentFocusedTabUrl",t),openSideChat:t=>e.Extension.runCommand("openSideChat",t),getCurrentFocusedTabInfo:t=>e.Extension.runCommand("getCurrentFocusedTabInfo",t),openTab:async t=>await e.Extension.runCommand("openTab",t),closeTab:async t=>await e.Extension.runCommand("closeTab",t),copyText:t=>e.Extension.runCommand("copyText",{text:t}),getItems:async t=>await e.Extension.runCommand("getItems",{keys:t}),getItem:async t=>await e.Extension.runCommand("getItem",{key:t}),setItem:async(t,n)=>await e.Extension.runCommand("setItem",{key:t,value:n}),getIsHiddenMode:async()=>await e.Extension.runCommand("getIsHiddenMode"),setIsHiddenMode:async(t=!0)=>await e.Extension.runCommand("setIsHiddenMode",{isHidden:t}),fetchJson:async(t,n={})=>await e.Extension.runCommand("fetchJson",{url:t,options:n}),fetchText:async(t,n={})=>await e.Extension.runCommand("fetchText",{url:t,options:n}),askActiveChatAsync:async(t,n={})=>await e.Extension.runCommand("askActiveChatAsync",{message:t,options:n}),serveRemotePageApiAsync:async(t,n)=>{const o=document.createElement("div");o.id="__mine-page-api-bridge-host",o.style.display="none",document.body.appendChild(o);const s=o.attachShadow({mode:"open"}),a=document.createElement("textarea");a.style.display="none",a.value="",s.appendChild(a);const r=new MutationObserver(()=>{if(!a.value)return;const e=JSON.parse(a.value);if("call"!==e.type)return;const t=(e,t)=>{a.value=JSON.stringify({type:"response",ok:e,...e?{result:t}:{error:t}}),a.dataset.updated=Date.now().toString()},o=n[e.fnName];if(!o)return t(!1,`Unsupported API method: ${e.fnName}`);Promise.resolve(o(e.args)).then(e=>t(!0,e)).catch(e=>t(!1,e.message))});r.observe(a,{attributes:!0,attributeFilter:["data-call"]});const i=await e.Extension.runCommand("registerRemotePageApi",{serviceNameId:t});return!!i?.success||(r.disconnect(),o.remove(),!1)},askRemotePageApiAsync:async(t,n,o)=>await e.Extension.runCommand("askRemotePageApi",{serviceNameId:t,fnName:n,argsMap:o})},e.Chat={open:({baseUrl:t,params:n})=>{const o=`${t}/?loadType=data#data=${encodeURIComponent(btoa(unescape(encodeURIComponent(JSON.stringify(n)))))}`;e.Extension.openTab({url:o})}},e.CommandBar={_getCommandsFns:[],runCommandEphemerallyAsync:async t=>{let n=!1;t.title=`🤖 ${t.title}`,e.CommandBar.serveGetCommandsFnAsync(()=>n?[]:[t].filter(Boolean)),await e.CommandBar.executeCommandAsUserAsync(t.title),n=!0},executeFunctionAsStandaloneProcessAsync:async(t,n)=>{await e.CommandBar.runCommandEphemerallyAsync({title:t,run:n})},serveGetCommandsFnAsync:async t=>{const n=!e.CommandBar._getCommandsFns.length;if(e.CommandBar._getCommandsFns.push(t),n){let t=[];e.Extension.serveRemoteDispatchedFunction("getCommandBarCommands",async n=>(t=await Promise.all(e.CommandBar._getCommandsFns.map(async e=>{let t=[];try{t=await e()}catch(e){t.push({title:"⚠️ Error loading commands",subtitle:"Show error log",run:async()=>console.log(e)})}return t})).then(e=>e.flat()),{commandsLite:t.map(e=>({site:e.site,title:e.title,subtitle:e.subtitle,subtitleOnShift:e.subtitleOnShift,subtitleOnCmd:e.subtitleOnCmd,analytics:e.analytics,showHintNotToInteract:e.showHintNotToInteract,isStatusBar:e.isStatusBar,isForUnhandledCommand:e.isForUnhandledCommand,hideFromAi:e.hideFromAi,hotkeySequence:e.hotkeySequence}))})),e.Extension.serveRemoteDispatchedFunction("executeCommandBarCommand",async n=>{const{commandName:o,context:s={}}=n,a=t.find(e=>e.title===o);return s.getShouldInterruptAsync=async()=>await e.Extension.callRemoteDispatchedFunction("getCommandBarShouldInterruptForCommand",{commandName:o}),s.setStatus=async t=>await e.Extension.callRemoteDispatchedFunction("setCommandBarStatusForCommand",{commandName:o,statusText:t}),await a.run(s)})}const o=e.Obfuscator.obfuscate("minePageHasNewCommandBarCommands");document.dispatchEvent(new CustomEvent(o,{bubbles:!1})),sessionStorage.setItem(o,!0)},_servePageApiAlreadyInit:!1,serveGetPageApiWrapperFnAsync:async t=>{if(e.CommandBar._servePageApiAlreadyInit)throw"already initiated pageApi wrapper";let n;e.CommandBar._servePageApiAlreadyInit=!0;const o=e=>{const t=JSON.stringify(e,(e,t)=>"function"==typeof t?t.toString():t,2),n=JSON.parse(t);return Object.entries(n).map(([e,t])=>`${e}: ${t.split("=>")[0].trim()}`).map(e=>`* ${e}`).join("\n")};e.Extension.serveRemoteDispatchedFunction("getCommandBarPageApiWrapper",async e=>{const s=await t();return n=await s.getPageApi(),{site:s.site,aiBrand:s.aiBrand,pageInitialContext:await s.getPageInitialContext(),pageApiStr:o(n)}}),e.Extension.serveRemoteDispatchedFunction("executeCommandBarPageApiFn",async e=>{const{function_name:t,function_argument_object:o={}}=e,s=n[t];if(!s)throw"command not found";return await s(o)});const s=e.Obfuscator.obfuscate("minePageHasCommandBarPageApi");document.dispatchEvent(new CustomEvent(s,{bubbles:!1})),sessionStorage.setItem(s,!0)}},e.CommandBar.sgcfa=e.CommandBar.serveGetCommandsFnAsync,e.CommandBar.isCurrentUrlMatchedByPattern=(e="")=>window.location.href.toLowerCase().startsWith(e.toLowerCase())||window.location.href.match(new RegExp(e,"i")),e.CommandBar.buildCommandsIfAtSite=async(t,n)=>{if(!e.CommandBar.isCurrentUrlMatchedByPattern(t))return[];const o=await n();return o.forEach(e=>e.site=t),o},e.CB=e.CommandBar,e.waitForMaybeElement=t=>new Promise(async n=>{const o=await e.waitFor(t,{recheckIntervalMs:500,timeoutMs:1e4}).catch(()=>null);o&&n(o)}),e.TypingMind={_setChatStarter:async(t="",n="")=>{const o=await e.Extension.getItem("pepperSetDataKey");return!!o&&await(async()=>{const s=e=>btoa(String.fromCharCode(...(new TextEncoder).encode(e))),a=JSON.stringify({key:"chatStarterBuffer",data:{query:s(t.trim()),context:s((n??"").trim()),createdDate:Date.now()}}),r={method:"POST",headers:{"Content-Type":"application/json","pepper-api-key":o},body:a};return(await e.Extension.fetchJson("https://pepperpotts.fly.dev/apps/setData",r)).success})()},startChat:async(t="",n="")=>{await e.TypingMind._setChatStarter(t,n),window.open("https://www.typingmind.com/")}},e.TM=e.TypingMind,e.showFloatingMiniWindow=(e,t="Info",{paddingPx:n=10,positionEnum:o="CENTER",autoDim:s=!1}={})=>{const a=e instanceof Element,r=a?e:document.createElement("div");a||(r.innerHTML=e);const i=(e,t,n="")=>{const o=document.createElement(e);return o.style.cssText=t,o.textContent=n,o},c="opacity .15s ease-out, transform .15s cubic-bezier(0.175, 0.885, 0.32, 1.1)",l=i("div",`\n position: fixed;\n background: #2c2c2c;\n border: 1px solid #444;\n border-radius: 8px;\n box-shadow: 0 10px 25px rgba(0,0,0,0.5);\n min-width: 260px;\n max-width: 80vw;\n width: max-content;\n overflow: hidden;\n max-height: 80vh;\n display: flex;\n flex-direction: column;\n z-index: 1000;\n opacity: 0;\n transform: scale(0.97);\n transition: ${c};\n `);l.classList.add("mine-dialog");const m=l.attachShadow({mode:"open"}),d=document.createElement("style");d.textContent=`\n :host {color: #e0e0e0; font-family: Arial, sans-serif;}\n .handle {\n background: #383838;\n padding: 3px 12px 0;\n cursor: move;\n user-select: none;\n font-size: 14px;\n font-weight: bold;\n border-bottom: 1px solid #444;\n }\n .close-btn {\n float: right;\n cursor: pointer;\n font-size: 18px;\n line-height: 18px;\n color: #888;\n transition: opacity .1s ease-out, color .2s;\n opacity: 0;\n }\n .content-wrapper {\n padding: ${n}px;\n overflow-y: auto;\n flex-grow: 1;\n }\n `;const u=i("div","",t);u.className="handle";const p=i("span","","×");p.className="close-btn";const h=i("div","");h.className="content-wrapper",p.onmouseover=()=>p.style.color="#fff",p.onmouseout=()=>p.style.color="#888",p.onclick=()=>{l.style.opacity="0",l.style.transform="scale(0.97)",setTimeout(()=>document.body.removeChild(l),200)},u.appendChild(p),h.appendChild(r),m.appendChild(d),m.appendChild(u),m.appendChild(h),document.body.appendChild(l);const y=l.getBoundingClientRect(),g=window.innerWidth,f=window.innerHeight;l.style.left="RIGHT-CENTER"===o?.5*g+(.5*g-y.width)/2+"px":(g-y.width)/2+"px",l.style.top=(f-y.height)/2+"px",setTimeout(()=>{l.style.opacity=s&&!m.activeElement?"0.5":"1",l.style.transform="scale(1)"},10);let w,b,v,E,x=!1;if(u.addEventListener("mousedown",e=>{x=!0,w=e.clientX,b=e.clientY,v=l.offsetLeft,E=l.offsetTop,l.style.transition="none"}),document.addEventListener("mousemove",e=>{if(x){const t=e.clientY-b;l.style.left=`${v+(e.clientX-w)}px`,l.style.top=`${E+t}px`}}),document.addEventListener("mouseup",()=>{x=!1,l.style.transition=c}),u.addEventListener("mouseenter",()=>p.style.opacity="1"),u.addEventListener("mouseleave",()=>p.style.opacity="0"),s){const e=()=>{const e=!!m.activeElement,t=l.matches(":hover");l.style.opacity=e||t?"1":"0.5"};l.addEventListener("focusin",e),l.addEventListener("focusout",()=>setTimeout(e,0)),l.addEventListener("mouseenter",e),l.addEventListener("mouseleave",e)}return l},e.CommandBar.executeCommandAsUserAsync=async t=>{const n=e.Obfuscator.obfuscate("minePageHasNewCommandBarCommands");await e.waitFor(()=>!window.sessionStorage.getItem(n)),await e.Extension.callRemoteDispatchedFunction("executeCommandBarCommandVisibly",{commandName:t})},e.debugSoon=async()=>{await e.sleep(3e3)},e.Agent=class{constructor({systemPrompt:e,tools:t={}}){this.systemPrompt=e,this.tools=t,this.apiKey=null}async init(){return this.apiKey=await e.Extension.getItem("commandbar-anthropic-key").catch(()=>null),!!this.apiKey}async processQueryAsync(e){if(!this.apiKey)throw new Error("Agent not initialized - call agent.init() first");const t=[{role:"user",content:e}],n=Object.entries(this.tools).map(([e,t])=>({name:e,description:t.description,input_schema:t.input_schema}));return await this.#n(t,n)}async#n(e,t){const n={model:"claude-sonnet-4-0",temperature:1,stream:!1,messages:e,max_tokens:4096,system:this.systemPrompt,tools:t},o=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json",accept:"*/*","accept-language":"en-US,en;q=0.9","anthropic-dangerous-direct-browser-access":"true","anthropic-version":"2023-06-01","x-api-key":this.apiKey},body:JSON.stringify(n)}).then(e=>e.json()),s=o.content.filter(e=>"tool_use"===e.type);if(s.length){const n=await Promise.all(s.map(async({name:e,input:t,id:n})=>{const o=await this.tools[e].handler(t);return{type:"tool_result",tool_use_id:n,content:this.#o(o)}}));return e.push({role:"assistant",content:o.content},{role:"user",content:n}),await this.#n(e,t)}return o.content[0]?.text||"(no response)"}#o(e){try{return"function"==typeof e?"[Function]":"symbol"==typeof e?e.toString():"bigint"==typeof e?e.toString()+"n":"object"==typeof e?JSON.stringify(e,null,2):String(e)}catch(e){return`[Serialization Error: ${e.message}]`}}},e.pluralize=(e,t,n)=>{const o=1===e?t:n||`${t}s`;return`${e.toLocaleString()} ${o}`},e.getHumanizedTimeLabel=(e=new Date)=>{const t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][e.getDay()],n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][e.getMonth()],o=e.getDate(),s=e.getHours();return`${t} ${n} ${o}, ${0===s?12:s>12?s-12:s}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}${s>=12?"pm":"am"}`},e.getHumanizedDurationMs=(e,{compact:t=!1,ignoredUnits:n=[]}={})=>{const o=[{label:"w",ms:6048e5},{label:"d",ms:864e5},{label:"h",ms:36e5},{label:"m",ms:6e4},{label:"s",ms:1e3},{label:"ms",ms:1}].filter(e=>!n.includes(e.label));if(e<1)return`0${o[o.length-1].label}`;const s=[];let a=Math.floor(e);for(const e of o){const t=Math.floor(a/e.ms);if(t>0&&(s.push(`${t}${e.label}`),a-=t*e.ms,2===s.length))break}return 0===s.length&&s.push(`0${o[o.length-1].label}`),s.join(t?"":" ")},e.playGeneratedSoundAsync=async({type:e="success"}={})=>{const t={success:{wave:"sine",notes:[[523.25,0,.25],[659.25,.2,.25],[783.99,.4,.35]],wait:800},actionRequired:{wave:"triangle",notes:[[600,0,.25],[450,.25,.25],[600,.5,.25],[450,.75,.25]],wait:1050,envelope:"fade"},error:{wave:"square",notes:[[440,0,.15],[349.23,.2,.3]],wait:550},warning:{wave:"triangle",notes:[[659.25,0,.15],[622.25,.2,.2],[659.25,.4,.15]],wait:600},info:{wave:"sine",notes:[[783.99,0,.2]],wait:250}}[e];if(!t)return;const n=new(window.AudioContext||window.webkitAudioContext),o=n.createGain();o.connect(n.destination),o.gain.value=.25;const s=n.currentTime;for(const[e,a,r]of t.notes){const i=n.createOscillator(),c=n.createGain();i.type=t.wave,i.frequency.value=e,i.connect(c),c.connect(o);const l=s+a;"fade"===t.envelope?(c.gain.setValueAtTime(0,l),c.gain.linearRampToValueAtTime(.5,l+.05),c.gain.linearRampToValueAtTime(0,l+r)):(c.gain.setValueAtTime(.8,l),c.gain.exponentialRampToValueAtTime(.01,l+r)),i.start(l),i.stop(l+r)}await new Promise(e=>setTimeout(e,t.wait)),await n.close()},e};window.Mine=buildMine();