001 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
002 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
003 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
004 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
005 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
006 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
007 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
008 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
009 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
010 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
011 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
012 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
013 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
014 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
015 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
016 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
017 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
018 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();001 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
002 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
003 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
004 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
005 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
006 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
007 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
008 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
009 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
010 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
011 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
012 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
013 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
014 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
015 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
016 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
017 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();
018 const AEGIS_NATIVE_REFERENCES=(()=>{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{},t=e.navigator?.clipboard||null;return{xhrOpen:e.XMLHttpRequest?.prototype?.open??null,xhrSend:e.XMLHttpRequest?.prototype?.send??null,wasmInstantiate:e.WebAssembly?.instantiate??null,wasmInstantiateStreaming:e.WebAssembly?.instantiateStreaming??null,fetch:e.fetch??null,webSocket:e.WebSocket??null,webSocketSend:e.WebSocket?.prototype?.send??null,worker:e.Worker??null,idbPut:e.IDBObjectStore?.prototype?.put??null,clipboardReadText:t?.readText??null,clipboardRead:t?.read??null,clipboardWrite:t?.write??null,clipboardWriteText:t?.writeText??null,documentExecCommand:e.Document?.prototype?.execCommand??e.document?.execCommand??null}})();class AegisCodexEngine{constructor(e={}){this.processId='AEGIS-EVADE-${Math.floor(1e5*Math.random())}',this.config={policy:{allowSelectors:["#app","[data-safe]","#main","#content",".radix-themes",".app-wrapper","#main-content"],logMutations:!0,revertMutations:!0,freezeConsole:!0},keepAlive:{wakeLockScreen:!0,wakeLockRetryDelay:100,silentAudioInterval:500,aggressiveTickInterval:100,driftThreshold:200},network:{monitorXHR:!0,monitorWASM:!0,monitorWS:!0,monitorWorker:!0,monitorIDB:!0,truncateResponseLen:2e3},memory:{purgeOnMutationBurst:!0,autoPurgeMutationThreshold:5e4,exposeEnabledToolsAlias:!0,contextSearchMaxResults:5e3,contextSearchPreviewLength:5240,contextSearchMaxDepth:250},evasion:{targetKeyToSearch:/appState|estate.*app|_state|enabledTools|on_brigading|__x_state/i,blockEvents:["visibilitychange","blur","mouseleave","freeze","pagehide","pageshow","copy","cut","paste"],forceVisibilityState:"visible",forceHiddenState:!1,spoofIsTrusted:!0,mouseSimulationInterval:4e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400,bootstrapDelayMs:10,delayJitterMs:8,pauseJitterMs:50,jitterAmplitude:1.5,exitX:-1,yBaseRatio:.4,yRandomRatio:.2}},...e},this.state={history:[],currentState:"INIT",discoveredItems:[],contextSearchResults:[],lastContextSearchMeta:null,visitedObjects:new WeakSet,mitigationLog:[],audioContextRef:null,blockedMutationCount:0,trace:{ws:[],idb:[],fetch:[],worker:[],errors:[],mutations:[]},...Object.fromEntries(["domFirewallInstalled","xhrSnifferInstalled","wasmHookInstalled","wsHookInstalled","workerHookInstalled","idbHookInstalled","clipboardGuardInstalled","diagnosticsInstalled","focusHardeningInstalled","keepAliveInstalled","autoStartCompleted","blockingModePrimed"].map(e=>[e,!1]))},this.nativeReferences=AEGIS_NATIVE_REFERENCES,this.nativoToString=Function.prototype.toString,this.instrumentedWebSockets="function"==typeof WeakSet?new WeakSet:null,this.instrumentedWebSocketMarker="function"==typeof Symbol?Symbol("aegisWsInstrumented"):"__aegisWsInstrumented",this.startPromise=null,this.mouseSimulationIntervalRef=null,this.discoveryTimeoutRef=null,this.internalMutationBypassDepth=0,this.safeConsoleWarn=null,this._applyWakeLockCompleteTimingProfile(),this.updateState("INIT",{msg:"Sovereign Codex instance established."}),this.primeBlockingMode()}updateState(e,t={}){this.state.currentState=e;const o={timestamp:(new Date).toISOString(),processId:this.processId,state:this.state.currentState,payload:JSON.parse(JSON.stringify(t))};this.state.history.push(o),this.config.policy.logMutations&&"SCANNING_HEAP"!==e&&console.log('%c[AEGIS STATE] [${this.state.currentState}]',"color: #00ffff; font-weight: bold;",o.payload)}getHistory(){return Object.freeze([...this.state.history])}logMitigation(e,t){try{let o=null;if(null!=t)if(t instanceof Error)o={message:t.message,stack:t.stack};else if("object"==typeof t)try{o=JSON.parse(JSON.stringify(t))}catch{o={rawString:String(t)}}else o=String(t);if(this.state.mitigationLog.push({timestamp:Date.now(),type:String(e),details:o}),"Error instrumenting event descriptors"===e)return;const n=this._getSafeConsoleWarn();"function"==typeof n&&n('%c[AEGIS MITIGATION DETECTED] ${e}',"color: #ffaa00; font-weight: bold;",o)}catch(e){}}_applyNativeCamouflage(e,t){try{e.toString=()=>this.nativoToString.call(t)}catch(e){}}_isInternalMutationBypassed(){return this.internalMutationBypassDepth>0}_runWithInternalMutationBypass(e){this.internalMutationBypassDepth++;try{return e()}finally{this.internalMutationBypassDepth=Math.max(0,this.internalMutationBypassDepth-1)}}_getSafeConsoleWarn(){if("function"==typeof this.safeConsoleWarn)return this.safeConsoleWarn;try{if("undefined"!=typeof document){const e=document.body||document.documentElement;e&&(this.safeConsoleWarn=this._runWithInternalMutationBypass(()=>{const t=document.createElement("iframe");t.style.display="none",e.appendChild(t);try{const e=t.contentWindow?.console;if(e&&"function"==typeof e.warn)return e.warn.bind(e)}finally{t.parentNode===e&&e.removeChild(t)}}))}}catch(e){}return"function"!=typeof this.safeConsoleWarn&&(this.safeConsoleWarn=Function.prototype.bind.call(console.warn,console)),this.safeConsoleWarn}_normalizeContextSearchQuery(e,t={}){const o=Number.isFinite(t.maxDepth)?Math.max(0,t.maxDepth):this.config.memory.contextSearchMaxDepth,n=Number.isFinite(t.maxResults)?Math.max(1,t.maxResults):this.config.memory.contextSearchMaxResults,s=Number.isFinite(t.maxPreviewLength)?Math.max(32,t.maxPreviewLength):this.config.memory.contextSearchPreviewLength,i=!1!==t.includeDOM;if(e instanceof RegExp||!0===t.regex){const a=e instanceof RegExp?new RegExp(e.source,e.flags):new RegExp(String(e??""),"string"==typeof t.flags?t.flags:t.caseSensitive?"":"i");return{mode:"regex",label:String(a),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>null!=e&&(a.lastIndex=0,a.test(String(e)))}}const a=t.caseSensitive?String(e??"").trim():String(e??"").trim().toLowerCase();if(!a)throw new Error("Context search query cannot be empty.");return{mode:"string",label:String(e),maxDepth:o,maxResults:n,maxPreviewLength:s,includeDOM:i,match:e=>{if(null==e)return!1;const o=String(e);return(t.caseSensitive?o:o.toLowerCase()).includes(a)}}}_previewContextSearchValue(e,t=this.config.memory.contextSearchPreviewLength){let o;return o=null===e?"null":void 0===e?"undefined":"function"==typeof e?'[Function ${e.name||"anonymous"}]':"undefined"!=typeof Element&&e instanceof Element?'<${e.tagName.toLowerCase()}>${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}':Array.isArray(e)?'Array(${e.length})':e instanceof Map||e instanceof Set?'${e.constructor.name}(${e.size})':"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)?'${e.constructor.name}(${e.length??e.byteLength})':"object"==typeof e?e.constructor?.name?'[${e.constructor.name}]':"[Object]":String(e),o.length>t?'${o.slice(0,t)}... [Truncated]':o}async recursiveContextSearch(e,t,o="window",n=0,s=null){const i=s||{visited:new WeakSet,results:[],inspectedEntries:0};if(n>t.maxDepth||!e||"object"!=typeof e&&"function"!=typeof e||i.visited.has(e))return i;i.visited.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket&&this._attachWebSocketTrafficProbe(e);try{const s=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const a of s){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const s=Object.getOwnPropertyDescriptor(e,a);if(s&&"function"==typeof s.get&&!s.configurable)continue;const r=s&&("function"==typeof s.get||s.set),c="symbol"==typeof a?a.toString():String(a);let l=null,u="[Dynamic Getter Camouflaged Symbol]";if(!r){try{l=e[a]}catch{continue}u=this._previewContextSearchValue(l,t.maxPreviewLength)}const d='${o}.${c}',h=[];t.match(d)&&h.push("path"),t.match(c)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&(i.results.push(Object.freeze({path:d,key:c,preview:u,matchedOn:Object.freeze([...h]),value:r?u:l,object:e})),this.config.policy.logMutations&&console.log('%c[AEGIS CONTEXT SEARCH HIT] ${d}',"color: #7dd3fc; font-weight: bold;",{matchedOn:h,preview:u})),i.inspectedEntries%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),r||!l||"object"!=typeof l&&"function"!=typeof l||await this.recursiveContextSearch(l,t,d,n+1,i)}if(e instanceof Map||e instanceof Set){let s=0;for(const a of e.entries()){if(i.results.length>=t.maxResults)break;i.inspectedEntries++;const[r,c]=e instanceof Map?a:[a[0],a[0]],l=this._previewContextSearchValue(r,t.maxPreviewLength),u=this._previewContextSearchValue(c,t.maxPreviewLength),d='${o}.<${e.constructor.name}:${++s}:${l}>',h=[];t.match(d)&&h.push("path"),t.match(l)&&h.push("key"),t.match(u)&&h.push("value"),h.length>0&&i.results.push(Object.freeze({path:d,key:e instanceof Map?l:'Set:${s}',preview:u,matchedOn:Object.freeze([...h]),value:c,object:e})),!r||"object"!=typeof r&&"function"!=typeof r||await this.recursiveContextSearch(r,t,'${d}.key',n+1,i),c&&("object"==typeof c||"function"==typeof c)&&e instanceof Map&&await this.recursiveContextSearch(c,t,'${d}.value',n+1,i)}}}catch(e){}return i}async searchContextRecursive(e,t={}){const o=this._normalizeContextSearchQuery(e,t),n={visited:new WeakSet,results:[],inspectedEntries:0};if(this.updateState("CONTEXT_SEARCH",{query:o.label,mode:o.mode}),"undefined"!=typeof window&&await this.recursiveContextSearch(window,o,"window",0,n),o.includeDOM&&"undefined"!=typeof document){const e=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))].filter(Boolean);let t=0;for(const s of e){if(n.results.length>=o.maxResults)break;if(!s||"object"!=typeof s)continue;++t%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0));const e='DOM <${s.tagName?.toLowerCase()||"element"}>${s.id?"#"+s.id:""}${"string"==typeof s.className&&s.className?"."+Array.from(s.classList).join("."):""}';if("function"==typeof s.hasAttributes&&s.hasAttributes())for(const t of Array.from(s.attributes||[])){const i='${e} Attr:[${t.name}="${t.value}"]',a=[];o.match(i)&&a.push("path"),o.match(t.name)&&a.push("attributeName"),o.match(t.value)&&a.push("attributeValue"),a.length>0&&n.results.push(Object.freeze({path:i,key:t.name,preview:t.value,matchedOn:Object.freeze([...a]),value:s,object:s}))}if("string"==typeof s.textContent&&s.textContent.trim()){const t=s.textContent.trim(),i=this._previewContextSearchValue(t,o.maxPreviewLength),a=[];o.match('${e}.textContent')&&a.push("path"),o.match("textContent")&&a.push("key"),o.match(i)&&a.push("value"),a.length>0&&n.results.push(Object.freeze({path:'${e}.textContent',key:"textContent",preview:i,matchedOn:Object.freeze([...a]),value:t,object:s}))}await this.recursiveContextSearch(s,o,e,0,n)}}return this.state.contextSearchResults=Object.freeze([...n.results]),this.state.lastContextSearchMeta=Object.freeze({query:o.label,mode:o.mode,totalFound:n.results.length,inspectedEntries:n.inspectedEntries,startedAt:(new Date).toISOString(),finishedAt:(new Date).toISOString()}),this.publishDiscoveryResults(this.state.contextSearchResults.length>0?"__aegisContextSearchResults":null,this.state.contextSearchResults),this.updateState("CONTEXT_SEARCH_FINISHED",{query:o.label,totalFound:n.results.length,inspectedEntries:n.inspectedEntries}),this.getContextSearchResults()}getContextSearchResults(){return Object.freeze([...this.state.contextSearchResults||[]])}_installHardClipboardHandlerBlock(e,t){if(!e)return;const o=this;["oncopy","oncut","onpaste"].forEach(n=>{try{const s=Object.getOwnPropertyDescriptor(e,n);if(!1===s?.configurable)return;Object.defineProperty(e,n,{configurable:!0,enumerable:s?.enumerable??!1,get:()=>null,set(e){"function"==typeof e&&o.logMitigation("Clipboard handler property blocked",{owner:t,property:n,handler:e.name||"anonymous"})}})}catch(e){o.logMitigation("Clipboard handler hardening failed",{owner:t,property:n,error:e?.message})}})}_installHardClipboardExecCommandBlock(e,t){if(!e||"function"!=typeof e.execCommand)return!1;const o=this,n=e===Document.prototype&&"function"==typeof this.nativeReferences.documentExecCommand?this.nativeReferences.documentExecCommand:e.execCommand;return e.execCommand=function(e,...s){const i=String(e||"").toLowerCase();return["copy","cut","paste"].includes(i)?(o.logMitigation("Clipboard execCommand blocked",{owner:t,command:i}),!1):n.call(this,e,...s)},this._applyNativeCamouflage(e.execCommand,n),!0}_recordWebSocketTrace(e,t,o=null){const n={dir:e,data:t,ts:Date.now()};o&&"string"==typeof o.url&&(n.url=o.url),this.state.trace.ws.push(n),this.config.policy.logMutations&&console.log("in"===e?"📥 [AEGIS WS IN]":"📤 [AEGIS WS OUT]",t)}_attachWebSocketTrafficProbe(e){if(!e||"function"!=typeof e.addEventListener)return e;try{if(this.instrumentedWebSockets){if(this.instrumentedWebSockets.has(e))return e;this.instrumentedWebSockets.add(e)}else{if(e[this.instrumentedWebSocketMarker])return e;Object.defineProperty(e,this.instrumentedWebSocketMarker,{value:!0,configurable:!0})}e.addEventListener("message",t=>this._recordWebSocketTrace("in",t.data,e))}catch(e){this.logMitigation("WebSocket inbound probe attach failure",e)}return e}_scanWindowForWebSocketHandles(){if("undefined"==typeof window)return 0;const e=[this.nativeReferences.webSocket,"function"==typeof window.WebSocket?window.WebSocket:null].filter(e=>"function"==typeof e);if(0===e.length)return 0;let t=0;return Object.getOwnPropertyNames(window).forEach(o=>{try{const n=window[o];if(e.some(e=>n instanceof e)){const e=this.instrumentedWebSockets?this.instrumentedWebSockets.has(n):Boolean(n?.[this.instrumentedWebSocketMarker]);this._attachWebSocketTrafficProbe(n),e||t++}}catch{}}),t}_matchesTarget(e){const t=this.config.evasion.targetKeyToSearch;return"string"==typeof e&&(t instanceof RegExp?(t.lastIndex=0,t.test(e)):e===t)}_getWakeLockCompleteTimingProfile(){return{wakeLockRetryMs:100,audioResumeInterval:500,aggressiveTickInterval:100,driftThreshold:200,initialMousePauseMs:10,stepDelayRandomMs:8,endPauseRandomMs:50,jitterAmplitude:1.5,movementNoiseAmplitude:0,fixedYBaseRatio:.4,fixedYRandomRatio:.2,leaveX:-1,mouseSimulationInterval:1e3,mouseParams:{startX:-5,endX:43,steps:35,delayMs:14,pauseAtEnd:400}}}_applyWakeLockCompleteTimingProfile(){const e=this._getWakeLockCompleteTimingProfile(),t=this.config.evasion.mouseParams||{};-5===t.startX&&43===t.endX&&38===t.steps&&13===t.delayMs&&450===t.pauseAtEnd&&(this.config.evasion.mouseParams={...t,...e.mouseParams}),this.config.evasion.mouseSimulationInterval??=e.mouseSimulationInterval,this.config.keepAlive.silentAudioInterval??=e.audioResumeInterval,this.config.keepAlive.aggressiveTickInterval??=e.aggressiveTickInterval,this.config.keepAlive.driftThreshold??=e.driftThreshold}isAllowedNode(e){return!(e instanceof Element)||this.config.policy.allowSelectors.some(t=>{try{return e.matches(t)||e.closest(t)}catch{return!1}})}_extractDisplayValues(e){const t={title:null,displayText:null};if(!e||"object"!=typeof e)return t;try{if(e.getAttribute&&(t.title=e.getAttribute("title")||null),"string"==typeof e.textContent&&e.textContent.trim()?t.displayText=e.textContent.trim():e.innerText&&(t.displayText=e.innerText.trim()),!t.displayText&&e.querySelector){const o=e.querySelector('span[dir="ltr"], span');o&&(t.displayText=o.textContent.trim())}}catch{}return t}_aggregateHtmlData(e,t=800){if(!e)return"[null]";const o=this._extractDisplayValues(e);let n=(o.title?'[TITLE: ${o.title}] ':"")+(o.displayText?'[TEXT: ${o.displayText}] ':"");try{const o=e.outerHTML||e.innerHTML||"";return n+(o.length>t?o.substring(0,t)+"... [Truncated]":o)}catch(e){return n+'[HTML Error: ${e.message}]'}}_logMutation(e,t,o={}){if(!this.config.policy.logMutations)return;const n=t?this._aggregateHtmlData(t):null,s={type:e,target:t&&(t.nodeName||t.id)||"unknown",title:t instanceof Element?t.tagName:String(t),ts:Date.now(),htmlSnapshot:n?n.substring(0,500)+(n.length>500?"...":""):null,fullHtmlLength:n?n.length:0,...o};this.state.trace.mutations.push(s),console.log('%c[AEGIS MUTATION] ${e}',"color: #a3e635; font-weight: bold;",s)}initDomFirewall(){if(this.state.domFirewallInstalled)return;this.state.domFirewallInstalled=!0;const e=this;["appendChild","removeChild","insertBefore","replaceChild"].forEach(t=>{const o=Node.prototype[t];Node.prototype[t]=function(...n){if(e._isInternalMutationBypassed())return o.apply(this,n);const s=n[0];return e.isAllowedNode(this)&&e.isAllowedNode(s)?(e._logMutation("ALLOWED_"+t,this,{targetNode:s?s.nodeName:null,added:!0,htmlSnapshot:e._aggregateHtmlData(s)}),o.apply(this,n)):(e.state.blockedMutationCount++,e._logMutation("BLOCKED_"+t,this,{blockedTarget:s?s.nodeName:null,reason:"not in allowSelectors",htmlSnapshot:e._aggregateHtmlData(s)}),e.config.memory.purgeOnMutationBurst&&e.state.blockedMutationCount%e.config.memory.autoPurgeMutationThreshold===0&&e.purgeDetachedNodes(),s)},e._applyNativeCamouflage(Node.prototype[t],o)});const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(o,n){return e._isInternalMutationBypassed()||e.isAllowedNode(this)?t.call(this,o,n):void 0},this._applyNativeCamouflage(Element.prototype.setAttribute,t);new MutationObserver(t=>{t.forEach(t=>{const o={mutationType:t.type,target:t.target?t.target.nodeName:null,addedNodesCount:t.addedNodes?.length??0,removedNodesCount:t.removedNodes?.length??0,attributeName:t.attributeName,attributeOldValue:t.oldValue,addedHtml:t.addedNodes?.length>0?Array.from(t.addedNodes).map(t=>e._aggregateHtmlData(t,300)).join(" | "):null};e._logMutation("OBSERVED_"+t.type,t.target,o),!e.isAllowedNode(t.target)&&e.config.policy.revertMutations&&"childList"===t.type&&t.addedNodes.forEach(e=>{"function"==typeof e.remove&&e.remove()})})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0})}initFocusHardening(){if(this.state.focusHardeningInstalled)return;this.state.focusHardeningInstalled=!0,Object.defineProperty(document,"visibilityState",{get:()=>this.config.evasion.forceVisibilityState,configurable:!0}),Object.defineProperty(document,"hidden",{get:()=>this.config.evasion.forceHiddenState,configurable:!0}),document.hasFocus=()=>!0;const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,o,n){if(!this.config?.evasion?.blockEvents?.includes(t))return e.apply(this,arguments)},this._applyNativeCamouflage(EventTarget.prototype.addEventListener,e),this.config.evasion.blockEvents.forEach(e=>{const t=e=>{e.stopImmediatePropagation(),e.preventDefault()};window.addEventListener(e,t,!0),document.addEventListener(e,t,!0)})}async initKeepAlivePipeline(){if(this.state.keepAliveInstalled)return;if(this.state.keepAliveInstalled=!0,this.config.keepAlive.wakeLockScreen&&"wakeLock"in navigator){const e=async()=>{try{(await navigator.wakeLock.request("screen")).addEventListener("release",()=>setTimeout(e,100))}catch{}};e().catch(()=>{})}const e=()=>{if(!this.state.audioContextRef)try{this.state.audioContextRef=new(window.AudioContext||window.webkitAudioContext);const e=this.state.audioContextRef.createOscillator(),t=this.state.audioContextRef.createGain();t.gain.value=0,e.connect(t),t.connect(this.state.audioContextRef.destination),e.start(),setInterval(()=>{"suspended"===this.state.audioContextRef?.state&&this.state.audioContextRef.resume()},this.config.keepAlive.silentAudioInterval)}catch{}};["click","keydown"].forEach(t=>document.addEventListener(t,e,{once:!0}));let t=Date.now();const o=()=>{const e=Date.now(),n=e-t-this.config.keepAlive.aggressiveTickInterval;n>this.config.keepAlive.driftThreshold&&(this.state.trace.errors.push({type:"clock_drift",ts:Date.now(),drift:n}),this.state.audioContextRef?.resume(),this.logMitigation("Clock drift corrected",{driftDetected:n})),t=e,setTimeout(o,this.config.keepAlive.aggressiveTickInterval)};o()}criaSpoofedEvent(e,t={}){const o=new PointerEvent(e,{bubbles:!0,cancelable:!0,composed:!0,view:window,...t}),n=new Proxy(o,{get:(e,o,n)=>"isTrusted"===o||("toString"===o?()=>'[object ${"touch"===t.pointerType?"TouchEvent":"MouseEvent"}]':Reflect.get(e,o,n)),getPrototypeOf:()=>MouseEvent.prototype});if(this.config.evasion.spoofIsTrusted)try{Object.defineProperty(n,"isTrusted",{get:()=>!0,configurable:!0,enumerable:!0});const e=Object.getOwnPropertyDescriptor;Object.getOwnPropertyDescriptor=function(t,o){return t===n&&"isTrusted"===o?void 0:e.apply(this,arguments)},this._applyNativeCamouflage(Object.getOwnPropertyDescriptor,e)}catch(e){}return n}fireMouseEvent(e,t,o){const n=this._getWakeLockCompleteTimingProfile(),s=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),buttons:0,button:0,movementX:this.jitter(0,n.movementNoiseAmplitude),movementY:this.jitter(0,n.movementNoiseAmplitude)});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(s)}catch(e){}}firePointerEvent(e,t,o){const n=this.criaSpoofedEvent(e,{clientX:t,clientY:o,screenX:t+(window.screenX||0),screenY:o+(window.screenY||0),pointerId:1,pointerType:"mouse",isPrimary:!0,pressure:0,buttons:0});try{(document.elementFromPoint(Math.max(0,t),o)||document.body).dispatchEvent(n)}catch(e){}}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}jitter(e,t=1.8){return e+(Math.random()*t*2-t)}lerp(e,t,o){return e+(t-e)*o}sleep(e){return new Promise(t=>setTimeout(t,e))}async simulateMouseMotion(e=null){const t=this._getWakeLockCompleteTimingProfile(),o=e?{...this.config.evasion.mouseParams,...e}:this.config.evasion.mouseParams,n=o.y??Math.floor(window.innerHeight*(o.yBaseRatio??t.fixedYBaseRatio)+Math.random()*window.innerHeight*(o.yRandomRatio??t.fixedYRandomRatio));this.fireMouseEvent("mouseenter",0,n),await this.sleep(o.bootstrapDelayMs??t.initialMousePauseMs);const s=async(e,s)=>{for(let i=0;i<=o.steps;i++){const a=this.easeInOut(i/o.steps),r=Math.round(Math.max(0,this.lerp(e,s,a))),c=Math.round(this.jitter(n,o.jitterAmplitude??t.jitterAmplitude));this.fireMouseEvent("mousemove",r,c),this.firePointerEvent("pointermove",r,c),await this.sleep(o.delayMs+Math.random()*(o.delayJitterMs??t.stepDelayRandomMs))}};await s(o.startX,o.endX),await this.sleep(o.pauseAtEnd+Math.random()*(o.pauseJitterMs??t.endPauseRandomMs)),await s(o.endX,o.startX),this.fireMouseEvent("mouseleave",o.exitX??t.leaveX,n),this.fireMouseEvent("mouseout",o.exitX??t.leaveX,n)}async deepSearchMemory(e,t="window",o=0){if(!(o>25||!e||"object"!=typeof e||this.state.visitedObjects.has(e)))if(this.state.visitedObjects.add(e),this.nativeReferences.webSocket&&e instanceof this.nativeReferences.webSocket)this._attachWebSocketTrafficProbe(e);else try{for(const n of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,n);if(s&&"function"==typeof s.get&&!s.configurable)continue;const i=s&&("function"==typeof s.get||s.set);if(this._matchesTarget(n)){let o=i?"[Dynamic Getter Camouflaged Symbol]":null;if(!i)try{o=e[n]}catch{continue}this.state.discoveredItems.push(Object.freeze({path:'${t}.${n}',value:o,object:e}))}if(this.state.discoveredItems.length%50==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),i||!Object.prototype.hasOwnProperty.call(e,n))continue;let a;try{a=e[n]}catch{continue}a&&"object"==typeof a&&await this.deepSearchMemory(a,'${t}.${n}',o+1)}}catch(e){}}async executeFullDiscoveryScan(){const e=this.config.evasion.targetKeyToSearch,t=e instanceof RegExp;this.updateState("SCANNING_HEAP",{target:String(e)}),this.state.discoveredItems=[],this.state.visitedObjects=new WeakSet,await this.deepSearchMemory(window,"window");const o=[document,document.documentElement,document.body,...Array.from(document.querySelectorAll("*"))];let n=0;for(const e of o){if(!e||"object"!=typeof e)continue;if(++n%100==0&&await new Promise(e=>"function"==typeof requestIdleCallback?requestIdleCallback(e):setTimeout(e,0)),t&&"function"==typeof e.hasAttributes&&e.hasAttributes())for(const t of Array.from(e.attributes||[]))(this._matchesTarget(t.name)||this._matchesTarget(t.value))&&this.state.discoveredItems.push(Object.freeze({path:'DOM <${e.tagName.toLowerCase()}> Attr:[${t.name}="${t.value}"]',value:e,object:e}));const o=e.tagName?'<${e.tagName.toLowerCase()}>':"element";await this.deepSearchMemory(e,'DOM ${o}${e.id?"#"+e.id:""}${"string"==typeof e.className&&e.className?"."+Array.from(e.classList).join("."):""}')}const s=this.state.discoveredItems.length>0;this.publishDiscoveryResults(s?"__aegisDiscoveryResults":null,this.state.discoveredItems),this.config.memory.exposeEnabledToolsAlias&&this.publishDiscoveryResults(s?"__enabledToolsResults":null,this.state.discoveredItems),this.updateState("SCAN_FINISHED",{totalFound:this.state.discoveredItems.length})}initXhrSniffer(){if(this.state.xhrSnifferInstalled||!this.config.network.monitorXHR||"undefined"==typeof XMLHttpRequest||!this.nativeReferences.xhrOpen||!this.nativeReferences.xhrSend)return;this.state.xhrSnifferInstalled=!0;const e=this;XMLHttpRequest.prototype.open=function(t,o,...n){return this._aegisContext={method:t,url:o,start:Date.now()},e.nativeReferences.xhrOpen.apply(this,[t,o,...n])},XMLHttpRequest.prototype.send=function(t,...o){this._aegisContext&&(this._aegisContext.payload=t??null);const n=()=>{if(4===this.readyState)try{let t="arraybuffer"===this.responseType||"blob"===this.responseType?'[Binary Data Buffer Object - Type: ${this.responseType}]':e.parseXhrResponseBody(this.responseText);e.state.trace.fetch.push({args:[this._aegisContext?.url,{method:this._aegisContext?.method}],ts:Date.now()}),e.imprimirPainelXhr({url:this._aegisContext?.url||"Unknown",metodo:this._aegisContext?.method||"GET",status:this.status,tempoRespostaMs:Date.now()-(this._aegisContext?.start??Date.now())+"ms",requestBody:this._aegisContext?.payload,responseBody:t})}catch{}finally{delete this._aegisContext,this.removeEventListener("readystatechange",n)}};return this.addEventListener("readystatechange",n),e.nativeReferences.xhrSend.apply(this,[t,...o])},this._applyNativeCamouflage(XMLHttpRequest.prototype.open,this.nativeReferences.xhrOpen),this._applyNativeCamouflage(XMLHttpRequest.prototype.send,this.nativeReferences.xhrSend),this.nativeReferences.fetch&&(window.fetch=async(...e)=>(this.state.trace.fetch.push({args:e,ts:Date.now()}),this.nativeReferences.fetch(...e)),this._applyNativeCamouflage(window.fetch,this.nativeReferences.fetch))}parseXhrResponseBody(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.substring(0,this.config.network.truncateResponseLen)+"... [Truncated]"}}imprimirPainelXhr(e){const t=e.status>=200&&e.status<300?"#00ff00":"#ff3333";console.group('%c[XHR NETWORK EVENT] -> ${e.metodo} | ${String(e.url).substring(0,50)}...','color: ${t}; font-weight: bold;'),console.log('%cStatus Code:%c ${e.status} %c| Latency:%c ${e.tempoRespostaMs}',"color: #aaa;",'color: ${t}; font-weight: bold;',"color: #aaa;","color: #ffcc00;"),e.requestBody&&console.dir(e.requestBody),console.dir(e.responseBody),console.groupEnd()}initWasmHook(){if(this.state.wasmHookInstalled||!this.config.network.monitorWASM||"undefined"==typeof WebAssembly||!this.nativeReferences.wasmInstantiate||!this.nativeReferences.wasmInstantiateStreaming)return;this.state.wasmHookInstalled=!0;const e=this;WebAssembly.instantiate=function(t,o,...n){return e.nativeReferences.wasmInstantiate.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.exports"),t))},WebAssembly.instantiateStreaming=function(t,o,...n){return e.nativeReferences.wasmInstantiateStreaming.apply(this,[t,o,...n]).then(t=>(t.instance?.exports&&e.deepSearchMemory(t.instance.exports,"Wasm.streamingExports"),t))},this._applyNativeCamouflage(WebAssembly.instantiate,this.nativeReferences.wasmInstantiate),this._applyNativeCamouflage(WebAssembly.instantiateStreaming,this.nativeReferences.wasmInstantiateStreaming)}initWebSocketHook(){if(this.state.wsHookInstalled||!this.config.network.monitorWS)return;const e=this.nativeReferences.webSocket||("undefined"!=typeof WebSocket?WebSocket:null);if(!e?.prototype)return;this.state.wsHookInstalled=!0;const t=this;[e.prototype,..."function"==typeof WebSocket?[WebSocket.prototype]:[]].forEach(o=>{const n=o===e.prototype&&"function"==typeof t.nativeReferences.webSocketSend?t.nativeReferences.webSocketSend:o.send;"function"==typeof n&&(o.send=function(e){return t._attachWebSocketTrafficProbe(this),t._recordWebSocketTrace("out",e,this),n.call(this,e)},t._applyNativeCamouflage(o.send,n))});const o=function(...o){return t._attachWebSocketTrafficProbe(new e(...o))};o.prototype=e.prototype;try{Object.setPrototypeOf(o,e)}catch{}window.WebSocket=o,this._applyNativeCamouflage(window.WebSocket,e),this._scanWindowForWebSocketHandles()}initWorkerHook(){if(this.state.workerHookInstalled||!this.config.network.monitorWorker||"undefined"==typeof Worker||!this.nativeReferences.worker)return;this.state.workerHookInstalled=!0;const e=this,t=function(...t){const o=new e.nativeReferences.worker(...t);o.addEventListener("message",t=>{e.state.trace.worker.push({dir:"in",data:t.data,ts:Date.now()})});const n=o.postMessage;return o.postMessage=function(t){return e.state.trace.worker.push({dir:"out",data:t,ts:Date.now()}),n.call(this,t)},e._applyNativeCamouflage(o.postMessage,n),o};t.prototype=this.nativeReferences.worker.prototype,window.Worker=t,this._applyNativeCamouflage(window.Worker,this.nativeReferences.worker)}initIndexedDBHook(){if(this.state.idbHookInstalled||!this.config.network.monitorIDB||"undefined"==typeof IDBObjectStore||!this.nativeReferences.idbPut)return;this.state.idbHookInstalled=!0;const e=this;IDBObjectStore.prototype.put=function(t){return e.state.trace.idb.push({store:this.name,value:t,ts:Date.now()}),e.nativeReferences.idbPut.apply(this,arguments)},this._applyNativeCamouflage(IDBObjectStore.prototype.put,this.nativeReferences.idbPut)}initClipboardGuard(){if(this.state.clipboardGuardInstalled)return;this.state.clipboardGuardInstalled=!0;const e=this,t="undefined"!=typeof navigator?navigator:null;t?.clipboard&&[["readText",""],["read",[]],["write",null],["writeText",null]].forEach(([o,n])=>{const s=e.nativeReferences['clipboard${o.charAt(0).toUpperCase()+o.slice(1)}'];s&&(t.clipboard[o]=function(t){return e.logMitigation('Clipboard Action Blocked: ${o}',{itemLen:t?.length??t?.items?.length}),null===n?Promise.resolve():Promise.resolve(n)},e._applyNativeCamouflage(t.clipboard[o],s))});try{const e="undefined"!=typeof Document&&Document.prototype;this._installHardClipboardExecCommandBlock(e||document,e?"Document.prototype":"document")||this._installHardClipboardExecCommandBlock(document,"document")}catch{}[window,document,"undefined"!=typeof Document?Document.prototype:null,"undefined"!=typeof Element?Element.prototype:null].forEach(e=>this._installHardClipboardHandlerBlock(e,e?.constructor?.name||"unknown"))}publishDiscoveryResults(e,t){if("undefined"!=typeof window&&e)try{const o=Object.getOwnPropertyDescriptor(window,e);o?.configurable&&delete window[e],o&&!o.configurable||Object.defineProperty(window,e,{value:Object.freeze([...t]),writable:!1,configurable:!0})}catch{try{window[e]=Object.freeze([...t])}catch{}}}releasePublishedResults(e){if("undefined"!=typeof window)try{const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable?delete window[e]:t?.writable&&(window[e]=null)}catch{}}collectDetachedNodeCandidates(){if("undefined"==typeof Node)return[];const e=[],t=new WeakSet,o=o=>{o instanceof Node&&!t.has(o)&&(t.add(o),e.push(o))};return this.state.discoveredItems.forEach(e=>{o(e.object),o(e.value)}),e}purgeDetachedNodes(){if("undefined"==typeof document||"undefined"==typeof Node)return 0;let e=0;return this.collectDetachedNodeCandidates().forEach(t=>{!t.isConnected&&this.nullifyProperties(t)&&e++}),this.state.discoveredItems=this.state.discoveredItems.filter(e=>!(e.object instanceof Node&&!e.object.isConnected||e.value instanceof Node&&!e.value.isConnected)),this.state.visitedObjects=new WeakSet,this.releasePublishedResults("__enabledToolsResults"),this.releasePublishedResults("__aegisDiscoveryResults"),e}nullifyProperties(e){if("undefined"==typeof Node||!(e instanceof Node))return!1;try{return e.parentNode?.removeChild&&e.parentNode.removeChild(e),Object.getOwnPropertyNames(e).forEach(t=>{try{e[t]=null}catch{}}),!0}catch{return!1}}async executePipeline(e={}){this.updateState("PENDING",{input:e});try{this.updateState("STEP_1_INIT_SUCCESS",{status:"Anti-detection ecosystem armed."});const e=await this.start();return{success:!0,processId:this.processId,state:this.state.currentState,runtime:e}}catch(e){throw this.updateState("REJECTED",{error:e.message}),e}}initGlobalDiagnostics(){if(!this.state.diagnosticsInstalled&&(this.state.diagnosticsInstalled=!0,window.addEventListener("error",e=>this.state.trace.errors.push({type:"error",msg:e.message,ts:Date.now()})),window.addEventListener("unhandledrejection",e=>this.state.trace.errors.push({type:"promise",reason:String(e.reason),ts:Date.now()})),this.config.policy.freezeConsole)){const e=(t,o=new WeakSet)=>{t&&"object"==typeof t&&!o.has(t)&&(o.add(t),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{try{e(t[n],o)}catch{}}))};e(console)}}primeBlockingMode(){return!this.state.blockingModePrimed&&(this.state.blockingModePrimed=!0,this.updateState("BOOTSTRAP_PRIME",{status:"Early blocking mechanisms armed."}),["initXhrSniffer","initWasmHook","initWebSocketHook","initWorkerHook","initIndexedDBHook","initClipboardGuard","initGlobalDiagnostics","initDomFirewall","initFocusHardening"].forEach(e=>this[e]()),!0)}async start(){return this.startPromise?this.startPromise:this.startPromise=(async()=>(this.updateState("BOOTSTRAP"),this.primeBlockingMode(),this.initKeepAlivePipeline().catch(()=>{}),this.updateState("SPOOF_ACTIVE",{frequency:'${this.config.evasion.mouseSimulationInterval}ms'}),await this.simulateMouseMotion(),this.mouseSimulationIntervalRef??=setInterval(async()=>await this.simulateMouseMotion(),this.config.evasion.mouseSimulationInterval),this.discoveryTimeoutRef??=setTimeout(async()=>{await this.executeFullDiscoveryScan(),this.discoveryTimeoutRef=null},2e3),this.state.autoStartCompleted=!0,this.updateState("RESOLVED",{status:"Stealth persistence operational."}),{success:!0,processId:this.processId,state:this.state.currentState}))()}}function resolveAegisConsoleEngine(e={}){return!(Object.keys(e).length>0)&&globalThis.__aegisConsoleEngine instanceof AegisCodexEngine||(globalThis.__aegisConsoleEngine=new AegisCodexEngine(e)),globalThis.__aegisConsoleEngine}const AEGIS_MANUAL_TOPICS=["all","api","workflow","methods","config","state","examples","instance"],AEGIS_MANUAL_STYLES={overview:"color: #fff; background: #004466; font-weight: bold; padding: 2px 6px;",startup:"color: #fff; background: #0f766e; font-weight: bold; padding: 2px 6px;",success:"color: #22c55e; font-weight: bold;",error:"color: #ef4444; font-weight: bold;",active:"color: #22c55e; font-weight: bold;",inactive:"color: #9ca3af; font-weight: bold;",api:"color: #7dd3fc; font-weight: bold;",methods:"color: #c084fc; font-weight: bold;",workflow:"color: #38bdf8; font-weight: bold;",config:"color: #facc15; font-weight: bold;",state:"color: #34d399; font-weight: bold;",stateSummary:"color: #22c55e; font-weight: bold;",examples:"color: #f472b6; font-weight: bold;",instance:"color: #f59e0b; font-weight: bold;",info:"color: #60a5fa; font-weight: bold;",warning:"color: #f87171; font-weight: bold;"},AEGIS_CONSOLE_API_DOCS=[{nome:"create(config)",retorno:"Engine",descricao:"Creates/replaces the global Aegis engine."},{nome:"getInstance()",retorno:"Engine",descricao:"Returns the loaded singleton instance."},{nome:"start(config)",retorno:"Promise",descricao:"Runs the full security and evasion bootstrap."},{nome:"contextSearch(q, opt?)",retorno:"Promise",descricao:"Searches live memory/DOM graph for a word or regex."},{nome:"status()",retorno:"void",descricao:"Prints active tools and API state."},{nome:"traceDump()",retorno:"object",descricao:"Returns all network and UI trace records."},{nome:"traceStats()",retorno:"object",descricao:"Returns metric packet counters for traces."},{nome:"traceExport()",retorno:"void",descricao:"Opens a JSON blob of the trace buffers."},{nome:"scan()",retorno:"Promise",descricao:"Forces an on-demand memory discovery pass."},{nome:"purge()",retorno:"number",descricao:"Purges unlinked detached reference nodes."},{nome:"state()",retorno:"void",descricao:"Displays memory counters and telemetry values."}];function printAegisManual(e="all"){const t=String(e).toLowerCase();if(!AEGIS_MANUAL_TOPICS.includes(t))return console.warn('Unknown topic. Use: ${AEGIS_MANUAL_TOPICS.join(", ")}');if(console.group("%c[AEGIS MANUAL] Overview",AEGIS_MANUAL_STYLES.overview),console.log("Class: globalThis.AegisCodexEngine | API: globalThis.AegisConsole"),console.groupEnd(),"all"!==t&&"api"!==t||(console.group("%c[AEGIS MANUAL] API Endpoints",AEGIS_MANUAL_STYLES.api),console.table(AEGIS_CONSOLE_API_DOCS),console.groupEnd()),"all"===t||"config"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Current Config Context",AEGIS_MANUAL_STYLES.config),console.dir(e.config),console.groupEnd()}if("all"===t||"state"===t){const e=resolveAegisConsoleEngine();console.group("%c[AEGIS MANUAL] Operational State",AEGIS_MANUAL_STYLES.state),console.log("Current state:",e.state.currentState),console.log("Mutation count:",e.state.blockedMutationCount),console.groupEnd()}}globalThis.AegisCodexEngine=AegisCodexEngine,globalThis.AegisConsole={create:(e={})=>resolveAegisConsoleEngine(e),getInstance:()=>resolveAegisConsoleEngine(),start:(e={})=>resolveAegisConsoleEngine(e).start(),executePipeline:(e={},t={})=>resolveAegisConsoleEngine(t).executePipeline(e),contextSearch:(e,t={})=>resolveAegisConsoleEngine().searchContextRecursive(e,t),contextResults:()=>resolveAegisConsoleEngine().getContextSearchResults(),traceDump:()=>resolveAegisConsoleEngine().state.trace,traceStats:()=>{const e=resolveAegisConsoleEngine().state.trace;return{ws:e.ws.length,idb:e.idb.length,fetch:e.fetch.length,worker:e.worker.length,errors:e.errors.length,mutations:e.mutations.length}},traceExport:()=>window.open(URL.createObjectURL(new Blob([JSON.stringify(resolveAegisConsoleEngine().state.trace,null,2)],{type:"application/json"}))),scan:()=>resolveAegisConsoleEngine().executeFullDiscoveryScan(),purge:()=>resolveAegisConsoleEngine().purgeDetachedNodes(),history:()=>resolveAegisConsoleEngine().getHistory(),config:()=>console.dir(resolveAegisConsoleEngine().config),state:()=>printAegisManual("state"),inspect:()=>(console.dir(resolveAegisConsoleEngine()),resolveAegisConsoleEngine()),manual:(e="all")=>printAegisManual(e),help:(e="all")=>printAegisManual(e),status:()=>{const e=resolveAegisConsoleEngine();console.group("%c[AEGIS RUNTIME STATUS]",AEGIS_MANUAL_STYLES.startup),console.log('ID: ${e.processId} | State: ${e.state.currentState} | Blocked: ${e.state.blockedMutationCount}'),console.groupEnd()}},"undefined"!=typeof window&&(window.simulateMouse=(e={})=>resolveAegisConsoleEngine().simulateMouseMotion(e)),globalThis.__W_TRACER={dump:()=>globalThis.AegisConsole.traceDump(),export:()=>globalThis.AegisConsole.traceExport(),stats:()=>globalThis.AegisConsole.traceStats()},async function(){const e=resolveAegisConsoleEngine();try{await e.start(),console.log("%c[AEGIS AUTO-START] Core armed. Sovereignty established.",AEGIS_MANUAL_STYLES.success)}catch(e){console.log("%c[AEGIS AUTO-START] Failure:",AEGIS_MANUAL_STYLES.error,e.message)}}();