@astermind/cybernetic-chatbot-client 2.2.18 → 2.2.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("fs"),require("path")):"function"==typeof define&&define.amd?define(["exports","fs","path"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).AsterMindCyberneticFull={})}(this,function(e){"use strict";function t(e){return{title:e.title,snippet:e.content,relevance:e.score,documentId:e.documentId,fullContent:e.fullContent,downloadUrl:e.downloadUrl,documentName:e.documentName,sourceType:e.sourceType,chunkId:e.chunkId}}class n{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.apiKey=t}async chat(e,n){const s=await fetch(`${this.baseUrl}/api/external/chat`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify({message:e,sessionId:n?.sessionId,context:n?.context})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e.message||`HTTP ${s.status}: ${s.statusText}`)}const i=await s.json();return{...i,sources:(i.sources||[]).map(t)}}async chatStream(e,n){const s=await fetch(`${this.baseUrl}/api/external/chat/stream`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify({message:e,sessionId:n?.sessionId,context:n?.context})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e.message||`HTTP ${s.status}`)}const i=s.body?.getReader();if(!i)throw new Error("Streaming not supported");const o=new TextDecoder;let r,a="",c="",l=[];try{for(;;){const{done:e,value:s}=await i.read();if(e)break;a+=o.decode(s,{stream:!0});const h=a.split("\n");a=h.pop()||"";for(const e of h)if(e.startsWith("event: "));else if(e.startsWith("data: "))try{const s=JSON.parse(e.slice(6));void 0!==s.text?(c+=s.text,n.onToken?.(s.text)):void 0!==s.sources?(l=(s.sources||[]).map(t),n.onSources?.(l)):void 0!==s.sessionId&&(r=s.sessionId)}catch{}}n.onComplete?.({fullText:c,sessionId:r,sources:l})}catch(e){n.onError?.(e)}}async getGeneralDocs(e){const t=new URLSearchParams;e&&t.set("since",e);const n=`${this.baseUrl}/api/external/docs${t.toString()?"?"+t:""}`,s=await fetch(n,{headers:{"X-API-Key":this.apiKey}});if(!s.ok)throw new Error(`HTTP ${s.status}`);return(await s.json()).documents}async getStatus(){const e=await fetch(`${this.baseUrl}/api/external/status`,{headers:{"X-API-Key":this.apiKey}});if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}async health(){const e=await fetch(`${this.baseUrl}/api/external/health`);if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}}let s,i;const o=new WeakMap,r=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap;let h={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return r.get(e);if("objectStoreNames"===t)return e.objectStoreNames||a.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return f(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function d(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(i||(i=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(g(this),t),f(o.get(this))}:function(...t){return f(e.apply(g(this),t))}:function(t,...n){const s=e.call(g(this),t,...n);return a.set(s,t.sort?t.sort():[t]),f(s)}}function u(e){return"function"==typeof e?d(e):(e instanceof IDBTransaction&&function(e){if(r.has(e))return;const t=new Promise((t,n)=>{const s=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),s()},o=()=>{n(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});r.set(e,t)}(e),t=e,(s||(s=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some(e=>t instanceof e)?new Proxy(e,h):e);var t}function f(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const s=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(f(e.result)),s()},o=()=>{n(e.error),s()};e.addEventListener("success",i),e.addEventListener("error",o)});return t.then(t=>{t instanceof IDBCursor&&o.set(t,e)}).catch(()=>{}),l.set(t,e),t}(e);if(c.has(e))return c.get(e);const t=u(e);return t!==e&&(c.set(e,t),l.set(t,e)),t}const g=e=>l.get(e);function m(e,t,{blocked:n,upgrade:s,blocking:i,terminated:o}={}){const r=indexedDB.open(e,t),a=f(r);return s&&r.addEventListener("upgradeneeded",e=>{s(f(r.result),e.oldVersion,e.newVersion,f(r.transaction),e)}),n&&r.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}const p=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],w=new Map;function b(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const n=t.replace(/FromIndex$/,""),s=t!==n,i=y.includes(n);if(!(n in(s?IDBIndex:IDBObjectStore).prototype)||!i&&!p.includes(n))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let r=o.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[n](...t),i&&o.done]))[0]};return w.set(t,o),o}h=(e=>({...e,get:(t,n,s)=>b(t,n)||e.get(t,n,s),has:(t,n)=>!!b(t,n)||e.has(t,n)}))(h);class v{constructor(e){this.db=null,this.dbPromise=null,this.documentCount=0,this.lastSyncAt=null,this.config=e,"indexeddb"===e.storage&&"undefined"!=typeof indexedDB?this.dbPromise=this.initDB():"localstorage"===e.storage&&this.loadLocalStorageMetadata()}loadLocalStorageMetadata(){try{const e=localStorage.getItem("cybernetic-cache-meta");if(e){const t=JSON.parse(e);this.documentCount=t.documentCount||0,this.lastSyncAt=t.lastSyncAt||null}}catch{}}async initDB(){return this.db=await m("cybernetic-cache",1,{upgrade(e){if(!e.objectStoreNames.contains("documents")){e.createObjectStore("documents",{keyPath:"id"}).createIndex("by-updated","updatedAt")}e.objectStoreNames.contains("metadata")||e.createObjectStore("metadata",{keyPath:"key"})}}),await this.loadMetadata(),this.db}async getDB(){if(this.db)return this.db;if(this.dbPromise)return this.dbPromise;throw new Error("Database not available")}async loadMetadata(){if(!this.db)return;const e=await this.db.get("metadata","documentCount");this.documentCount=e?.value||0;const t=await this.db.get("metadata","lastSyncAt");this.lastSyncAt=t?.value||null}async store(e){if("localstorage"===this.config.storage)return this.storeLocalStorage(e);const t=(await this.getDB()).transaction(["documents","metadata"],"readwrite");for(const n of e)await t.objectStore("documents").put(n);this.documentCount=await t.objectStore("documents").count(),this.lastSyncAt=(new Date).toISOString(),await t.objectStore("metadata").put({key:"documentCount",value:this.documentCount}),await t.objectStore("metadata").put({key:"lastSyncAt",value:this.lastSyncAt}),await t.done}async retrieve(){if("localstorage"===this.config.storage)return this.retrieveLocalStorage();return(await this.getDB()).getAll("documents")}async getLastSync(){return this.lastSyncAt}getStatus(){const e=Date.now()-(this.lastSyncAt?new Date(this.lastSyncAt).getTime():0)>this.config.maxAge;return{documentCount:this.documentCount,lastSyncAt:this.lastSyncAt,cacheSize:5e3*this.documentCount,isStale:e}}async clear(){if("localstorage"===this.config.storage)return localStorage.removeItem("cybernetic-cache-docs"),localStorage.removeItem("cybernetic-cache-meta"),this.documentCount=0,void(this.lastSyncAt=null);const e=(await this.getDB()).transaction(["documents","metadata"],"readwrite");await e.objectStore("documents").clear(),await e.objectStore("metadata").clear(),await e.done,this.documentCount=0,this.lastSyncAt=null}storeLocalStorage(e){try{localStorage.setItem("cybernetic-cache-docs",JSON.stringify(e)),this.documentCount=e.length,this.lastSyncAt=(new Date).toISOString(),localStorage.setItem("cybernetic-cache-meta",JSON.stringify({documentCount:this.documentCount,lastSyncAt:this.lastSyncAt}))}catch{localStorage.removeItem("cybernetic-cache-docs");const t=e.slice(0,50);localStorage.setItem("cybernetic-cache-docs",JSON.stringify(t)),this.documentCount=t.length}}retrieveLocalStorage(){try{const e=localStorage.getItem("cybernetic-cache-docs");return e?JSON.parse(e):[]}catch{return[]}}}class S{constructor(){this.documents=[],this.idf=new Map,this.indexed=!1,this.loadedFromExport=!1,this.vocabulary=new Map}isIndexed(){return this.indexed&&this.documents.length>0}async index(e){this.documents=[],this.idf=new Map;const t=new Map;for(const n of e){const e=this.tokenize(n.content),s=new Set(e);for(const e of s)t.set(e,(t.get(e)||0)+1);this.documents.push({id:n.id,title:n.title,content:n.content,tokens:e,tfidf:new Map})}const n=e.length;for(const[e,s]of t)this.idf.set(e,Math.log((n+1)/(s+1))+1);for(const e of this.documents){const t=this.computeTermFrequency(e.tokens);for(const[n,s]of t){const t=this.idf.get(n)||1;e.tfidf.set(n,s*t)}}this.indexed=!0}async ask(e){if(!this.indexed||0===this.documents.length)return{answer:"I don't have any information available offline.",sources:[],topScore:0};const t=this.tokenize(e),n=this.computeTermFrequency(t),s=new Map;for(const[e,t]of n){const n=this.idf.get(e)||1;s.set(e,t*n)}const i=this.documents.map(e=>({doc:e,score:this.cosineSimilarity(s,e.tfidf)}));i.sort((e,t)=>t.score-e.score);const o=i.slice(0,3).filter(e=>e.score>.1);if(0===o.length)return{answer:"I couldn't find relevant information for your question in my offline data.",sources:[],topScore:i[0]?.score||0};const r=o[0].doc;return{answer:this.extractRelevantSnippet(r.content,t),sources:o.map(e=>({title:e.doc.title,snippet:e.doc.content.substring(0,200)+"...",score:e.score})),topScore:o[0].score}}reset(){this.documents=[],this.idf=new Map,this.vocabulary=new Map,this.indexed=!1,this.loadedFromExport=!1,this.exportVersion=void 0,this.exportedAt=void 0}async loadFromExport(e){this.reset(),this.idf=new Map(Object.entries(e.tfidfIndex.idf));let t=0;for(const e of this.idf.keys())this.vocabulary.set(e,t++);for(const t of e.documents){const e=new Map;for(const[n,s]of t.tfidfVector)for(const[t,i]of this.vocabulary)if(i===n){e.set(t,s);break}this.documents.push({id:t.id,title:t.title,content:t.content,tokens:[],tfidf:e})}this.indexed=!0,this.loadedFromExport=!0,this.exportVersion=e.version,this.exportedAt=e.meta.exportedAt,console.log(`[CyberneticLocalRAG] Loaded ${this.documents.length} documents from export (v${e.version})`)}getExportStatus(){return{loaded:this.indexed,loadedFromExport:this.loadedFromExport,documentCount:this.documents.length,chunkCount:this.documents.length,exportVersion:this.exportVersion,exportedAt:this.exportedAt}}tokenize(e){return e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(e=>e.length>2&&!this.isStopWord(e))}computeTermFrequency(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)||0)+1);const n=Math.max(...t.values());if(n>0)for(const[e,s]of t)t.set(e,s/n);return t}cosineSimilarity(e,t){let n=0,s=0,i=0;for(const[i,o]of e){n+=o*(t.get(i)||0),s+=o*o}for(const e of t.values())i+=e*e;return 0===s||0===i?0:n/(Math.sqrt(s)*Math.sqrt(i))}extractRelevantSnippet(e,t){const n=e.split(/[.!?]+/).filter(e=>e.trim().length>0).map(e=>{const n=new Set(this.tokenize(e));let s=0;for(const e of t)n.has(e)&&s++;return{sentence:e.trim(),score:s}});n.sort((e,t)=>t.score-e.score);const s=n.slice(0,3).filter(e=>e.score>0);return 0===s.length?e.substring(0,300)+"...":s.map(e=>e.sentence).join(". ")+"."}isStopWord(e){return new Set(["the","a","an","and","or","but","in","on","at","to","for","of","with","by","from","up","about","into","through","during","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","this","that","these","those","it","its","they","them","their","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","not","only","same","so","than","too","very"]).has(e)}}class C{constructor(){this.db=null,this.dbPromise=null,this.dbName="cybernetic-offline-vectors",this.dbVersion=1}async initDB(){return this.db?this.db:this.dbPromise?this.dbPromise:(this.dbPromise=m(this.dbName,this.dbVersion,{upgrade(e){e.objectStoreNames.contains("vectors")||e.createObjectStore("vectors",{keyPath:"id"})}}),this.db=await this.dbPromise,this.db)}async store(e,t){const n=await this.getDB();await n.put("vectors",{id:e,exportVersion:t.version,exportedAt:t.meta.exportedAt,type:t.type,data:t}),console.log(`[CyberneticOfflineStorage] Stored ${t.meta.chunkCount} chunks`)}async retrieve(e){const t=await this.getDB(),n=await t.get("vectors",e);return n?.data??null}async isValid(e,t){const n=await this.getDB(),s=await n.get("vectors",e);if(!s)return!1;const i=new Date(s.exportedAt).getTime();return Date.now()-i<t}async getMeta(e){const t=await this.getDB(),n=await t.get("vectors",e);return n?{version:n.exportVersion,exportedAt:n.exportedAt,documentCount:n.data.meta.documentCount,chunkCount:n.data.meta.chunkCount,type:n.type}:null}async hasData(){const e=await this.getDB();return await e.count("vectors")>0}async getStoredIds(){return(await this.getDB()).getAllKeys("vectors")}async delete(e){const t=await this.getDB();await t.delete("vectors",e)}async clear(){const e=await this.getDB();await e.clear("vectors"),console.log("[CyberneticOfflineStorage] Cache cleared")}async getDB(){return this.db?this.db:this.initDB()}close(){this.db&&(this.db.close(),this.db=null,this.dbPromise=null)}}function M(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const n=t.length%4;n&&(t+="=".repeat(4-n));const s=atob(t),i=new Uint8Array(s.length);for(let e=0;e<s.length;e++)i[e]=s.charCodeAt(e);return i}function A(e){const t=M(e);return(new TextDecoder).decode(t)}function k(e){try{const t=e.split(".");if(3!==t.length)return null;const[n,s,i]=t;return{header:JSON.parse(A(n)),payload:JSON.parse(A(s)),signature:M(i),signedContent:`${n}.${s}`}}catch{return null}}async function E(e,t,n){try{const s=await async function(e){const t=e.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s/g,""),n=atob(t),s=new Uint8Array(n.length);for(let e=0;e<n.length;e++)s[e]=n.charCodeAt(e);return crypto.subtle.importKey("spki",s.buffer,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}(n),i=(new TextEncoder).encode(e),o=new Uint8Array(t).buffer;return await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,o,i)}catch(e){return console.warn("[License] Signature verification failed:",e),!1}}async function x(e,t){if(!e||""===e.trim())return{status:"missing",payload:null,error:"No license key provided",inGracePeriod:!1,daysRemaining:null};const n=k(e);if(!n)return{status:"invalid",payload:null,error:"Invalid license key format",inGracePeriod:!1,daysRemaining:null};const s=function(e){return"string"!=typeof e.iss||"string"!=typeof e.sub||"string"!=typeof e.aud||"number"!=typeof e.iat||"number"!=typeof e.exp||"string"!=typeof e.plan||"number"!=typeof e.seats?null:Array.isArray(e.features)?"number"!=typeof e.licenseVersion?null:{iss:e.iss,sub:e.sub,aud:e.aud,iat:e.iat,exp:e.exp,plan:e.plan,org:"string"==typeof e.org?e.org:void 0,seats:e.seats,features:e.features,graceUntil:"number"==typeof e.graceUntil?e.graceUntil:void 0,licenseVersion:e.licenseVersion}:null}(n.payload);if(!s)return{status:"invalid",payload:null,error:"Invalid license payload structure",inGracePeriod:!1,daysRemaining:null};if("astermind"!==s.iss)return{status:"invalid",payload:null,error:"Invalid license issuer",inGracePeriod:!1,daysRemaining:null};if("cybernetic-chatbot"!==s.aud&&"*"!==s.aud)return{status:"invalid",payload:null,error:"License not valid for this product",inGracePeriod:!1,daysRemaining:null};if("undefined"!=typeof crypto&&crypto.subtle){const e=t||"-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEhLW7MXHQ0Fuk1OKt9D5CbRw7fUMN\nLJ5AZXvOhHaXdHzMuYKX5BpK4w7TqbPvJ6QPvKmLKvHh1VKcUJ6mJQgJJw==\n-----END PUBLIC KEY-----";if(!await E(n.signedContent,n.signature,e))return{status:"invalid",payload:null,error:"License signature verification failed",inGracePeriod:!1,daysRemaining:null}}const i=Math.floor(Date.now()/1e3),o=function(e){const t=e-Math.floor(Date.now()/1e3);return Math.floor(t/86400)}(s.exp);return s.exp<i?s.graceUntil&&s.graceUntil>i?{status:"valid",payload:s,inGracePeriod:!0,daysRemaining:o}:{status:"expired",payload:s,error:"License has expired",inGracePeriod:!1,daysRemaining:o}:"eval"===s.plan?{status:"eval",payload:s,inGracePeriod:!1,daysRemaining:o}:{status:"valid",payload:s,inGracePeriod:!1,daysRemaining:o}}const R={CLIENT:"cybernetic-chatbot-client",AGENTIC:"agentic"};function I(){if("undefined"==typeof window)return"production"===process?.env?.NODE_ENV?"production":"development";const e=window.location?.hostname||"",t=["localhost","127.0.0.1","0.0.0.0",".local",".dev",".test",":3000",":5173",":8080",":4200"];for(const n of t)if(e.includes(n)||window.location?.port===n.replace(":",""))return"development";if("file:"===window.location?.protocol)return"development";const n=["staging.","preview.","-preview.",".vercel.app",".netlify.app",".pages.dev"];for(const t of n)if(e.includes(t))return"production";return"production"}function D(e){return"development"===e?"soft":"hard"}class L{constructor(e={}){this.state=null,this.verificationPromise=null,this.hasLoggedWarning=!1,this.loggedMissingFeatures=new Set,this.config=e,this.environment=e.environment||I(),this.enforcementMode=D(this.environment)}async verify(){if(this.state)return this.state;if(this.verificationPromise)return this.verificationPromise;this.verificationPromise=x(this.config.licenseKey,this.config.publicKey);try{return this.state=await this.verificationPromise,this.config.onStatusChange?.(this.state),this.logLicenseStatus(),this.state}finally{this.verificationPromise=null}}getState(){return this.state}isValid(){return!!this.state&&("valid"===this.state.status||"eval"===this.state.status)}requiresAction(){return!this.state||("expired"===this.state.status||"missing"===this.state.status||"invalid"===this.state.status)}getEnvironment(){return this.environment}getEnforcementMode(){return this.enforcementMode}processResponse(e){return this.state?this.isValid()&&!this.state.inGracePeriod?e:"soft"===this.enforcementMode?(this.hasLoggedWarning||(this.logDevelopmentWarning(),this.hasLoggedWarning=!0),e):e+"\n\n---\n⚠️ License Notice: Your AsterMind license key needs to be updated. Please contact support@astermind.ai or visit https://astermind.ai/license to renew your license.":e}getStatusMessage(){if(!this.state)return"License not verified";switch(this.state.status){case"valid":return this.state.inGracePeriod?`License expired but in grace period (${Math.abs(this.state.daysRemaining||0)} days overdue)`:`License valid (${this.state.daysRemaining} days remaining)`;case"eval":return`Evaluation license (${this.state.daysRemaining} days remaining)`;case"expired":return`License expired ${Math.abs(this.state.daysRemaining||0)} days ago`;case"missing":return"No license key provided";case"invalid":return`Invalid license: ${this.state.error}`;default:return"Unknown license status"}}async reVerify(){return this.state=null,this.hasLoggedWarning=!1,this.loggedMissingFeatures.clear(),this.verify()}hasFeature(e){return!!this.state?.payload&&this.state.payload.features.includes(e)}getFeatures(){return this.state?.payload?.features||[]}checkClientFeature(){return this.checkFeatureWithLog(R.CLIENT,"CyberneticClient")}checkAgenticFeature(){return this.checkFeatureWithLog(R.AGENTIC,"Agentic capabilities")}checkFeatureWithLog(e,t){if(!this.state?.payload)return!0;const n=this.state.payload.features.includes(e);return n||this.loggedMissingFeatures.has(e)||(this.loggedMissingFeatures.add(e),this.logMissingFeature(e,t)),n}logMissingFeature(e,t){const n=this.getFeatures(),s=this.state?.payload?.plan||"unknown";console.warn(`[Cybernetic License] ${t} requires the '${e}' feature, which is not included in your license.`),console.info(`[Cybernetic License] Current license plan: ${s}`),console.info(`[Cybernetic License] Licensed features: ${n.length>0?n.join(", "):"(none)"}`),console.info("[Cybernetic License] To add this feature, upgrade your license at https://astermind.ai/license")}logLicenseStatus(){if(!this.state)return;const e="[Cybernetic License]";switch(this.state.status){case"valid":this.state.inGracePeriod?console.warn(`${e} License expired but in grace period. Please renew at https://astermind.ai/license`):null!==this.state.daysRemaining&&this.state.daysRemaining<=30&&console.info(`${e} License expires in ${this.state.daysRemaining} days`);break;case"eval":console.info(`${e} Evaluation license - ${this.state.daysRemaining} days remaining`);break;case"expired":console.error(`${e} License expired. Enforcement mode: ${this.enforcementMode}. Renew at https://astermind.ai/license`);break;case"missing":console.warn(`${e} No license key provided. Enforcement mode: ${this.enforcementMode}. Get a license at https://astermind.ai/license`);break;case"invalid":console.error(`${e} Invalid license: ${this.state.error}. Enforcement mode: ${this.enforcementMode}`)}}logDevelopmentWarning(){console.warn(`[Cybernetic License] Running in development mode with ${this.state?.status||"unknown"} license. In production, a warning will be appended to chatbot responses. Get a license at https://astermind.ai/license`)}}class _{constructor(e){this.status="connecting",this.lastError=null,this.systemSettings=null,this.settingsLastChecked=0,this.SETTINGS_CHECK_INTERVAL=3e5,this.agenticCapabilities=null,this.offlineStorage=null,this.omegaRAG=null,this.offlineWarningShown=!1,this.config={apiUrl:e.apiUrl,apiKey:e.apiKey,fallback:{enabled:e.fallback?.enabled??!0,cacheMaxAge:e.fallback?.cacheMaxAge??864e5,cacheOnConnect:e.fallback?.cacheOnConnect??!0,cacheStorage:e.fallback?.cacheStorage??"indexeddb"},retry:{maxRetries:e.retry?.maxRetries??2,initialDelay:e.retry?.initialDelay??1e3,exponentialBackoff:e.retry?.exponentialBackoff??!0},agentic:e.agentic??null,offline:e.offline??null,sitemap:e.sitemap??null,sources:{enabled:e.sources?.enabled??!0,showSummary:e.sources?.showSummary??!0,showDownload:e.sources?.showDownload??!0,includeFullContent:e.sources?.includeFullContent??!1,maxSources:e.sources?.maxSources??5},onStatusChange:e.onStatusChange||(()=>{}),onError:e.onError||(()=>{})},this.apiClient=new n(this.config.apiUrl,this.config.apiKey),this.cache=new v({storage:this.config.fallback.cacheStorage,maxAge:this.config.fallback.cacheMaxAge}),this.localRAG=new S,this.licenseManager=new L({licenseKey:e.licenseKey}),this.licenseManager.verify().then(()=>{this.licenseManager.checkClientFeature()}).catch(()=>{}),this.monitorConnection(),this.config.fallback.enabled&&this.config.fallback.cacheOnConnect&&this.syncCache().catch(()=>{}),this.config.offline?.enabled&&this.initializeOffline(this.config.offline).catch(e=>{console.warn("[Cybernetic] Failed to initialize offline vectors:",e)})}registerAgentic(e){this.agenticCapabilities=e,console.log("[Cybernetic] Agentic capabilities registered")}isAgenticEnabled(){return null!==this.agenticCapabilities&&!0===this.config.agentic?.enabled&&(this.licenseManager.checkAgenticFeature(),!0)}getAgenticCapabilities(){return this.agenticCapabilities}getAgenticConfig(){return this.config.agentic}getSourcesConfig(){return{...this.config.sources}}isSourceFeatureAvailable(e){return!!this.config.sources.enabled&&("summary"===e?this.config.sources.showSummary:"download"===e&&(this.config.sources.showDownload&&"online"===this.status))}classifyIntent(e){if(!this.isAgenticEnabled()||!this.agenticCapabilities)return null;const t=this.config.agentic;return new(0,this.agenticCapabilities.agent)(t).interpretIntent(e)}async executeAction(e){if(!this.isAgenticEnabled()||!this.agenticCapabilities)return{success:!1,message:"Agentic capabilities not enabled"};const t=this.config.agentic;return new(0,this.agenticCapabilities.agent)(t).executeAction(e)}async smartAsk(e,t){const n=this.classifyIntent(e);if(n&&n.action&&!n.shouldEscalate){if(!1!==this.config.agentic?.requireConfirmation)return{action:n.action};const e=await this.executeAction(n.action);return{action:n.action,actionResult:e}}return{response:await this.ask(e,t)}}async initializeOffline(e){const t=e.storageMode??"hybrid",n=e.cacheMaxAge??6048e5;if("memory"!==t&&(this.offlineStorage=new C),this.offlineStorage&&"memory"!==t){const e="default";if(await this.offlineStorage.isValid(e,n)){console.log("[Cybernetic] Loading vectors from IndexedDB cache");const t=await this.offlineStorage.retrieve(e);if(t)return await this.localRAG.loadFromExport(t),void console.log("[Cybernetic] Loaded vectors from IndexedDB cache")}}if(e.vectorFileUrl)try{const n=await fetch(e.vectorFileUrl);if(!n.ok)throw new Error(`Failed to fetch vectors: ${n.status}`);const s=await n.json();return this.offlineStorage&&"memory"!==t&&await this.offlineStorage.store("default",s),await this.localRAG.loadFromExport(s),e.omega?.enabled&&await this.initializeOmega(e),void console.log("[Cybernetic] Loaded vectors from URL:",e.vectorFileUrl)}catch(e){console.error("[Cybernetic] Failed to load offline vectors from URL:",e)}if(e.vectorData)return await this.localRAG.loadFromExport(e.vectorData),e.omega?.enabled&&await this.initializeOmega(e),void console.log("[Cybernetic] Loaded inline vector data");this.offlineWarningShown||(console.warn("[Cybernetic] Offline functionality is enabled but no vectors are loaded. Offline responses will be limited. To enable full offline functionality, export vectors from the AsterMind admin panel and configure the vectorFileUrl or vectorData option."),this.offlineWarningShown=!0)}async initializeOmega(e){if(e.omega?.enabled)try{const{OmegaOfflineRAG:t}=await Promise.resolve().then(function(){return pe});this.omegaRAG=new t({reranking:e.omega.reranking,topK:5,verbose:!1}),e.omega.modelUrl?await this.omegaRAG.loadModelFromUrl(e.omega.modelUrl):e.omega.modelData&&await this.omegaRAG.loadModel(e.omega.modelData),console.log("[Cybernetic] Omega RAG initialized")}catch(e){console.warn("[Cybernetic] Failed to initialize Omega RAG:",e),this.omegaRAG=null}}async reloadOfflineVectors(){this.config.offline?.enabled?(this.localRAG.reset(),this.offlineStorage&&await this.offlineStorage.clear(),this.omegaRAG&&this.omegaRAG.clear(),await this.initializeOffline(this.config.offline)):console.warn("[Cybernetic] Offline mode is not enabled")}isOmegaOfflineEnabled(){return this.omegaRAG?.isReady()??!1}getOfflineModelInfo(){return this.omegaRAG?.getModelInfo()??null}getLocalRAGStatus(){return this.localRAG.getExportStatus()}getOfflineStorage(){return this.offlineStorage}async ask(e,t){if(!e||"string"!=typeof e)return this.createErrorResponse("Message is required","none");const n=await this.checkSystemStatus();if(n.maintenanceMode||n.forceOfflineClients)return console.log("[Cybernetic] Maintenance mode active, using cached data"),this.isCacheValid()?await this.fallbackAsk(e):{reply:n.maintenanceMessage||"The service is currently under maintenance. Please try again later.",confidence:"none",sources:[],offline:!0,degradedReason:"Maintenance mode active, no valid cache available"};try{const n=await this.apiWithRetry(e,t);this.setStatus("online");return{reply:this.licenseManager.processResponse(n.reply),confidence:"high",sources:n.sources||[],offline:!1,sessionId:n.sessionId}}catch(n){const s=this.normalizeError(n);return this.lastError=s,this.config.onError(s),"RATE_LIMIT"===s.code?{reply:"I'm receiving too many requests right now. Please try again in a moment.",confidence:"none",sources:[],offline:!1,retryAfter:s.retryAfter}:this.config.fallback.enabled&&!t?.skipFallback?await this.fallbackAsk(e):this.createErrorResponse("Unable to connect to the chatbot service. Please try again later.","none",s.retryAfter)}}async askStream(e,t,n){if(!e||"string"!=typeof e)return void t.onError?.({code:"LOCAL_RAG_ERROR",message:"Message is required"});const s=await this.checkSystemStatus();if(s.maintenanceMode||s.forceOfflineClients){console.log("[Cybernetic] Maintenance mode active, falling back to offline");const n=await this.fallbackAsk(e);return void t.onComplete?.(n)}try{await this.apiClient.chatStream(e,{sessionId:n?.sessionId,context:n?.context,onToken:t.onToken,onSources:t.onSources,onComplete:e=>{this.setStatus("online");const n=this.licenseManager.processResponse(e.fullText);t.onComplete?.({reply:n,confidence:"high",sources:e.sources||[],offline:!1,sessionId:e.sessionId})},onError:e=>{const n=this.normalizeError(e);this.config.onError(n),t.onError?.(n)}})}catch(s){const i=this.normalizeError(s);if(this.lastError=i,this.config.onError(i),this.config.fallback.enabled&&!n?.skipFallback){const n=await this.fallbackAsk(e);t.onComplete?.(n)}else t.onError?.(i)}}async syncCache(){try{const e=await this.cache.getLastSync(),t=await this.apiClient.getGeneralDocs(e);t.length>0&&(await this.cache.store(t),await this.localRAG.index(t),console.log(`[Cybernetic] Cache synced: ${t.length} documents`)),this.setStatus("online")}catch(e){console.warn("[Cybernetic] Cache sync failed:",e)}}getStatus(){return{connection:this.status,cache:this.cache.getStatus(),lastError:this.lastError,systemSettings:this.systemSettings,license:this.licenseManager.getState()}}getLicenseManager(){return this.licenseManager}async clearCache(){await this.cache.clear(),this.localRAG.reset()}async checkConnection(){try{return await this.apiClient.getStatus(),this.setStatus("online"),!0}catch{return this.setStatus("offline"),!1}}async checkSystemStatus(){if(this.systemSettings&&Date.now()-this.settingsLastChecked<this.SETTINGS_CHECK_INTERVAL)return this.systemSettings;try{const e=await this.apiClient.getStatus();return this.systemSettings={cacheRetentionHours:e.systemSettings?.cacheRetentionHours??168,maintenanceMode:e.systemSettings?.maintenanceMode??!1,maintenanceMessage:e.systemSettings?.maintenanceMessage,forceOfflineClients:e.systemSettings?.forceOfflineClients??!1},this.settingsLastChecked=Date.now(),this.systemSettings}catch{return this.systemSettings||{cacheRetentionHours:168,maintenanceMode:!1,forceOfflineClients:!1}}}isMaintenanceMode(){return this.systemSettings?.maintenanceMode??!1}getMaintenanceMessage(){return this.systemSettings?.maintenanceMessage}isCacheValid(){const e=this.cache.getStatus();if(!e.lastSyncAt)return!1;const t=60*(this.systemSettings?.cacheRetentionHours||168)*60*1e3,n=new Date(e.lastSyncAt).getTime();return Date.now()-n<t}async apiWithRetry(e,t){const{maxRetries:n,initialDelay:s,exponentialBackoff:i}=this.config.retry;let o=null;for(let r=0;r<=n;r++)try{return await this.apiClient.chat(e,{sessionId:t?.sessionId,context:t?.context})}catch(e){o=e;const t=this.normalizeError(e);if("AUTH_ERROR"===t.code||"RATE_LIMIT"===t.code)throw e;if(r<n){const e=i?s*Math.pow(2,r):s;await this.sleep(e)}}throw o}async fallbackAsk(e){if(this.setStatus("offline"),this.omegaRAG?.isReady())try{const t=await this.omegaRAG.ask(e);if(!t.degraded){return{reply:this.licenseManager.processResponse(t.answer),confidence:t.confidence,sources:t.sources.map(e=>({title:e.heading,snippet:e.content.substring(0,200)+"...",relevance:e.score})),offline:!0,degradedReason:"Omega hybrid retrieval (offline)"}}}catch(e){console.warn("[Cybernetic] Omega RAG failed, falling back to TF-IDF:",e)}const t=this.localRAG.getExportStatus();if(t.loaded&&t.documentCount>0)try{const n=await this.localRAG.ask(e);let s="medium";n.topScore<.3?s="low":n.topScore>.7&&(s="medium");return{reply:this.licenseManager.processResponse(n.answer),confidence:s,sources:n.sources.map(e=>({title:e.title,snippet:e.snippet,relevance:e.score})),offline:!0,degradedReason:t.loadedFromExport?"Using pre-exported vectors (offline)":"Processed locally with TF-IDF"}}catch(e){console.error("[Cybernetic] Local RAG error:",e)}const n=this.cache.getStatus();if(0===n.documentCount&&!t.loaded)return{reply:"I'm currently offline and don't have any cached information. Please check your connection and try again.",confidence:"none",sources:[],offline:!0,degradedReason:"No cached documents or offline vectors available"};try{const t=await this.cache.retrieve();this.localRAG.isIndexed()||await this.localRAG.index(t);const s=await this.localRAG.ask(e);let i="medium";s.topScore<.3?i="low":s.topScore>.7&&(i="medium");return{reply:this.licenseManager.processResponse(s.answer),confidence:i,sources:s.sources.map(e=>({title:e.title,snippet:e.snippet,relevance:e.score})),offline:!0,degradedReason:n.isStale?"Using stale cached data":"Processed locally without server"}}catch(e){return console.error("[Cybernetic] Local RAG error:",e),{reply:"I'm having trouble processing your request offline. Please try again when you're back online.",confidence:"none",sources:[],offline:!0,degradedReason:"Local RAG processing failed"}}}monitorConnection(){"undefined"!=typeof window&&(window.addEventListener("online",()=>{this.syncCache().catch(()=>{})}),window.addEventListener("offline",()=>{this.setStatus("offline")}),navigator.onLine||this.setStatus("offline"))}setStatus(e){this.status!==e&&(this.status=e,this.config.onStatusChange(e))}normalizeError(e){if(e instanceof Error){if(e.message.includes("401")||e.message.includes("Unauthorized"))return{code:"AUTH_ERROR",message:"Invalid or expired API key",originalError:e};if(e.message.includes("429")||e.message.includes("Rate limit")){const t=e.message.match(/retry after (\d+)/i);return{code:"RATE_LIMIT",message:"Rate limit exceeded",retryAfter:t?parseInt(t[1],10):60,originalError:e}}return e.message.includes("5")||e.message.includes("Server")?{code:"SERVER_ERROR",message:"Server error occurred",originalError:e}:{code:"NETWORK_ERROR",message:e.message||"Network error",originalError:e}}return{code:"NETWORK_ERROR",message:"Unknown error occurred"}}createErrorResponse(e,t,n){return{reply:e,confidence:t,sources:[],offline:!1,retryAfter:n}}sleep(e){return new Promise(t=>setTimeout(t,e))}}const $="https://api.astermind.ai";function T(e){if(!e||"object"!=typeof e)throw new Error("Config must be an object");const t=e;if(!t.apiUrl||"string"!=typeof t.apiUrl)throw new Error("apiUrl is required and must be a string");if(!t.apiKey||"string"!=typeof t.apiKey)throw new Error("apiKey is required and must be a string");if(!t.apiKey.startsWith("am_"))throw new Error('apiKey must start with "am_"');return!0}class F{constructor(e,t,n){this.staticEntries=[],this.discoveredEntries=[],this.backendEntries=[],this.backendCache=null,this.isInitialized=!1,this.initPromise=null,this.config=e,this.apiUrl=t,this.apiKey=n,e.static&&(this.staticEntries=this.enhanceEntries(e.static,"props"))}async initialize(){if(!this.isInitialized){if(this.initPromise)return this.initPromise;this.initPromise=this.performInitialization(),await this.initPromise,this.isInitialized=!0}}async performInitialization(){const e=[];!1!==this.config.discovery?.enabled&&e.push(this.discoverFromFramework()),!1!==this.config.backend?.enabled&&this.config.backend?.endpoint&&e.push(this.fetchFromBackend());const t=await Promise.allSettled(e);for(const e of t)if("fulfilled"===e.status){const{entries:t,source:n}=e.value;"discovery"===n?this.discoveredEntries=t:"backend"===n&&(this.backendEntries=t)}else console.warn("[SiteMapDiscovery] Source failed:",e.reason);const n=this.staticEntries.length+this.discoveredEntries.length+this.backendEntries.length;console.log(`[SiteMapDiscovery] Initialized with ${n} total entries (${this.staticEntries.length} static, ${this.discoveredEntries.length} discovered, ${this.backendEntries.length} backend)`)}getMergedEntries(){return this.mergeEntries(this.staticEntries,this.discoveredEntries,this.backendEntries)}getLegacyEntries(){return this.getMergedEntries().map(e=>({path:e.path,name:e.name,description:e.description,params:e.params,dynamicParams:e.dynamicParams,aliases:e.aliases}))}async discoverFromFramework(){const e=this.config.discovery||{},t=[];try{const n=e.framework||this.detectFramework();let s=[];switch(n){case"react-router":s=this.discoverReactRouter();break;case"vue-router":s=this.discoverVueRouter();break;case"next":s=this.discoverNextRoutes();break;case"angular":s=this.discoverAngularRoutes();break;default:!1!==e.domFallback&&(s=this.discoverFromDOM(e.navSelectors))}for(const n of s){if(this.shouldExcludeRoute(n.path,e.excludePaths))continue;let s;s=e.transformRoute?e.transformRoute(n):this.defaultRouteTransform(n),s&&t.push(this.enhanceEntry(s,"discovery"))}console.log(`[SiteMapDiscovery] Discovered ${t.length} routes from ${n}`)}catch(e){return console.warn("[SiteMapDiscovery] Framework discovery failed:",e),{entries:[],source:"discovery",timestamp:Date.now(),error:String(e)}}return{entries:t,source:"discovery",timestamp:Date.now()}}detectFramework(){if("undefined"==typeof window)return"generic";const e=window;return e.__REACT_ROUTER_DATA_ROUTER__||e.__reactRouterContext?"react-router":e.__VUE_ROUTER__||e.__VUE_APP__?.$router?"vue-router":e.__NEXT_DATA__?"next":e.ng||document.querySelector("[ng-version]")?"angular":"generic"}discoverReactRouter(){const e=[];if("undefined"==typeof window)return e;const t=window.__REACT_ROUTER_DATA_ROUTER__;return t?.routes?(this.extractRoutesFromConfig(t.routes,e,""),e):e}extractRoutesFromConfig(e,t,n){for(const s of e){const e=this.normalizePath(n,s.path||""),i={path:e,name:s.handle?.name||s.handle?.title||s.id,meta:s.handle||{},children:[]};(s.path||s.index)&&t.push(i),s.children&&this.extractRoutesFromConfig(s.children,t,e)}}discoverVueRouter(){const e=[];if("undefined"==typeof window)return e;const t=window,n=t.__VUE_APP__,s=n?.$router||t.__VUE_ROUTER__;if(s?.getRoutes){const t=s.getRoutes();for(const n of t)e.push({path:n.path,name:n.name?.toString(),meta:n.meta||{},component:n.components?.default?.name})}return e}discoverNextRoutes(){const e=[];if("undefined"==typeof window)return e;const t=window.__NEXT_DATA__;if(!t)return e;const n=t.buildManifest?.pages||{};for(const t of Object.keys(n))t.startsWith("/_")||e.push({path:t,name:this.pathToName(t)});return e}discoverAngularRoutes(){return[]}discoverFromDOM(e){const t=[];if("undefined"==typeof document)return t;const n=e||["nav a[href]",'[role="navigation"] a[href]',".nav a[href]",".navigation a[href]",".sidebar a[href]",".menu a[href]","header a[href]"],s=new Set;for(const e of n)try{const n=document.querySelectorAll(e);for(const e of n){const n=e.getAttribute("href");if(!n)continue;if(n.startsWith("http")&&!n.startsWith(window.location.origin))continue;const i=n.startsWith("/")?n:`/${n}`;if(s.has(i)||i.startsWith("/#")||"/"===i||i.includes("javascript:"))continue;s.add(i);const o=i.split("?")[0].split("#")[0];t.push({path:o,name:e.textContent?.trim()||this.pathToName(o)})}}catch(e){}return t}async fetchFromBackend(){const e=this.config.backend||{},t=e.endpoint||"/api/external/sitemap";if(this.backendCache&&Date.now()<this.backendCache.expiresAt)return{entries:this.backendCache.entries,source:"backend",timestamp:this.backendCache.fetchedAt};try{const n=new URL(t,this.apiUrl);!1!==e.tenantScoped&&n.searchParams.set("tenantScoped","true"),!1!==e.includeGeneral&&n.searchParams.set("includeGeneral","true");const s=await fetch(n.toString(),{method:"GET",headers:{"X-API-Key":this.apiKey,"Content-Type":"application/json",...e.headers}});if(!s.ok)throw new Error(`Backend sitemap fetch failed: ${s.status}`);const i=await s.json(),o=this.transformBackendResponse(i),r=e.cacheTtl||3e5;return this.backendCache={entries:o,fetchedAt:Date.now(),expiresAt:Date.now()+r},console.log(`[SiteMapDiscovery] Loaded ${o.length} routes from backend`),{entries:o,source:"backend",timestamp:Date.now()}}catch(e){return console.warn("[SiteMapDiscovery] Backend fetch failed:",e),{entries:this.backendCache?.entries||[],source:"backend",timestamp:Date.now(),error:String(e)}}}transformBackendResponse(e){return(Array.isArray(e)?e:e.entries||e.sitemap||e.routes||[]).map(e=>this.enhanceEntry({path:e.url||e.path,name:e.title||e.name,description:e.description,aliases:e.keywords||e.aliases,params:e.params,dynamicParams:e.dynamicParams},"backend"))}mergeEntries(...e){const t=this.config.merge||{},n=t.sourcePriority||["props","backend","discovery"],s=t.deduplication||"path",i=new Map;n.forEach((e,t)=>{i.set(e,n.length-t)});const o=[];for(const t of e)for(const e of t){const t=i.get(e._source||"props")||0;o.push({...e,_priority:t})}o.sort((e,t)=>(t._priority||0)-(e._priority||0));const r=new Map;for(const e of o){let n;switch(s){case"name":n=e.name.toLowerCase();break;case"both":n=`${e.path}|${e.name.toLowerCase()}`;break;default:n=this.normalizePath("",e.path)}if(r.has(n)){if(!1!==t.keepNonConflicting){const t=r.get(n);!t.description&&e.description&&(t.description=e.description),!t.aliases?.length&&e.aliases?.length&&(t.aliases=e.aliases)}}else r.set(n,e)}return Array.from(r.values())}enhanceEntries(e,t){return e.map(e=>this.enhanceEntry(e,t))}enhanceEntry(e,t){return{...e,_source:t,_discoveredAt:Date.now()}}defaultRouteTransform(e){return e.path&&"*"!==e.path&&"**"!==e.path?{path:e.path,name:e.name||e.meta?.title||this.pathToName(e.path),description:e.meta?.description,aliases:e.meta?.keywords||e.meta?.aliases,dynamicParams:e.path.includes(":")||e.path.includes("[")}:null}normalizePath(e,t){return t&&"/"!==t?t.startsWith("/")?t:e&&"/"!==e?`${e}/${t}`.replace(/\/+/g,"/"):`/${t}`:e||"/"}pathToName(e){const t=e.split("/").filter(Boolean);return(t[t.length-1]||"Home").replace(/[-_]/g," ").replace(/\[.*?\]/g,"").replace(/:/g,"").split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ").trim()||"Page"}shouldExcludeRoute(e,t){if(!t?.length)return!1;for(const n of t){if(new RegExp("^"+n.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(e))return!0}return!1}async refresh(){this.backendCache=null,this.isInitialized=!1,this.initPromise=null,await this.initialize()}isReady(){return this.isInitialized}getStats(){return{static:this.staticEntries.length,discovered:this.discoveredEntries.length,backend:this.backendEntries.length,merged:this.getMergedEntries().length}}}const P={navigate:[{pattern:/^(go to|navigate to|take me to|open|show me|bring up)\s+(.+)/i,type:"navigate",weight:.9},{pattern:/^(i want to see|i need to go to|let me see)\s+(.+)/i,type:"navigate",weight:.85},{pattern:/^(where is|how do i get to)\s+(.+)/i,type:"navigate",weight:.6}],fillForm:[{pattern:/^(search for|find|look up|search)\s+(.+)/i,type:"fillForm",weight:.88},{pattern:/^(filter by|set .+ to|change .+ to)\s+(.+)/i,type:"fillForm",weight:.85},{pattern:/^(enter|type|put)\s+(.+)\s+(in|into)\s+(.+)/i,type:"fillForm",weight:.9}],clickElement:[{pattern:/^(click|press|hit|tap)\s+(the\s+)?(.+)\s+(button|link)/i,type:"clickElement",weight:.9},{pattern:/^(submit|send|confirm|save|cancel|delete)/i,type:"clickElement",weight:.85}],triggerModal:[{pattern:/^(open|show|display)\s+(the\s+)?(.+)\s+(modal|dialog|popup|window)/i,type:"triggerModal",weight:.9},{pattern:/^(open|show)\s+(help|settings|preferences|options)/i,type:"triggerModal",weight:.85}],scroll:[{pattern:/^(scroll to|jump to|go to)\s+(the\s+)?(.+)\s+(section|area|part)/i,type:"scroll",weight:.85},{pattern:/^(show me|take me to)\s+(the\s+)?(bottom|top|end|beginning)/i,type:"scroll",weight:.8}],highlight:[{pattern:/^(highlight|show me|point to|where is)\s+(the\s+)?(.+)/i,type:"highlight",weight:.7}],custom:[{pattern:/^(export|download|refresh|reload|sync)/i,type:"custom",weight:.85}]};class O{constructor(e,t="",n=""){this.categories=[],this.topicKeywords=new Map,this.siteMapDiscovery=null,this.config=e,this.siteMapIndex=new Map,this.formIndex=new Map,this.modalIndex=new Map,this.buildIndexes(),e.siteMapConfig&&(this.siteMapDiscovery=new F(e.siteMapConfig,t,n))}buildIndexes(){if(this.config.siteMap)for(const e of this.config.siteMap){const t=[e.name.toLowerCase(),e.path.toLowerCase(),...(e.aliases||[]).map(e=>e.toLowerCase())];for(const n of t)this.siteMapIndex.set(n,e)}if(this.config.forms)for(const[e,t]of Object.entries(this.config.forms)){const n=[e.toLowerCase(),t.name.toLowerCase(),...(t.aliases||[]).map(e=>e.toLowerCase())];for(const e of n)this.formIndex.set(e,t)}if(this.config.modals)for(const[e,t]of Object.entries(this.config.modals)){const n=[e.toLowerCase(),t.id.toLowerCase(),...(t.aliases||[]).map(e=>e.toLowerCase())];for(const e of n)this.modalIndex.set(e,t)}}classify(e){if(!this.config.enabled)return{action:null,shouldEscalate:!0,rawConfidence:0};const t=e.trim().toLowerCase();for(const[t,n]of Object.entries(P))for(const{pattern:s,weight:i}of n){const n=e.match(s);if(n){const e=this.buildAction(t,n,i);if(e)return e}}const n=this.fuzzyMatchSiteMap(t);if(n)return n;const s=this.matchCustomAction(t);return s||{action:null,shouldEscalate:!0,rawConfidence:0,matchedPatterns:[]}}buildAction(e,t,n){const s=this.config.confidenceThreshold??.8;switch(e){case"navigate":{const e=this.extractTarget(t),i=this.findSiteMapMatch(e);if(i){const e=n*i.similarity;return{action:{id:`action-${Date.now()}`,type:"navigate",target:i.entry.path,confidence:e,explanation:`Navigate to ${i.entry.name}`},shouldEscalate:e<s,rawConfidence:e,matchedPatterns:["navigate",i.entry.name]}}break}case"fillForm":{const e=this.extractTarget(t),{field:i,value:o}=this.parseFormIntent(t);if(i){const e=.95*n;return{action:{id:`action-${Date.now()}`,type:"fillForm",target:i.selector,params:{value:o},confidence:e,explanation:`Fill "${i.name}" with "${o}"`},shouldEscalate:e<s,rawConfidence:e,matchedPatterns:["fillForm",i.name]}}if(this.config.forms?.search){const t=.9*n;return{action:{id:`action-${Date.now()}`,type:"fillForm",target:this.config.forms.search.selector,params:{value:e},confidence:t,explanation:`Search for "${e}"`},shouldEscalate:t<s,rawConfidence:t,matchedPatterns:["fillForm","search"]}}break}case"clickElement":{const e=this.extractTarget(t),i=this.findButtonSelector(e);if(i){const t=.95*n;return{action:{id:`action-${Date.now()}`,type:"clickElement",target:i,confidence:t,explanation:`Click "${e}" button`},shouldEscalate:t<s,rawConfidence:t,matchedPatterns:["clickElement",e]}}break}case"triggerModal":{const e=this.extractTarget(t),i=this.findModalConfig(e);if(i){const e=.95*n;return{action:{id:`action-${Date.now()}`,type:"triggerModal",target:i.trigger,confidence:e,explanation:`Open ${i.id} modal`},shouldEscalate:e<s,rawConfidence:e,matchedPatterns:["triggerModal",i.id]}}break}case"scroll":{const e=this.extractTarget(t),i=this.findScrollTarget(e);if(i){const t=.9*n;return{action:{id:`action-${Date.now()}`,type:"scroll",target:i,confidence:t,explanation:`Scroll to ${e}`},shouldEscalate:t<s,rawConfidence:t,matchedPatterns:["scroll",e]}}break}case"highlight":{const e=this.extractTarget(t),i=this.findElementByDescription(e);if(i){const t=.85*n;return{action:{id:`action-${Date.now()}`,type:"highlight",target:i,confidence:t,explanation:`Highlight ${e}`},shouldEscalate:t<s,rawConfidence:t,matchedPatterns:["highlight",e]}}break}case"custom":{const e=t[1]?.toLowerCase();if(this.config.customActions?.[e]){const t=.95*n;return{action:{id:`action-${Date.now()}`,type:"custom",target:e,confidence:t,explanation:`Execute ${e} action`},shouldEscalate:t<s,rawConfidence:t,matchedPatterns:["custom",e]}}break}}return null}extractTarget(e){for(let t=e.length-1;t>=1;t--)if(e[t])return e[t].trim();return""}findSiteMapMatch(e){const t=e.toLowerCase().replace(/[^a-z0-9\s]/g,""),n=this.siteMapIndex.get(t);if(n)return{entry:n,similarity:1};let s=null,i=0;for(const[e,n]of this.siteMapIndex){const o=this.calculateSimilarity(t,e);o>i&&o>.6&&(i=o,s=n)}return s?{entry:s,similarity:i}:null}fuzzyMatchSiteMap(e){const t=this.config.confidenceThreshold??.8;for(const[n,s]of this.siteMapIndex)if(e.includes(n)){const e=.75;return{action:{id:`action-${Date.now()}`,type:"navigate",target:s.path,confidence:e,explanation:`Navigate to ${s.name}`},shouldEscalate:e<t,rawConfidence:e,matchedPatterns:["fuzzy-sitemap",n]}}return null}matchCustomAction(e){if(!this.config.customActions)return null;const t=this.config.confidenceThreshold??.8;for(const n of Object.keys(this.config.customActions))if(e.includes(n.toLowerCase())){const e=.85;return{action:{id:`action-${Date.now()}`,type:"custom",target:n,confidence:e,explanation:`Execute ${n}`},shouldEscalate:e<t,rawConfidence:e,matchedPatterns:["custom",n]}}return null}parseFormIntent(e){const t=e[0];for(const[,e]of this.formIndex)if(t.toLowerCase().includes(e.name.toLowerCase())){const n=t.match(new RegExp(`${e.name}[^a-z]*(.+)`,"i"));return{field:e,value:n?.[1]?.trim()||""}}return{field:null,value:this.extractTarget(e)}}findButtonSelector(e){const t=e.toLowerCase();if("undefined"==typeof document)return`button:contains("${e}")`;const n=[`[data-action="${t}"]`,`[aria-label*="${t}" i]`,`.btn-${t}`,`#${t}-button`,`button.${t}`];for(const e of n)try{if(document.querySelector(e))return e}catch{}const s=document.querySelectorAll('button, [role="button"], a.btn');for(const e of s)if(e.textContent?.toLowerCase().includes(t))return this.generateUniqueSelector(e);return null}findModalConfig(e){return this.modalIndex.get(e.toLowerCase())||null}findScrollTarget(e){const t=e.toLowerCase();if("top"===t||"beginning"===t)return"body";if("bottom"===t||"end"===t)return"body:last-child";if("undefined"==typeof document)return`#${t.replace(/\s+/g,"-")}`;const n=[`#${t.replace(/\s+/g,"-")}`,`[data-section="${t}"]`,`.${t.replace(/\s+/g,"-")}-section`,`section[aria-label*="${t}" i]`];for(const e of n)try{if(document.querySelector(e))return e}catch{continue}return null}findElementByDescription(e){const t=e.toLowerCase();if("undefined"==typeof document)return`[aria-label*="${t}" i]`;const n=[`[aria-label*="${t}" i]`,`[data-testid*="${t}" i]`,`[title*="${t}" i]`];for(const e of n)try{if(document.querySelector(e))return e}catch{continue}return null}generateUniqueSelector(e){if(e.id)return`#${e.id}`;if(e.getAttribute("data-testid"))return`[data-testid="${e.getAttribute("data-testid")}"]`;const t=[];let n=e;for(;n&&n!==document.body;){let e=n.tagName.toLowerCase();if(n.className&&"string"==typeof n.className){const t=n.className.split(" ").filter(e=>e&&!e.includes(" "));t.length>0&&(e+=`.${t.slice(0,2).join(".")}`)}t.unshift(e),n=n.parentElement}return t.join(" > ")}calculateSimilarity(e,t){const n=new Set(e.split(/\s+/)),s=new Set(t.split(/\s+/)),i=new Set([...n].filter(e=>s.has(e))),o=new Set([...n,...s]);return i.size/o.size}getConfig(){return this.config}async trainFromExport(e){if(e.categories){this.categories=e.categories;for(const t of e.categories)for(const e of t.keywords){const n=this.topicKeywords.get(t.name)||[];n.push(e.toLowerCase()),this.topicKeywords.set(t.name,n)}}const t=this.extractTopicsFromDocuments(e.documents);for(const[e,n]of t){const t=this.topicKeywords.get(e)||[];t.push(...n),this.topicKeywords.set(e,[...new Set(t)])}e.sitemap&&this.loadSitemapEntries(e.sitemap),console.log(`[CyberneticIntentClassifier] Trained with ${this.categories.length} categories, ${this.topicKeywords.size} topics`)}async loadSitemap(e){if(e.enabled)if(e.sitemapData)this.loadSitemapEntries(e.sitemapData);else if(e.sitemapUrl)try{const t=await fetch(e.sitemapUrl);if(!t.ok)throw new Error(`Failed to fetch sitemap: ${t.status}`);const n=await t.json();this.loadSitemapEntries(n)}catch(e){console.error("[CyberneticIntentClassifier] Failed to load sitemap:",e)}}loadSitemapEntries(e){for(const t of e){const e={path:t.url,name:t.title,description:t.description,aliases:t.keywords},n=[t.title.toLowerCase(),t.url.toLowerCase(),...(t.keywords||[]).map(e=>e.toLowerCase())];if(t.description){const e=t.description.toLowerCase().split(/\s+/).filter(e=>e.length>4);n.push(...e)}for(const t of n)this.siteMapIndex.set(t,e)}console.log(`[CyberneticIntentClassifier] Loaded ${e.length} sitemap entries`)}extractTopicsFromDocuments(e){const t=new Map;for(const n of e){const e=n.title.toLowerCase(),s=[];n.metadata?.keywords&&s.push(...n.metadata.keywords.map(e=>e.toLowerCase()));const i=n.title.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(e=>e.length>3&&!this.isStopWord(e));s.push(...i);const o=n.content.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(e=>e.length>4&&!this.isStopWord(e)),r=new Map;for(const e of o)r.set(e,(r.get(e)||0)+1);const a=[...r.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5).map(([e])=>e);s.push(...a),t.set(e,[...new Set(s)])}return t}isStopWord(e){return new Set(["the","a","an","and","or","but","in","on","at","to","for","of","with","by","from","up","about","into","through","during","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","this","that","these","those","it","its","they","them","their","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","not","only","same","so","than","too","very","can","just","dont","now","here","there","also","your","you"]).has(e)}getCategories(){return this.categories}getTopicKeywords(){return this.topicKeywords}isTrained(){return this.categories.length>0||this.topicKeywords.size>0}async initializeDiscovery(){if(this.siteMapDiscovery)try{await this.siteMapDiscovery.initialize(),this.rebuildIndexesFromDiscovery(),console.log(`[CyberneticIntentClassifier] Discovery complete, indexed ${this.siteMapIndex.size} entries`)}catch(e){console.error("[CyberneticIntentClassifier] Discovery initialization failed:",e)}else console.log("[CyberneticIntentClassifier] No siteMapConfig provided, skipping discovery")}rebuildIndexesFromDiscovery(){if(!this.siteMapDiscovery)return;const e=this.siteMapDiscovery.getLegacyEntries();this.siteMapIndex.clear();for(const t of e){const e={path:t.path,name:t.name,description:t.description,params:t.params,aliases:t.aliases},n=[t.name.toLowerCase(),t.path.toLowerCase(),...(t.aliases||[]).map(e=>e.toLowerCase())];if(t.description){const e=t.description.toLowerCase().split(/\s+/).filter(e=>e.length>4&&!this.isStopWord(e));n.push(...e)}for(const t of n)this.siteMapIndex.set(t,e)}}isSiteMapReady(){return this.siteMapDiscovery?this.siteMapDiscovery.isReady():this.siteMapIndex.size>0||(this.config.siteMap?.length??0)>0}async ensureSiteMapReady(){this.isSiteMapReady()||await this.initializeDiscovery()}async refreshSiteMap(){this.siteMapDiscovery?(await this.siteMapDiscovery.refresh(),this.rebuildIndexesFromDiscovery()):console.log("[CyberneticIntentClassifier] No siteMapConfig provided, cannot refresh")}getSiteMapDiscovery(){return this.siteMapDiscovery}getSiteMapEntries(){return this.siteMapDiscovery?this.siteMapDiscovery.getLegacyEntries():this.config.siteMap||[]}}class U{constructor(e){this.highlightOverlay=null,this.actionCount=0,this.lastActionReset=Date.now(),this.config=e,this.classifier=new O(e),"undefined"!=typeof document&&this.injectStyles()}interpretIntent(e){return this.classifier.classify(e)}async executeAction(e){const t=Date.now();t-this.lastActionReset>6e4&&(this.actionCount=0,this.lastActionReset=t);const n=this.config.maxActionsPerTurn??5;if(this.actionCount>=n)return{success:!1,message:`Rate limit exceeded. Maximum ${n} actions per minute.`};if(!this.isActionAllowed(e))return{success:!1,message:`Action type "${e.type}" is not allowed`};switch(this.actionCount++,e.type){case"navigate":return this.navigate(e.target,e.params);case"fillForm":return this.fillForm(e.target,e.params?.value);case"clickElement":return this.clickElement(e.target);case"triggerModal":return this.triggerModal(e.target);case"scroll":return this.scrollToElement(e.target);case"highlight":return this.highlightElement(e.target);case"custom":return this.executeCustomAction(e.target,e.params);default:return{success:!1,message:`Unknown action type: ${e.type}`}}}isActionAllowed(e){const t=this.config.allowedActions;if(!t)return!0;const n={navigate:"navigate",fillForm:"fill",clickElement:"click",scroll:"scroll",highlight:"click",triggerModal:"click",custom:"click"}[e.type];return t.includes(n)}isSelectorAllowed(e){if(this.config.blockedSelectors)for(const t of this.config.blockedSelectors)if(e.includes(t))return!1;return!(this.config.allowedSelectors&&this.config.allowedSelectors.length>0)||this.config.allowedSelectors.some(t=>e.includes(t))}async navigate(e,t){try{if(!this.validateNavigationUrl(e))return{success:!1,message:"Invalid or blocked URL"};let n=e;if(t){const e=new URLSearchParams;for(const[n,s]of Object.entries(t))null!=s&&e.set(n,String(s));const s=e.toString();s&&(n+=(n.includes("?")?"&":"?")+s)}return"undefined"==typeof window?{success:!0,message:`Navigation to ${e} would be executed (server-side)`}:this.isInternalUrl(n)?this.tryClientSideNavigation(n)?{success:!0,message:`Navigated to ${e}`}:(window.location.href=n,{success:!0,message:`Navigating to ${e}...`}):(window.open(n,"_blank","noopener,noreferrer"),{success:!0,message:`Opened ${n} in new tab`})}catch(e){return{success:!1,message:"Navigation failed",error:String(e)}}}async fillForm(e,t){if(!this.isSelectorAllowed(e))return{success:!1,message:`Selector "${e}" is not allowed`};const n=this.sanitizeSelector(e);if("undefined"==typeof document)return{success:!0,message:`Form fill would set "${n}" to "${t}" (server-side)`};try{const e=document.querySelector(n);if(!e)return{success:!1,message:`Element not found: ${n}`};if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement))return{success:!1,message:"Element is not a form field"};if(e.focus(),e instanceof HTMLSelectElement){const n=Array.from(e.options).find(e=>e.value.toLowerCase()===t.toLowerCase()||e.text.toLowerCase()===t.toLowerCase());if(!n)return{success:!1,message:`Option "${t}" not found`};e.value=n.value}else e.value=t;e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}));const s=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set;return s&&e instanceof HTMLInputElement&&(s.call(e,t),e.dispatchEvent(new Event("input",{bubbles:!0}))),{success:!0,message:`Filled field with "${t}"`}}catch(e){return{success:!1,message:"Failed to fill form field",error:String(e)}}}async clickElement(e){if(!this.isSelectorAllowed(e))return{success:!1,message:`Selector "${e}" is not allowed`};const t=this.sanitizeSelector(e);if("undefined"==typeof document)return{success:!0,message:`Click on "${t}" would be executed (server-side)`};try{const e=document.querySelector(t);return e?e instanceof HTMLElement?(e.scrollIntoView({behavior:"smooth",block:"center"}),await this.sleep(300),e.click(),{success:!0,message:"Element clicked"}):{success:!1,message:"Element is not clickable"}:{success:!1,message:`Element not found: ${t}`}}catch(e){return{success:!1,message:"Failed to click element",error:String(e)}}}async triggerModal(e){return this.clickElement(e)}async scrollToElement(e){if("undefined"==typeof window)return{success:!0,message:`Scroll to "${e}" would be executed (server-side)`};try{if("body"===e)return window.scrollTo({top:0,behavior:"smooth"}),{success:!0,message:"Scrolled to top"};if("body:last-child"===e)return window.scrollTo({top:document.body.scrollHeight,behavior:"smooth"}),{success:!0,message:"Scrolled to bottom"};const t=document.querySelector(e);return t?(t.scrollIntoView({behavior:"smooth",block:"start"}),{success:!0,message:"Scrolled to element"}):{success:!1,message:`Element not found: ${e}`}}catch(e){return{success:!1,message:"Failed to scroll",error:String(e)}}}async highlightElement(e){if(!this.isSelectorAllowed(e))return{success:!1,message:`Selector "${e}" is not allowed`};if("undefined"==typeof document)return{success:!0,message:`Highlight on "${e}" would be shown (server-side)`};try{const t=document.querySelector(e);if(!t)return{success:!1,message:`Element not found: ${e}`};this.removeHighlight(),t.scrollIntoView({behavior:"smooth",block:"center"}),await this.sleep(300);const n=t.getBoundingClientRect(),s=document.createElement("div");return s.className="astermind-highlight-overlay",s.style.cssText=`\n position: fixed;\n top: ${n.top-4}px;\n left: ${n.left-4}px;\n width: ${n.width+8}px;\n height: ${n.height+8}px;\n border: 3px solid #4F46E5;\n border-radius: 4px;\n pointer-events: none;\n z-index: 999999;\n animation: astermind-highlight-pulse 1s ease-in-out 3;\n `,document.body.appendChild(s),this.highlightOverlay=s,setTimeout(()=>this.removeHighlight(),3e3),{success:!0,message:"Element highlighted"}}catch(e){return{success:!1,message:"Failed to highlight element",error:String(e)}}}async executeCustomAction(e,t){if(!this.isAllowedCustomAction(e))return{success:!1,message:`Custom action "${e}" not found`};const n=this.config.customActions[e];try{return await n(t)}catch(t){return{success:!1,message:`Custom action "${e}" failed`,error:String(t)}}}isInternalUrl(e){if(e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))return!0;if("undefined"==typeof window)return!0;try{return new URL(e,window.location.href).origin===window.location.origin}catch{return!0}}tryClientSideNavigation(e){if("undefined"==typeof window)return!1;try{return window.history.pushState({},"",e),window.dispatchEvent(new PopStateEvent("popstate")),e.includes("#")&&window.dispatchEvent(new HashChangeEvent("hashchange")),!0}catch{return!1}}validateNavigationUrl(e){if(/^(javascript|data):/i.test(e))return!1;if("undefined"==typeof window)return!0;try{return new URL(e,window.location.href).origin===window.location.origin||e.startsWith("/")}catch{return e.startsWith("/")}}sanitizeSelector(e){return e.replace(/[<>'"]/g,"").replace(/javascript:/gi,"").replace(/data:/gi,"").trim()}isAllowedCustomAction(e){return void 0!==this.config.customActions&&Object.prototype.hasOwnProperty.call(this.config.customActions,e)}removeHighlight(){this.highlightOverlay&&(this.highlightOverlay.remove(),this.highlightOverlay=null)}injectStyles(){if("undefined"==typeof document)return;if(document.getElementById("astermind-agent-styles"))return;const e=document.createElement("style");e.id="astermind-agent-styles",e.textContent="\n @keyframes astermind-highlight-pulse {\n 0%, 100% {\n box-shadow: 0 0 0 0 rgba(79, 70, 229, 0.4);\n }\n 50% {\n box-shadow: 0 0 0 10px rgba(79, 70, 229, 0);\n }\n }\n\n .astermind-highlight-overlay {\n transition: all 0.2s ease-out;\n }\n ",document.head.appendChild(e)}sleep(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return this.config}getClassifier(){return this.classifier}resetActionCount(){this.actionCount=0,this.lastActionReset=Date.now()}}const z={hiddenUnits:50,activation:"relu",ridgeLambda:.01,weightInit:"xavier",seed:1337,dropout:0,log:{verbose:!0,toFile:!1,modelName:"Unnamed ELM Model",level:"info"}};function N(e){let t=0,n=0;for(;0===t;)t=e();for(;0===n;)n=e();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*n)}Object.assign(Object.assign({},z),{useTokenizer:!1}),Object.assign(Object.assign({},z),{useTokenizer:!0,maxLen:30,charSet:"abcdefghijklmnopqrstuvwxyz",tokenizerDelimiter:/\s+/});class j{constructor(e,t,n=1e-4){this.p=e,this.m=t,this.lambda=n,this.Ainv=new Float64Array(e*e),this.Beta=new Float64Array(e*t);const s=1/Math.max(1e-12,n);for(let t=0;t<e;t++)this.Ainv[t*e+t]=s}update(e,t){const{p:n,m:s,Ainv:i,Beta:o}=this,r=new Float64Array(n);for(let t=0;t<n;t++){let s=0,o=t*n;for(let t=0;t<n;t++)s+=i[o+t]*e[t];r[t]=s}let a=1;for(let t=0;t<n;t++)a+=e[t]*r[t];a=Math.max(a,1e-12);const c=1/a;for(let e=0;e<n;e++){const t=r[e]*c;for(let s=0;s<n;s++)i[e*n+s]-=t*r[s]}for(let t=0;t<n;t++){let s=0,o=t*n;for(let t=0;t<n;t++)s+=i[o+t]*e[t];r[t]=s}for(let e=0;e<n;e++){const n=r[e];for(let i=0;i<s;i++)o[e*s+i]+=n*t[i]}}predict(e){const{p:t,m:n,Beta:s}=this,i=new Float64Array(n);for(let o=0;o<n;o++){let r=0;for(let i=0;i<t;i++)r+=e[i]*s[i*n+o];i[o]=r}return i}}function K(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(Math.max(0,t))}function G(e,t){var n,s;const i=Math.min(e.length,t.length);if(0===i)return 0;let o=0,r=0,a=0;for(let c=0;c<i;c++){const i=null!==(n=e[c])&&void 0!==n?n:0,l=null!==(s=t[c])&&void 0!==s?s:0;o+=i*l,r+=i*i,a+=l*l}const c=o/Math.sqrt(Math.max(r*a,1e-12));return Number.isFinite(c)?c:0}function B(e,t,n,s){return new(n||(n=Promise))(function(i,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}c((s=s.apply(e,t||[])).next())})}function W(e){return e.replace(/\s+/g," ").split(/(?<=[.?!])\s+/).map(e=>e.trim()).filter(e=>e.length>8&&/\w/.test(e))}function q(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]+`/g," ").replace(/\[[^\]]*\]\([^)]*\)/g,"").replace(/[-–>•→]/g," ").replace(/\s+/g," ").trim()}function V(e,t){return B(this,arguments,void 0,function*(e,t,n={}){if(!(null==t?void 0:t.length))return"No results found.";const{dim:s=64,features:i=32,sigma:o=1,rounds:r=3,topSentences:a=8,personality:c="neutral"}=n;let l=W(t.map(e=>q(e.content)).join(" ")).filter(e=>!function(e){return/^(\*|#)/.test(e)||/chapter/i.test(e)||/part\s*\d+/i.test(e)||/section/i.test(e)||/^\s*[A-Z]\)\s*$/.test(e)||e.length<15}(e)).slice(0,120);if(0===l.length)return q(t[0].content).slice(0,400);const h=function(e,t,n=1,s=Math.random){const i=new Float64Array(t*e),o=new Float64Array(t),r=1/Math.max(1e-12,n);for(let n=0;n<t*e;n++)i[n]=N(s)*r;for(let e=0;e<t;e++)o[e]=2*s()*Math.PI;return{W:i,b:o,D:t,d:e,sigma:n}}(s,i,o),d=new j(2*i,1,.001),u=e=>{const t=new Float64Array(s),n=Math.min(e.length,s);for(let s=0;s<n;s++)t[s]=e.charCodeAt(s)/255;return function(e,t){const{W:n,b:s,D:i,d:o}=e,r=new Float64Array(2*i);for(let e=0;e<i;e++){let a=s[e];const c=e*o;for(let e=0;e<o;e++)a+=n[c+e]*(t[e]||0);r[e]=Math.cos(a),r[i+e]=Math.sin(a)}let a=0;for(let e=0;e<r.length;e++)a+=r[e]*r[e];const c=1/Math.sqrt(Math.max(a,1e-12));for(let e=0;e<r.length;e++)r[e]*=c;return r}(h,function(e,t=1e-12){const n=K(e);if(!(n>t&&Number.isFinite(n)))return new Float64Array(e.length);const s=new Float64Array(e.length),i=1/n;for(let t=0;t<e.length;t++)s[t]=e[t]*i;return s}(t))},f=u(e),g=e.toLowerCase().split(/\W+/).filter(e=>e.length>2),m=l.map(e=>{const t=u(e);let n=G(t,f);const s=e.toLowerCase();for(const e of g)s.includes(e)&&(n+=.02);return{s:e,v:t,w:n}});m.sort((e,t)=>t.w-e.w);let p=m.slice(0,a).map(e=>e.s).join(" "),y=new Float64Array(2*i);for(let e=0;e<r;e++){const e=W(p).slice(0,a),t=e.map(e=>u(e)),n=t.map(e=>G(e,f));for(let e=0;e<t.length;e++)d.update(t[e],new Float64Array([n[e]]));y.fill(0);for(let e=0;e<t.length;e++){const s=t[e],i=n[e];for(let e=0;e<s.length;e++)y[e]+=s[e]*i}const s=K(y)||1;for(let e=0;e<y.length;e++)y[e]/=s;const i=e.map(e=>({s:e,w:G(u(e),y)}));i.sort((e,t)=>t.w-e.w),p=i.slice(0,Math.max(3,Math.floor(a/2))).map(e=>e.s).join(" ")}p=function(e){return e.replace(/\s+[-–>•→]\s+/g," ").replace(/\s+\.\s+/g,". ").replace(/([a-z]) - ([a-z])/gi,"$1-$2").replace(/\s{2,}/g," ").trim()}(p);return`${"teacher"===c?"Here’s a simple way to think about it:\n\n":"scientist"===c?"From the retrieved material, we can infer:\n\n":""}${p.charAt(0).toUpperCase()+p.slice(1)}\n\n(${t[0].heading||"Answer"}, Ω-synthesized)`})}function H(e,t){let n=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s];return n}function J(e,t,n,s){if("cosine"===n){const n=H(e,t),s=Math.hypot(...e),i=Math.hypot(...t);return s&&i?n/(s*i):0}if("poly2"===n){const n=H(e,t);return Math.pow(n+1,2)}{let n=0;for(let s=0;s<e.length;s++){const i=e[s]-t[s];n+=i*i}return Math.exp(-n/Math.max(1e-9,2*s*s))}}function Q(e,t,n,s,i){const o=function(e,t){const n=new Float64Array(t);for(const[t,s]of e)n[t]=s;return n}(e,t),r=new Float64Array(n.length);for(let e=0;e<n.length;e++){const t=n[e];r[e]=J(o,t,s,i)}const a=Math.hypot(...r);if(a>0)for(let e=0;e<r.length;e++)r[e]/=a;return r}"function"==typeof SuppressedError&&SuppressedError;const Y=new Map;function X(e){const t=e,n=Y.get(t);if(n)return n;let s=e.toLowerCase();if(s=s.replace(/^[^a-z0-9]+|[^a-z0-9]+$/g,""),s.length<=2)return Y.set(t,s),s;s.endsWith("ies")&&s.length>4?s=s.slice(0,-3)+"y":/(xes|ches|shes|zes|sses)$/.test(s)&&s.length>4?s=s.replace(/(xes|ches|shes|zes|sses)$/,e=>"sses"===e?"ss":e.replace(/es$/,"")):s.endsWith("s")&&!/(ss|us)$/.test(s)&&s.length>3&&(s=s.slice(0,-1));const i=[[/ization$|isation$/,"ize"],[/ational$/,"ate"],[/fulness$/,"ful"],[/ousness$/,"ous"],[/iveness$/,"ive"],[/ability$/,"able"],[/ness$/,""],[/ment$/,""],[/ations?$/,"ate"],[/izer$|iser$/,"ize"],[/ally$/,"al"],[/ically$/,"ic"],[/ingly$|edly$/,""],[/ing$|ed$/,""]];for(const[e,t]of i)if(e.test(s)&&s.length-t.length>=4){s=s.replace(e,t);break}return Y.set(t,s),s}function Z(e,t){const n=Array.from(e,(e,t)=>t);return n.sort((t,n)=>e[n]-e[t]),n.slice(0,t)}function ee(e){const{query:t,chunks:n,vocabMap:s,idf:i,tfidfDocs:o,denseDocs:r,landmarksIdx:a,landmarkMat:c,vocabSize:l,kernel:h,sigma:d,alpha:u,beta:f,ridge:g,headingW:m,useStem:p,expandQuery:y,topK:w,prefilter:b}=e,v=function(e,t,n,s=1){const i=new Map;for(let t=0;t<e.length;t++){const o=e[t],r=n.get(o);if(void 0===r)continue;const a=t<8?s:1;i.set(r,(i.get(r)||0)+a)}const o=Math.max(1,...i.values()),r=new Map;for(const[e,n]of i){const s=.5+n/o*.5;r.set(e,s*(t[e]||0))}return r}(function(e,t){const n=e.toLowerCase().replace(/[`*_>~]/g," ").replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(Boolean);if(!t)return n;const s=[];for(const e of n){const t=X(e);t&&t.length>1&&s.push(t)}return s}(y?function(e){const t=[];return/\bmap\b/.test(e)&&t.push("dict key value make"),/\bchan|channel\b/.test(e)&&t.push("goroutine concurrency select buffer"),/\berror\b/.test(e)&&t.push("fmt wrap unwrap sentinel try catch"),/\bstruct\b/.test(e)&&t.push("field method receiver init zero value"),e+" "+t.join(" ")}(t):t,p),i,s,m),S=Q(v,l,c,h,d),C=o.map(e=>function(e,t){let n=0,s=0,i=0;for(const[i,o]of e){s+=o*o;const e=t.get(i);e&&(n+=o*e)}for(const[,e]of t)i+=e*e;return s&&i?n/(Math.sqrt(s)*Math.sqrt(i)):0}(e,v)),M=r.map(e=>function(e,t,n,s){if("cosine"===n){const n=H(e,t),s=Math.hypot(...e),i=Math.hypot(...t);return s&&i?n/(s*i):0}if("poly2"===n){const n=H(e,t);return Math.pow(n+1,2)}{let n=0;for(let s=0;s<e.length;s++){const i=e[s]-t[s];n+=i*i}return Math.exp(-n/Math.max(1e-9,2*s*s))}}(e,S,h,d)),A=function(e,t){const n=Array.from(new Set(t.toLowerCase().split(/\W+/).filter(e=>e.length>2))),s=/\b(define|declare|syntax|example|function|struct|map|interface)\b/i.test(t);return e.map(e=>{const t=e.rich||e.content||"",i=t.toLowerCase();let o=0;for(const e of n)i.includes(e)&&o++;return s&&/```/.test(t)&&(o+=5),Math.min(1,.03*o)})}(n,t),k=(E=u,x=0,R=1,Math.max(x,Math.min(R,E)));var E,x,R;const I=null!=g?g:.08,D=M.map((e,t)=>{const n=C[t],s=f*A[t],i=1/(1+I*(e*e+n*n+.5*s*s))*(k*e+(1-k)*n+s);return Math.tanh(i)}),L=Math.max(w,null!=b?b:0),_=Z(D,L),$=Z(_.map(e=>D[e]),w).map(e=>_[e]);return{items:$.map(e=>{const t=n[e],s=t.rich&&t.rich.trim()||t.content&&t.content.trim()||"(see subsections)";return{score:D[e],heading:t.heading,content:s,index:e}}),scores:$.map(e=>D[e]),indices:$,tfidfScores:$.map(e=>C[e]),denseScores:$.map(e=>M[e])}}const te=new Set(["a","an","the","and","or","but","if","then","else","for","to","of","in","on","at","by","with","is","are","was","were","be","been","being","as","from","that","this","it","its","you","your","i","we","they","he","she","them","his","her","our","us","do","does","did","done","not","no","yes","can","could","should","would","may","might","into","about","over","under","between"]);function ne(e){return e.toLowerCase().replace(/[`*_#>~=\[\]{}()!?.:,;'"<>|/\\+-]+/g," ").split(/\s+/).filter(e=>e&&!te.has(e))}function se(e){const t=new Map,n=[],s=[];let i=0;for(const o of e){const e=ne(o);s.push(e.length);const r=new Map;for(const n of e){let e=t.get(n);void 0===e&&(e=i++,t.set(n,e)),r.set(e,(r.get(e)||0)+1)}n.push(r)}const o=e.length,r=Array(i).fill(0);for(const e of n)for(const t of e.keys())r[t]+=1;return{stats:{vocab:t,idf:r.map(e=>Math.log((o+1)/(e+1))+1),avgLen:s.reduce((e,t)=>e+t,0)/Math.max(1,o),df:r},tf:n,docLens:s}}function ie(e,t){const n=new Map;let s=0;for(const[i,o]of e){const e=o*(t[i]||0);n.set(i,e),s+=e*e}const i=Math.sqrt(s)||1e-12;for(const[e,t]of n)n.set(e,t/i);return n}function oe(e,t){const[n,s]=e.size<t.size?[e,t]:[t,e];let i=0;for(const[e,t]of n){const n=s.get(e);void 0!==n&&(i+=t*n)}return i}function re(e,t,n=1337){const s=new Float64Array(t);for(const[n,i]of e){let e=2654435761*n>>>0;for(let n=0;n<t;n++){e^=e<<13,e^=e>>>17,e^=e<<5;const t=(e>>>0)/4294967296*2-1;s[n]+=i*t}}let i=0;for(let e=0;e<t;e++)i+=s[e]*s[e];const o=Math.sqrt(i)||1e-12;for(let e=0;e<t;e++)s[e]/=o;return s}function ae(e){return/```+\s*go([\s\S]*?)```/i.test(e)||/\bfunc\s+\w+\s*\(.*\)\s*\w*\s*{/.test(e)}function ce(e){return/```+/.test(e)||/{[^}]*}/.test(e)}function le(e,t){const n=(s=ne(e),Array.from(new Set(s)));var s;const i=new Set(ne(t));if(0===n.length||0===i.size)return 0;let o=0;for(const e of n)i.has(e)&&o++;return o/n.length}function he(e,t,n,s,i,o,r,a,c,l){var h;const d=[],u=[],f=oe(n,s);d.push(f),u.push("cosine_tfidf");const g=function(e,t,n,s,i=1.5,o=.75){let r=0;for(const[a]of e){const e=t.get(a)||0;e<=0||(r+=Math.log(((n.df[a]||0)+.5)/(n.idf.length-(n.df[a]||0)+.5)+1)*(e*(i+1)/(e+i*(1-o+o*(s/(n.avgLen||1)))||1e-12)))}return r}(i,o,r,a);d.push(g),u.push("bm25");const m=le(t.heading||"",e);d.push(m),u.push("heading_match_frac");const p=function(e,t){const n=new Set(ne(e)),s=new Set(ne(t));let i=0;for(const e of n)s.has(e)&&i++;const o=n.size+s.size-i;return 0===o?0:i/o}(e,t.content||"");d.push(p),u.push("jaccard_tokens");const y=ae(t.rich||t.content||""),w=ce(t.rich||t.content||"");var b;d.push(y?1:0),u.push("flag_go_code"),d.push(w?1:0),u.push("flag_any_code"),d.push((b=t.content||"",!/(golang\.org|go\.dev|pkg\.go\.dev)/i.test(b)?0:1)),u.push("flag_go_spec_link"),d.push(null!==(h=t.score_base)&&void 0!==h?h:0),u.push("prior_score_base");const v=(t.content||"").length;if(d.push(1/Math.sqrt(1+v)),u.push("len_inv_sqrt"),c&&l){let e=0,t=0;for(let n=0;n<c.length;n++)e+=c[n]*l[n],t+=Math.abs(c[n]-l[n]);d.push(e),u.push("proj_dot"),d.push(t/c.length),u.push("proj_l1mean")}return{names:u,values:d}}class de{constructor(){this.w=null,this.mu=null,this.sigma=null}fit(e,t,n=.01){var s;const i=e.length,o=(null===(s=e[0])||void 0===s?void 0:s.length)||0;if(0===i||0===o)return void(this.w=new Float64Array(o));const r=new Float64Array(o),a=new Float64Array(o);for(let t=0;t<o;t++){let n=0;for(let s=0;s<i;s++)n+=e[s][t];n/=i,r[t]=n;let s=0;for(let o=0;o<i;o++){const i=e[o][t]-n;s+=i*i}a[t]=Math.sqrt(s/i)||1}const c=Array.from({length:i},(e,t)=>new Float64Array(o));for(let t=0;t<i;t++)for(let n=0;n<o;n++)c[t][n]=(e[t][n]-r[n])/a[n];const l=Array.from({length:o},()=>new Float64Array(o)),h=new Float64Array(o);for(let e=0;e<i;e++){const n=c[e],s=t[e];for(let e=0;e<o;e++){h[e]+=n[e]*s;const t=n[e];for(let s=0;s<=e;s++)l[e][s]+=t*n[s]}}for(let e=0;e<o;e++){for(let t=0;t<e;t++)l[t][e]=l[e][t];l[e][e]+=n}const d=Array.from({length:o},()=>new Float64Array(o));for(let e=0;e<o;e++)for(let t=0;t<=e;t++){let n=l[e][t];for(let s=0;s<t;s++)n-=d[e][s]*d[t][s];d[e][t]=e===t?Math.sqrt(Math.max(n,1e-12)):n/(d[t][t]||1e-12)}const u=new Float64Array(o);for(let e=0;e<o;e++){let t=h[e];for(let n=0;n<e;n++)t-=d[e][n]*u[n];u[e]=t/(d[e][e]||1e-12)}const f=new Float64Array(o);for(let e=o-1;e>=0;e--){let t=u[e];for(let n=e+1;n<o;n++)t-=d[n][e]*f[n];f[e]=t/(d[e][e]||1e-12)}this.w=f,this.mu=r,this.sigma=a}predict(e){if(!this.w||!this.mu||!this.sigma)return 0;let t=0;for(let n=0;n<this.w.length;n++){const s=(e[n]-this.mu[n])/this.sigma[n];t+=this.w[n]*s}return t}}function ue(e,t,n){var s;const i=t.rich||t.content||"";let o=0;/\bgo\b/.test(e.toLowerCase())&&/(define|declare|function|func)/i.test(e)&&ae(i)&&(o=Math.max(o,1));le(t.heading||"",e)>=.34&&ce(i)&&(o=Math.max(o,.8));const r=n.names.indexOf("cosine_tfidf"),a=n.names.indexOf("bm25"),c=r>=0?n.values[r]:0,l=a>=0?n.values[a]:0;c>.25&&(o=Math.max(o,.6)),l>1&&(o=Math.max(o,.6));const h=n.names.indexOf("prior_score_base"),d=h>=0?n.values[h]:0;return(null!==(s=t.score_base)&&void 0!==s?s:0)>0&&(o=Math.max(o,Math.min(.6,.2+.5*d))),o}function fe(e,t,n={}){var s,i;const{lambdaRidge:o=.01,randomProjDim:r=32,exposeFeatures:a=!0,attachFeatureNames:c=!1}=n,l=[e,...t.map(e=>e.content||"")],{stats:h,tf:d,docLens:u}=se(l),f=d.map(e=>ie(e,h.idf)),g=d[0],m=f[0],p=r>0?re(m,r):void 0,y=[],w=[],b=[];for(let n=0;n<t.length;n++){const s=t[n],i=d[n+1],o=f[n+1],a=r>0?re(o,r,1337+n):void 0,c=he(e,s,m,o,g,i,h,u[n+1]||1,p,a);b.push(c),y.push(c.values);const l=ue(e,s,c);w.push(l)}if(w.every(e=>Math.abs(e-w[0])<1e-9)){const e=b[0].names.indexOf("cosine_tfidf");if(e>=0)for(let t=0;t<w.length;t++)w[t]=Math.max(0,Math.min(1,.2+.6*y[t][e]))}const v=new de;v.fit(y,w,o);let S=1/0,C=-1/0;const M=y.map(e=>v.predict(e));for(const e of M)e<S&&(S=e),e>C&&(C=e);const A=Math.max(1e-9,C-S),k=c?null!==(i=null===(s=b[0])||void 0===s?void 0:s.names)&&void 0!==i?i:[]:void 0,E=t.map((e,t)=>{const n=(M[t]-S)/A,s=function(e){if(e>=0)return 1/(1+Math.exp(-e));{const t=Math.exp(e);return t/(1+t)}}((M[t]-.5*(S+C))/(.2*A+1e-6)),i=Object.assign(Object.assign({},e),{score_rr:n,p_relevant:s});return a&&(i._features=y[t]),k&&(i._feature_names=k),i});return E.sort((e,t)=>t.score_rr-e.score_rr),E}function ge(e,t={}){const{probThresh:n=.45,epsilonTop:s=.05,useMMR:i=!0,mmrLambda:o=.7,budgetChars:r=1200}=t;if(0===e.length)return[];const a=e[0].score_rr,c=e.filter(e=>e.p_relevant>=n&&e.score_rr>=a-s),l=c.length>0?c:[e[0]];if(!i){const e=[];let t=0;for(const n of l){const s=(n.content||"").length;if(t+s>r&&e.length>0)break;e.push(n),t+=s}return e}return function(e,t=.7,n=1200){const s=[],i=e.map(e=>e.content||""),{stats:o,tf:r}=se(i),a=r.map(e=>ie(e,o.idf)),c=new Set;let l=0;for(;c.size<e.length;){let i=-1,o=-1/0;for(let n=0;n<e.length;n++){if(c.has(n))continue;const s=e[n];let r=0;for(const e of c){const t=oe(a[n],a[e]);t>r&&(r=t)}const l=t*s.score_rr-(1-t)*r;l>o&&(o=l,i=n)}if(i<0)break;const r=e[i],h=(r.content||"").length;if(l+h>n&&s.length>0)break;s.push(r),l+=h,c.add(i)}return s}(e.map(e=>Object.assign(Object.assign({},e),{score_rr:l.includes(e)?e.score_rr+.01:e.score_rr})),o,r)}class me{constructor(e){this.modelState=null,this.model=null,this.config={reranking:{enabled:e?.reranking?.enabled??!0,lambdaRidge:e?.reranking?.lambdaRidge??.1,useMMR:e?.reranking?.useMMR??!0,mmrLambda:e?.reranking?.mmrLambda??.5,probThresh:e?.reranking?.probThresh??.1},topK:e?.topK??5,verbose:e?.verbose??!1}}async loadModel(e){const t=performance.now();if(this.model=e,this.modelState=function(e){if("astermind-pro-v1"!==e.version&&"astermind-elm-v1"!==e.version)throw new Error(`Unsupported model version: ${e.version}. Expected 'astermind-pro-v1' or 'astermind-elm-v1'`);const t=JSON.parse(JSON.stringify(e.settings||{})),n=new Map(e.vocab),s=Float64Array.from(e.idf),i=e.chunks.map(e=>({heading:e.heading,content:e.content||"",rich:e.rich,level:e.level,secId:e.secId})),o=e.tfidfDocs.map(e=>{const t=new Map;for(const[n,s]of e)t.set(n,s);return t}),r=Array.from(e.landmarksIdx),a=e.landmarkMat.map(e=>Float64Array.from(e));let c;if(!e.denseDocs||e.denseDocs.length!==o.length)throw new Error("recomputeDense=true but buildDense function not provided");return c=e.denseDocs.map(e=>Float64Array.from(e)),{settings:t,vocabMap:n,idf:s,chunks:i,tfidfDocs:o,landmarksIdx:r,landmarkMat:a,denseDocs:c}}(e),this.config.verbose){const e=performance.now()-t;console.log(`[OmegaOfflineRAG] Model loaded in ${e.toFixed(0)}ms`),console.log(`[OmegaOfflineRAG] ${this.modelState.chunks.length} chunks, ${this.modelState.vocabMap.size} vocab`)}}async loadModelFromUrl(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch model from ${e}: ${t.status}`);const n=await t.json();await this.loadModel(n)}isReady(){return null!==this.modelState}getModelInfo(){return this.model&&this.modelState?{version:this.model.version,savedAt:this.model.savedAt,documentCount:this.modelState.chunks.length,vocabularySize:this.modelState.vocabMap.size,landmarkCount:this.modelState.landmarksIdx.length,hasDenseVectors:this.modelState.denseDocs.length>0,settings:this.model.settings}:null}async ask(e){const t=performance.now();if(!this.modelState||!this.model)return{answer:"Omega model not loaded. Please load a model first.",confidence:"none",sources:[],processingTime:0,degraded:!0,degradedReason:"Model not loaded"};try{const n=this.model.settings,s=n.kernel??"rbf",i=n.sigma??1,o=n.alpha??.5,r=n.beta??.3,a=n.ridge??.001,c=n.headingW??.2,l=n.useStem??!0,h=n.expandQuery??!1,d=n.prefilter??100,u=ee({query:e,chunks:this.modelState.chunks,vocabMap:this.modelState.vocabMap,idf:this.modelState.idf,tfidfDocs:this.modelState.tfidfDocs,denseDocs:this.modelState.denseDocs,landmarksIdx:this.modelState.landmarksIdx,landmarkMat:this.modelState.landmarkMat,vocabSize:this.modelState.vocabMap.size,kernel:s,sigma:i,alpha:o,beta:r,ridge:a,headingW:c,useStem:l,expandQuery:h,topK:2*this.config.topK,prefilter:d});let f;if(this.config.reranking.enabled&&u.items.length>0){const t=function(e,t,n={}){return ge(fe(e,t,n),n)}(e,u.items.map((e,t)=>({heading:e.heading,content:e.content,rich:e.rich,score_base:u.scores[t]})),{lambdaRidge:this.config.reranking.lambdaRidge,useMMR:this.config.reranking.useMMR,mmrLambda:this.config.reranking.mmrLambda,probThresh:this.config.reranking.probThresh});f=t.slice(0,this.config.topK).map(e=>({heading:e.heading,content:e.content,rich:e.rich,score:e.score_base??0,rerankScore:e.score_rr,probability:e.p_relevant}))}else f=u.items.slice(0,this.config.topK).map((e,t)=>({heading:e.heading,content:e.content,rich:e.rich,score:u.scores[t]}));const g=await V(e,f.map(e=>({heading:e.heading,content:e.content,score:e.score}))),m=performance.now()-t,p=f[0]?.score??0,y=this.determineConfidence(p,f.length);return{answer:g,confidence:y,sources:f,processingTime:m,degraded:!1,queryClassification:this.classifyQuery(e)}}catch(e){const n=performance.now()-t;return console.error("[OmegaOfflineRAG] Error during retrieval:",e),{answer:"An error occurred while processing your question offline.",confidence:"none",sources:[],processingTime:n,degraded:!0,degradedReason:e instanceof Error?e.message:"Unknown error"}}}async retrieve(e,t){if(!this.modelState||!this.model)return[];const n=t??this.config.topK,s=this.model.settings,i=s.kernel??"rbf",o=s.sigma??1,r=s.alpha??.5,a=s.beta??.3,c=s.ridge??.001,l=s.headingW??.2,h=s.useStem??!0,d=s.expandQuery??!1,u=s.prefilter??100,f=ee({query:e,chunks:this.modelState.chunks,vocabMap:this.modelState.vocabMap,idf:this.modelState.idf,tfidfDocs:this.modelState.tfidfDocs,denseDocs:this.modelState.denseDocs,landmarksIdx:this.modelState.landmarksIdx,landmarkMat:this.modelState.landmarkMat,vocabSize:this.modelState.vocabMap.size,kernel:i,sigma:o,alpha:r,beta:a,ridge:c,headingW:l,useStem:h,expandQuery:d,topK:n,prefilter:u});return f.items.map((e,t)=>({heading:e.heading,content:e.content,rich:e.rich,score:f.scores[t]}))}classifyQuery(e){const t=e.toLowerCase(),n=t.split(/\s+/),s=["what","who","when","where","which","is","are","was","were"],i=["how","steps","guide","tutorial","process","procedure"],o=["why","explain","describe","meaning","definition","concept"],r=["go to","navigate","find","page","link","take me","show me"];let a="unknown",c=.5;const l=[];for(const e of r)if(t.includes(e)){a="navigational",c=.8,l.push(e);break}if("unknown"===a){const e=n[0];i.includes(e)||i.some(e=>t.includes(e))?(a="procedural",c=.7,l.push(...i.filter(e=>t.includes(e)))):o.includes(e)||o.some(e=>t.includes(e))?(a="conceptual",c=.7,l.push(...o.filter(e=>t.includes(e)))):s.includes(e)&&(a="factual",c=.7,l.push(e))}return{type:a,confidence:c,keywords:l}}determineConfidence(e,t){return 0===t?"none":e>=.7||e>=.4?"medium":"low"}clear(){this.modelState=null,this.model=null}}var pe=Object.freeze({__proto__:null,OmegaOfflineRAG:me});e.ApiClient=n,e.CyberneticAgent=U,e.CyberneticCache=v,e.CyberneticClient=_,e.CyberneticIntentClassifier=O,e.CyberneticLocalRAG=S,e.CyberneticOfflineStorage=C,e.LicenseManager=L,e.OmegaOfflineRAG=me,e.REQUIRED_FEATURES=R,e.createClient=function(e){return new _(e)},e.createLicenseManager=async function(e){const t=new L(e);return await t.verify(),t},e.detectEnvironment=I,e.getEnforcementMode=D,e.getTokenExpiration=function(e){const t=k(e);return t&&"number"==typeof t.payload.exp?new Date(1e3*t.payload.exp):null},e.isValidJWTFormat=function(e){return null!==k(e)},e.loadConfig=function(e={}){const{throwOnMissingKey:t=!0}=e,n=function(){if("undefined"==typeof process||!process.env)return null;const e=process.env.ASTERMIND_RAG_API_KEY,t=process.env.ASTERMIND_RAG_API_SERVER_URL;if(e)return{apiKey:e,apiUrl:t||$,_source:"env"};const n=process.env.REACT_APP_ASTERMIND_RAG_API_KEY,s=process.env.REACT_APP_ASTERMIND_RAG_API_SERVER_URL;return n?{apiKey:n,apiUrl:s||$,_source:"env"}:null}();if(n)return n;const s=function(){if("undefined"!=typeof window){const e=window.__ASTERMIND_CONFIG__;if(e&&"object"==typeof e&&e.apiKey)return{...e,apiUrl:e.apiUrl||$,_source:"vite"}}try{const e=globalThis.import?.meta?.env;if(e){const t=e.VITE_ASTERMIND_RAG_API_KEY,n=e.VITE_ASTERMIND_RAG_API_SERVER_URL;if(t)return{apiKey:t,apiUrl:n||$,_source:"vite"}}}catch{}return null}();if(s)return s;const i=function(){if("undefined"==typeof window)return null;const e=window.astermindConfig;return e&&"object"==typeof e&&e.apiKey?{...e,apiUrl:e.apiUrl||$,_source:"window"}:null}();if(i)return T(i),i;const o=function(){if("undefined"==typeof window||"undefined"==typeof document)return null;const e=document.querySelector("script[data-astermind-key]");if(e){const t=e.getAttribute("data-astermind-key");if(t)return{apiKey:t,apiUrl:e.getAttribute("data-astermind-url")||$,_source:"data-attr"}}return null}();if(o)return o;if(t)throw new Error('AsterMind API key is required. Configure using one of these methods:\n 1. Set VITE_ASTERMIND_RAG_API_KEY environment variable (Vite)\n 2. Set REACT_APP_ASTERMIND_RAG_API_KEY environment variable (CRA)\n 3. Set window.astermindConfig = { apiKey: "am_...", apiUrl: "..." }\n 4. Add data-astermind-key attribute to your script tag\n 5. Pass apiKey directly to createClient() or CyberneticClient constructor');return console.warn("[AsterMind] No API key found. Chatbot will not function until configured."),null},e.registerAgenticCapabilities=function(e){const t={agent:U,intentClassifier:O};e.registerAgentic(t)},e.validateConfig=T,e.verifyLicenseToken=x});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("fs"),require("path")):"function"==typeof define&&define.amd?define(["exports","fs","path"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).AsterMindCyberneticFull={})}(this,function(e){"use strict";function t(e){return{title:e.title,snippet:e.content,relevance:e.score,documentId:e.documentId,fullContent:e.fullContent,downloadUrl:e.downloadUrl,documentName:e.documentName,sourceType:e.sourceType,chunkId:e.chunkId}}class n{constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.apiKey=t}async chat(e,n){const s=await fetch(`${this.baseUrl}/api/external/chat`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify({message:e,sessionId:n?.sessionId,context:n?.context})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e.message||`HTTP ${s.status}: ${s.statusText}`)}const i=await s.json();return{...i,sources:(i.sources||[]).map(t)}}async chatStream(e,n){const s=await fetch(`${this.baseUrl}/api/external/chat/stream`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.apiKey},body:JSON.stringify({message:e,sessionId:n?.sessionId,context:n?.context})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e.message||`HTTP ${s.status}`)}const i=s.body?.getReader();if(!i)throw new Error("Streaming not supported");const o=new TextDecoder;let r,a="",c="",l=[];try{for(;;){const{done:e,value:s}=await i.read();if(e)break;a+=o.decode(s,{stream:!0});const h=a.split("\n");a=h.pop()||"";for(const e of h)if(e.startsWith("event: "));else if(e.startsWith("data: "))try{const s=JSON.parse(e.slice(6));void 0!==s.text?(c+=s.text,n.onToken?.(s.text)):void 0!==s.sources?(l=(s.sources||[]).map(t),n.onSources?.(l)):void 0!==s.sessionId&&(r=s.sessionId)}catch{}}n.onComplete?.({fullText:c,sessionId:r,sources:l})}catch(e){n.onError?.(e)}}async getGeneralDocs(e){const t=new URLSearchParams;e&&t.set("since",e);const n=`${this.baseUrl}/api/external/docs${t.toString()?"?"+t:""}`,s=await fetch(n,{headers:{"X-API-Key":this.apiKey}});if(!s.ok)throw new Error(`HTTP ${s.status}`);return(await s.json()).documents}async getStatus(){const e=await fetch(`${this.baseUrl}/api/external/status`,{headers:{"X-API-Key":this.apiKey}});if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}async health(){const e=await fetch(`${this.baseUrl}/api/external/health`);if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}}let s,i;const o=new WeakMap,r=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap;let h={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return r.get(e);if("objectStoreNames"===t)return e.objectStoreNames||a.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return f(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function d(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(i||(i=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(g(this),t),f(o.get(this))}:function(...t){return f(e.apply(g(this),t))}:function(t,...n){const s=e.call(g(this),t,...n);return a.set(s,t.sort?t.sort():[t]),f(s)}}function u(e){return"function"==typeof e?d(e):(e instanceof IDBTransaction&&function(e){if(r.has(e))return;const t=new Promise((t,n)=>{const s=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),s()},o=()=>{n(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});r.set(e,t)}(e),t=e,(s||(s=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some(e=>t instanceof e)?new Proxy(e,h):e);var t}function f(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const s=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(f(e.result)),s()},o=()=>{n(e.error),s()};e.addEventListener("success",i),e.addEventListener("error",o)});return t.then(t=>{t instanceof IDBCursor&&o.set(t,e)}).catch(()=>{}),l.set(t,e),t}(e);if(c.has(e))return c.get(e);const t=u(e);return t!==e&&(c.set(e,t),l.set(t,e)),t}const g=e=>l.get(e);function m(e,t,{blocked:n,upgrade:s,blocking:i,terminated:o}={}){const r=indexedDB.open(e,t),a=f(r);return s&&r.addEventListener("upgradeneeded",e=>{s(f(r.result),e.oldVersion,e.newVersion,f(r.transaction),e)}),n&&r.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}const p=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],w=new Map;function b(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const n=t.replace(/FromIndex$/,""),s=t!==n,i=y.includes(n);if(!(n in(s?IDBIndex:IDBObjectStore).prototype)||!i&&!p.includes(n))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let r=o.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[n](...t),i&&o.done]))[0]};return w.set(t,o),o}h=(e=>({...e,get:(t,n,s)=>b(t,n)||e.get(t,n,s),has:(t,n)=>!!b(t,n)||e.has(t,n)}))(h);class v{constructor(e){this.db=null,this.dbPromise=null,this.documentCount=0,this.lastSyncAt=null,this.config=e,"indexeddb"===e.storage&&"undefined"!=typeof indexedDB?this.dbPromise=this.initDB():"localstorage"===e.storage&&this.loadLocalStorageMetadata()}loadLocalStorageMetadata(){try{const e=localStorage.getItem("cybernetic-cache-meta");if(e){const t=JSON.parse(e);this.documentCount=t.documentCount||0,this.lastSyncAt=t.lastSyncAt||null}}catch{}}async initDB(){return this.db=await m("cybernetic-cache",1,{upgrade(e){if(!e.objectStoreNames.contains("documents")){e.createObjectStore("documents",{keyPath:"id"}).createIndex("by-updated","updatedAt")}e.objectStoreNames.contains("metadata")||e.createObjectStore("metadata",{keyPath:"key"})}}),await this.loadMetadata(),this.db}async getDB(){if(this.db)return this.db;if(this.dbPromise)return this.dbPromise;throw new Error("Database not available")}async loadMetadata(){if(!this.db)return;const e=await this.db.get("metadata","documentCount");this.documentCount=e?.value||0;const t=await this.db.get("metadata","lastSyncAt");this.lastSyncAt=t?.value||null}async store(e){if("localstorage"===this.config.storage)return this.storeLocalStorage(e);const t=(await this.getDB()).transaction(["documents","metadata"],"readwrite");for(const n of e)await t.objectStore("documents").put(n);this.documentCount=await t.objectStore("documents").count(),this.lastSyncAt=(new Date).toISOString(),await t.objectStore("metadata").put({key:"documentCount",value:this.documentCount}),await t.objectStore("metadata").put({key:"lastSyncAt",value:this.lastSyncAt}),await t.done}async retrieve(){if("localstorage"===this.config.storage)return this.retrieveLocalStorage();return(await this.getDB()).getAll("documents")}async getLastSync(){return this.lastSyncAt}getStatus(){const e=Date.now()-(this.lastSyncAt?new Date(this.lastSyncAt).getTime():0)>this.config.maxAge;return{documentCount:this.documentCount,lastSyncAt:this.lastSyncAt,cacheSize:5e3*this.documentCount,isStale:e}}async clear(){if("localstorage"===this.config.storage)return localStorage.removeItem("cybernetic-cache-docs"),localStorage.removeItem("cybernetic-cache-meta"),this.documentCount=0,void(this.lastSyncAt=null);const e=(await this.getDB()).transaction(["documents","metadata"],"readwrite");await e.objectStore("documents").clear(),await e.objectStore("metadata").clear(),await e.done,this.documentCount=0,this.lastSyncAt=null}storeLocalStorage(e){try{localStorage.setItem("cybernetic-cache-docs",JSON.stringify(e)),this.documentCount=e.length,this.lastSyncAt=(new Date).toISOString(),localStorage.setItem("cybernetic-cache-meta",JSON.stringify({documentCount:this.documentCount,lastSyncAt:this.lastSyncAt}))}catch{localStorage.removeItem("cybernetic-cache-docs");const t=e.slice(0,50);localStorage.setItem("cybernetic-cache-docs",JSON.stringify(t)),this.documentCount=t.length}}retrieveLocalStorage(){try{const e=localStorage.getItem("cybernetic-cache-docs");return e?JSON.parse(e):[]}catch{return[]}}}class S{constructor(){this.documents=[],this.idf=new Map,this.indexed=!1,this.loadedFromExport=!1,this.vocabulary=new Map}isIndexed(){return this.indexed&&this.documents.length>0}async index(e){this.documents=[],this.idf=new Map;const t=new Map;for(const n of e){const e=this.tokenize(n.content),s=new Set(e);for(const e of s)t.set(e,(t.get(e)||0)+1);this.documents.push({id:n.id,title:n.title,content:n.content,tokens:e,tfidf:new Map})}const n=e.length;for(const[e,s]of t)this.idf.set(e,Math.log((n+1)/(s+1))+1);for(const e of this.documents){const t=this.computeTermFrequency(e.tokens);for(const[n,s]of t){const t=this.idf.get(n)||1;e.tfidf.set(n,s*t)}}this.indexed=!0}async ask(e){if(!this.indexed||0===this.documents.length)return{answer:"I don't have any information available offline.",sources:[],topScore:0};const t=this.tokenize(e),n=this.computeTermFrequency(t),s=new Map;for(const[e,t]of n){const n=this.idf.get(e)||1;s.set(e,t*n)}const i=this.documents.map(e=>({doc:e,score:this.cosineSimilarity(s,e.tfidf)}));i.sort((e,t)=>t.score-e.score);const o=i.slice(0,3).filter(e=>e.score>.1);if(0===o.length)return{answer:"I couldn't find relevant information for your question in my offline data.",sources:[],topScore:i[0]?.score||0};const r=o[0].doc;return{answer:this.extractRelevantSnippet(r.content,t),sources:o.map(e=>({title:e.doc.title,snippet:e.doc.content.substring(0,200)+"...",score:e.score})),topScore:o[0].score}}reset(){this.documents=[],this.idf=new Map,this.vocabulary=new Map,this.indexed=!1,this.loadedFromExport=!1,this.exportVersion=void 0,this.exportedAt=void 0}async loadFromExport(e){this.reset(),this.idf=new Map(Object.entries(e.tfidfIndex.idf));let t=0;for(const e of this.idf.keys())this.vocabulary.set(e,t++);for(const t of e.documents){const e=new Map;for(const[n,s]of t.tfidfVector)for(const[t,i]of this.vocabulary)if(i===n){e.set(t,s);break}this.documents.push({id:t.id,title:t.title,content:t.content,tokens:[],tfidf:e})}this.indexed=!0,this.loadedFromExport=!0,this.exportVersion=e.version,this.exportedAt=e.meta.exportedAt,console.log(`[CyberneticLocalRAG] Loaded ${this.documents.length} documents from export (v${e.version})`)}getExportStatus(){return{loaded:this.indexed,loadedFromExport:this.loadedFromExport,documentCount:this.documents.length,chunkCount:this.documents.length,exportVersion:this.exportVersion,exportedAt:this.exportedAt}}tokenize(e){return e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(e=>e.length>2&&!this.isStopWord(e))}computeTermFrequency(e){const t=new Map;for(const n of e)t.set(n,(t.get(n)||0)+1);const n=Math.max(...t.values());if(n>0)for(const[e,s]of t)t.set(e,s/n);return t}cosineSimilarity(e,t){let n=0,s=0,i=0;for(const[i,o]of e){n+=o*(t.get(i)||0),s+=o*o}for(const e of t.values())i+=e*e;return 0===s||0===i?0:n/(Math.sqrt(s)*Math.sqrt(i))}extractRelevantSnippet(e,t){const n=e.split(/[.!?]+/).filter(e=>e.trim().length>0).map(e=>{const n=new Set(this.tokenize(e));let s=0;for(const e of t)n.has(e)&&s++;return{sentence:e.trim(),score:s}});n.sort((e,t)=>t.score-e.score);const s=n.slice(0,3).filter(e=>e.score>0);return 0===s.length?e.substring(0,300)+"...":s.map(e=>e.sentence).join(". ")+"."}isStopWord(e){return new Set(["the","a","an","and","or","but","in","on","at","to","for","of","with","by","from","up","about","into","through","during","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","this","that","these","those","it","its","they","them","their","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","not","only","same","so","than","too","very"]).has(e)}}class C{constructor(){this.db=null,this.dbPromise=null,this.dbName="cybernetic-offline-vectors",this.dbVersion=1}async initDB(){return this.db?this.db:this.dbPromise?this.dbPromise:(this.dbPromise=m(this.dbName,this.dbVersion,{upgrade(e){e.objectStoreNames.contains("vectors")||e.createObjectStore("vectors",{keyPath:"id"})}}),this.db=await this.dbPromise,this.db)}async store(e,t){const n=await this.getDB();await n.put("vectors",{id:e,exportVersion:t.version,exportedAt:t.meta.exportedAt,type:t.type,data:t}),console.log(`[CyberneticOfflineStorage] Stored ${t.meta.chunkCount} chunks`)}async retrieve(e){const t=await this.getDB(),n=await t.get("vectors",e);return n?.data??null}async isValid(e,t){const n=await this.getDB(),s=await n.get("vectors",e);if(!s)return!1;const i=new Date(s.exportedAt).getTime();return Date.now()-i<t}async getMeta(e){const t=await this.getDB(),n=await t.get("vectors",e);return n?{version:n.exportVersion,exportedAt:n.exportedAt,documentCount:n.data.meta.documentCount,chunkCount:n.data.meta.chunkCount,type:n.type}:null}async hasData(){const e=await this.getDB();return await e.count("vectors")>0}async getStoredIds(){return(await this.getDB()).getAllKeys("vectors")}async delete(e){const t=await this.getDB();await t.delete("vectors",e)}async clear(){const e=await this.getDB();await e.clear("vectors"),console.log("[CyberneticOfflineStorage] Cache cleared")}async getDB(){return this.db?this.db:this.initDB()}close(){this.db&&(this.db.close(),this.db=null,this.dbPromise=null)}}function M(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const n=t.length%4;n&&(t+="=".repeat(4-n));const s=atob(t),i=new Uint8Array(s.length);for(let e=0;e<s.length;e++)i[e]=s.charCodeAt(e);return i}function A(e){const t=M(e);return(new TextDecoder).decode(t)}function k(e){try{const t=e.split(".");if(3!==t.length)return null;const[n,s,i]=t;return{header:JSON.parse(A(n)),payload:JSON.parse(A(s)),signature:M(i),signedContent:`${n}.${s}`}}catch{return null}}async function E(e,t,n){try{const s=await async function(e){const t=e.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s/g,""),n=atob(t),s=new Uint8Array(n.length);for(let e=0;e<n.length;e++)s[e]=n.charCodeAt(e);return crypto.subtle.importKey("spki",s.buffer,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}(n),i=(new TextEncoder).encode(e),o=new Uint8Array(t).buffer;return await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,o,i)}catch(e){return console.warn("[License] Signature verification failed:",e),!1}}async function x(e,t){if(!e||""===e.trim())return{status:"missing",payload:null,error:"No license key provided",inGracePeriod:!1,daysRemaining:null};const n=k(e);if(!n)return{status:"invalid",payload:null,error:"Invalid license key format",inGracePeriod:!1,daysRemaining:null};const s=function(e){return"string"!=typeof e.iss||"string"!=typeof e.sub||"string"!=typeof e.aud||"number"!=typeof e.iat||"number"!=typeof e.exp||"string"!=typeof e.plan||"number"!=typeof e.seats?null:Array.isArray(e.features)?"number"!=typeof e.licenseVersion?null:{iss:e.iss,sub:e.sub,aud:e.aud,iat:e.iat,exp:e.exp,plan:e.plan,org:"string"==typeof e.org?e.org:void 0,seats:e.seats,features:e.features,graceUntil:"number"==typeof e.graceUntil?e.graceUntil:void 0,licenseVersion:e.licenseVersion}:null}(n.payload);if(!s)return{status:"invalid",payload:null,error:"Invalid license payload structure",inGracePeriod:!1,daysRemaining:null};if("astermind"!==s.iss)return{status:"invalid",payload:null,error:"Invalid license issuer",inGracePeriod:!1,daysRemaining:null};if("cybernetic-chatbot"!==s.aud&&"*"!==s.aud)return{status:"invalid",payload:null,error:"License not valid for this product",inGracePeriod:!1,daysRemaining:null};if("undefined"!=typeof crypto&&crypto.subtle){const e=t||"-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEhLW7MXHQ0Fuk1OKt9D5CbRw7fUMN\nLJ5AZXvOhHaXdHzMuYKX5BpK4w7TqbPvJ6QPvKmLKvHh1VKcUJ6mJQgJJw==\n-----END PUBLIC KEY-----";if(!await E(n.signedContent,n.signature,e))return{status:"invalid",payload:null,error:"License signature verification failed",inGracePeriod:!1,daysRemaining:null}}const i=Math.floor(Date.now()/1e3),o=function(e){const t=e-Math.floor(Date.now()/1e3);return Math.floor(t/86400)}(s.exp);return s.exp<i?s.graceUntil&&s.graceUntil>i?{status:"valid",payload:s,inGracePeriod:!0,daysRemaining:o}:{status:"expired",payload:s,error:"License has expired",inGracePeriod:!1,daysRemaining:o}:"eval"===s.plan?{status:"eval",payload:s,inGracePeriod:!1,daysRemaining:o}:{status:"valid",payload:s,inGracePeriod:!1,daysRemaining:o}}const R={CLIENT:"cybernetic-chatbot-client",AGENTIC:"agentic"};function I(){if("undefined"==typeof window)return"production"===process?.env?.NODE_ENV?"production":"development";const e=window.location?.hostname||"",t=["localhost","127.0.0.1","0.0.0.0",".local",".dev",".test",":3000",":5173",":8080",":4200"];for(const n of t)if(e.includes(n)||window.location?.port===n.replace(":",""))return"development";if("file:"===window.location?.protocol)return"development";const n=["staging.","preview.","-preview.",".vercel.app",".netlify.app",".pages.dev"];for(const t of n)if(e.includes(t))return"production";return"production"}function D(e){return"development"===e?"soft":"hard"}class L{constructor(e={}){this.state=null,this.verificationPromise=null,this.hasLoggedWarning=!1,this.loggedMissingFeatures=new Set,this.config=e,this.environment=e.environment||I(),this.enforcementMode=D(this.environment)}async verify(){if(this.state)return this.state;if(this.verificationPromise)return this.verificationPromise;this.verificationPromise=x(this.config.licenseKey,this.config.publicKey);try{return this.state=await this.verificationPromise,this.config.onStatusChange?.(this.state),this.logLicenseStatus(),this.state}finally{this.verificationPromise=null}}getState(){return this.state}isValid(){return!!this.state&&("valid"===this.state.status||"eval"===this.state.status)}requiresAction(){return!this.state||("expired"===this.state.status||"missing"===this.state.status||"invalid"===this.state.status)}getEnvironment(){return this.environment}getEnforcementMode(){return this.enforcementMode}processResponse(e){return this.state?this.isValid()&&!this.state.inGracePeriod?e:"soft"===this.enforcementMode?(this.hasLoggedWarning||(this.logDevelopmentWarning(),this.hasLoggedWarning=!0),e):e+"\n\n---\n⚠️ License Notice: Your AsterMind license key needs to be updated. Please contact support@astermind.ai or visit https://astermind.ai/license to renew your license.":e}getStatusMessage(){if(!this.state)return"License not verified";switch(this.state.status){case"valid":return this.state.inGracePeriod?`License expired but in grace period (${Math.abs(this.state.daysRemaining||0)} days overdue)`:`License valid (${this.state.daysRemaining} days remaining)`;case"eval":return`Evaluation license (${this.state.daysRemaining} days remaining)`;case"expired":return`License expired ${Math.abs(this.state.daysRemaining||0)} days ago`;case"missing":return"No license key provided";case"invalid":return`Invalid license: ${this.state.error}`;default:return"Unknown license status"}}async reVerify(){return this.state=null,this.hasLoggedWarning=!1,this.loggedMissingFeatures.clear(),this.verify()}hasFeature(e){return!!this.state?.payload&&this.state.payload.features.includes(e)}getFeatures(){return this.state?.payload?.features||[]}checkClientFeature(){return this.checkFeatureWithLog(R.CLIENT,"CyberneticClient")}checkAgenticFeature(){return this.checkFeatureWithLog(R.AGENTIC,"Agentic capabilities")}checkFeatureWithLog(e,t){if(!this.state?.payload)return!0;const n=this.state.payload.features.includes(e);return n||this.loggedMissingFeatures.has(e)||(this.loggedMissingFeatures.add(e),this.logMissingFeature(e,t)),n}logMissingFeature(e,t){const n=this.getFeatures(),s=this.state?.payload?.plan||"unknown";console.warn(`[Cybernetic License] ${t} requires the '${e}' feature, which is not included in your license.`),console.info(`[Cybernetic License] Current license plan: ${s}`),console.info(`[Cybernetic License] Licensed features: ${n.length>0?n.join(", "):"(none)"}`),console.info("[Cybernetic License] To add this feature, upgrade your license at https://astermind.ai/license")}logLicenseStatus(){if(!this.state)return;const e="[Cybernetic License]";switch(this.state.status){case"valid":this.state.inGracePeriod?console.warn(`${e} License expired but in grace period. Please renew at https://astermind.ai/license`):null!==this.state.daysRemaining&&this.state.daysRemaining<=30&&console.info(`${e} License expires in ${this.state.daysRemaining} days`);break;case"eval":console.info(`${e} Evaluation license - ${this.state.daysRemaining} days remaining`);break;case"expired":console.error(`${e} License expired. Enforcement mode: ${this.enforcementMode}. Renew at https://astermind.ai/license`);break;case"missing":console.warn(`${e} No license key provided. Enforcement mode: ${this.enforcementMode}. Get a license at https://astermind.ai/license`);break;case"invalid":console.error(`${e} Invalid license: ${this.state.error}. Enforcement mode: ${this.enforcementMode}`)}}logDevelopmentWarning(){console.warn(`[Cybernetic License] Running in development mode with ${this.state?.status||"unknown"} license. In production, a warning will be appended to chatbot responses. Get a license at https://astermind.ai/license`)}}class _{constructor(e){this.status="connecting",this.lastError=null,this.systemSettings=null,this.settingsLastChecked=0,this.SETTINGS_CHECK_INTERVAL=3e5,this.agenticCapabilities=null,this.offlineStorage=null,this.omegaRAG=null,this.offlineWarningShown=!1,this.config={apiUrl:e.apiUrl,apiKey:e.apiKey,fallback:{enabled:e.fallback?.enabled??!0,cacheMaxAge:e.fallback?.cacheMaxAge??864e5,cacheOnConnect:e.fallback?.cacheOnConnect??!0,cacheStorage:e.fallback?.cacheStorage??"indexeddb"},retry:{maxRetries:e.retry?.maxRetries??2,initialDelay:e.retry?.initialDelay??1e3,exponentialBackoff:e.retry?.exponentialBackoff??!0},agentic:e.agentic??null,offline:e.offline??null,sitemap:e.sitemap??null,sources:{enabled:e.sources?.enabled??!0,showSummary:e.sources?.showSummary??!0,showDownload:e.sources?.showDownload??!0,includeFullContent:e.sources?.includeFullContent??!1,maxSources:e.sources?.maxSources??5},onStatusChange:e.onStatusChange||(()=>{}),onError:e.onError||(()=>{})},this.apiClient=new n(this.config.apiUrl,this.config.apiKey),this.cache=new v({storage:this.config.fallback.cacheStorage,maxAge:this.config.fallback.cacheMaxAge}),this.localRAG=new S,this.licenseManager=new L({licenseKey:e.licenseKey}),this.licenseManager.verify().then(()=>{this.licenseManager.checkClientFeature()}).catch(()=>{}),this.monitorConnection(),this.config.fallback.enabled&&this.config.fallback.cacheOnConnect&&this.syncCache().catch(()=>{}),this.config.offline?.enabled&&this.initializeOffline(this.config.offline).catch(e=>{console.warn("[Cybernetic] Failed to initialize offline vectors:",e)})}registerAgentic(e){this.agenticCapabilities=e,console.log("[Cybernetic] Agentic capabilities registered")}isAgenticEnabled(){return null!==this.agenticCapabilities&&!0===this.config.agentic?.enabled&&(this.licenseManager.checkAgenticFeature(),!0)}getAgenticCapabilities(){return this.agenticCapabilities}getAgenticConfig(){return this.config.agentic}getSourcesConfig(){return{...this.config.sources}}isSourceFeatureAvailable(e){return!!this.config.sources.enabled&&("summary"===e?this.config.sources.showSummary:"download"===e&&(this.config.sources.showDownload&&"online"===this.status))}classifyIntent(e){if(!this.isAgenticEnabled()||!this.agenticCapabilities)return null;const t=this.config.agentic;return new(0,this.agenticCapabilities.agent)(t).interpretIntent(e)}async executeAction(e){if(!this.isAgenticEnabled()||!this.agenticCapabilities)return{success:!1,message:"Agentic capabilities not enabled"};const t=this.config.agentic;return new(0,this.agenticCapabilities.agent)(t).executeAction(e)}async smartAsk(e,t){const n=this.classifyIntent(e);if(n&&n.action&&!n.shouldEscalate){if(!1!==this.config.agentic?.requireConfirmation)return{action:n.action};const e=await this.executeAction(n.action);return{action:n.action,actionResult:e}}return{response:await this.ask(e,t)}}async initializeOffline(e){const t=e.storageMode??"hybrid",n=e.cacheMaxAge??6048e5;if("memory"!==t&&(this.offlineStorage=new C),this.offlineStorage&&"memory"!==t){const e="default";if(await this.offlineStorage.isValid(e,n)){console.log("[Cybernetic] Loading vectors from IndexedDB cache");const t=await this.offlineStorage.retrieve(e);if(t)return await this.localRAG.loadFromExport(t),void console.log("[Cybernetic] Loaded vectors from IndexedDB cache")}}if(e.vectorFileUrl)try{const n=await fetch(e.vectorFileUrl);if(!n.ok)throw new Error(`Failed to fetch vectors: ${n.status}`);const s=await n.json();return this.offlineStorage&&"memory"!==t&&await this.offlineStorage.store("default",s),await this.localRAG.loadFromExport(s),e.omega?.enabled&&await this.initializeOmega(e),void console.log("[Cybernetic] Loaded vectors from URL:",e.vectorFileUrl)}catch(e){console.error("[Cybernetic] Failed to load offline vectors from URL:",e)}if(e.vectorData)return await this.localRAG.loadFromExport(e.vectorData),e.omega?.enabled&&await this.initializeOmega(e),void console.log("[Cybernetic] Loaded inline vector data");this.offlineWarningShown||(console.warn("[Cybernetic] Offline functionality is enabled but no vectors are loaded. Offline responses will be limited. To enable full offline functionality, export vectors from the AsterMind admin panel and configure the vectorFileUrl or vectorData option."),this.offlineWarningShown=!0)}async initializeOmega(e){if(e.omega?.enabled)try{const{OmegaOfflineRAG:t}=await Promise.resolve().then(function(){return pe});this.omegaRAG=new t({reranking:e.omega.reranking,topK:5,verbose:!1}),e.omega.modelUrl?await this.omegaRAG.loadModelFromUrl(e.omega.modelUrl):e.omega.modelData&&await this.omegaRAG.loadModel(e.omega.modelData),console.log("[Cybernetic] Omega RAG initialized")}catch(e){console.warn("[Cybernetic] Failed to initialize Omega RAG:",e),this.omegaRAG=null}}async reloadOfflineVectors(){this.config.offline?.enabled?(this.localRAG.reset(),this.offlineStorage&&await this.offlineStorage.clear(),this.omegaRAG&&this.omegaRAG.clear(),await this.initializeOffline(this.config.offline)):console.warn("[Cybernetic] Offline mode is not enabled")}isOmegaOfflineEnabled(){return this.omegaRAG?.isReady()??!1}getOfflineModelInfo(){return this.omegaRAG?.getModelInfo()??null}getLocalRAGStatus(){return this.localRAG.getExportStatus()}getOfflineStorage(){return this.offlineStorage}async ask(e,t){if(!e||"string"!=typeof e)return this.createErrorResponse("Message is required","none");const n=await this.checkSystemStatus();if(n.maintenanceMode||n.forceOfflineClients)return console.log("[Cybernetic] Maintenance mode active, using cached data"),this.isCacheValid()?await this.fallbackAsk(e):{reply:n.maintenanceMessage||"The service is currently under maintenance. Please try again later.",confidence:"none",sources:[],offline:!0,degradedReason:"Maintenance mode active, no valid cache available"};try{const n=await this.apiWithRetry(e,t);this.setStatus("online");return{reply:this.licenseManager.processResponse(n.reply),confidence:"high",sources:n.sources||[],offline:!1,sessionId:n.sessionId}}catch(n){const s=this.normalizeError(n);return this.lastError=s,this.config.onError(s),"RATE_LIMIT"===s.code?{reply:"I'm receiving too many requests right now. Please try again in a moment.",confidence:"none",sources:[],offline:!1,retryAfter:s.retryAfter}:this.config.fallback.enabled&&!t?.skipFallback?await this.fallbackAsk(e):this.createErrorResponse("Unable to connect to the chatbot service. Please try again later.","none",s.retryAfter)}}async askStream(e,t,n){if(!e||"string"!=typeof e)return void t.onError?.({code:"LOCAL_RAG_ERROR",message:"Message is required"});const s=await this.checkSystemStatus();if(s.maintenanceMode||s.forceOfflineClients){console.log("[Cybernetic] Maintenance mode active, falling back to offline");const n=await this.fallbackAsk(e);return void t.onComplete?.(n)}try{await this.apiClient.chatStream(e,{sessionId:n?.sessionId,context:n?.context,onToken:t.onToken,onSources:t.onSources,onComplete:e=>{this.setStatus("online");const n=this.licenseManager.processResponse(e.fullText);t.onComplete?.({reply:n,confidence:"high",sources:e.sources||[],offline:!1,sessionId:e.sessionId})},onError:e=>{const n=this.normalizeError(e);this.config.onError(n),t.onError?.(n)}})}catch(s){const i=this.normalizeError(s);if(this.lastError=i,this.config.onError(i),this.config.fallback.enabled&&!n?.skipFallback){const n=await this.fallbackAsk(e);t.onComplete?.(n)}else t.onError?.(i)}}async syncCache(){try{const e=await this.cache.getLastSync(),t=await this.apiClient.getGeneralDocs(e);t.length>0&&(await this.cache.store(t),await this.localRAG.index(t),console.log(`[Cybernetic] Cache synced: ${t.length} documents`)),this.setStatus("online")}catch(e){console.warn("[Cybernetic] Cache sync failed:",e)}}getStatus(){return{connection:this.status,cache:this.cache.getStatus(),lastError:this.lastError,systemSettings:this.systemSettings,license:this.licenseManager.getState()}}getLicenseManager(){return this.licenseManager}async clearCache(){await this.cache.clear(),this.localRAG.reset()}async checkConnection(){try{return await this.apiClient.getStatus(),this.setStatus("online"),!0}catch{return this.setStatus("offline"),!1}}async checkSystemStatus(){if(this.systemSettings&&Date.now()-this.settingsLastChecked<this.SETTINGS_CHECK_INTERVAL)return this.systemSettings;try{const e=await this.apiClient.getStatus();return this.systemSettings={cacheRetentionHours:e.systemSettings?.cacheRetentionHours??168,maintenanceMode:e.systemSettings?.maintenanceMode??!1,maintenanceMessage:e.systemSettings?.maintenanceMessage,forceOfflineClients:e.systemSettings?.forceOfflineClients??!1},this.settingsLastChecked=Date.now(),this.systemSettings}catch{return this.systemSettings||{cacheRetentionHours:168,maintenanceMode:!1,forceOfflineClients:!1}}}isMaintenanceMode(){return this.systemSettings?.maintenanceMode??!1}getMaintenanceMessage(){return this.systemSettings?.maintenanceMessage}isCacheValid(){const e=this.cache.getStatus();if(!e.lastSyncAt)return!1;const t=60*(this.systemSettings?.cacheRetentionHours||168)*60*1e3,n=new Date(e.lastSyncAt).getTime();return Date.now()-n<t}async apiWithRetry(e,t){const{maxRetries:n,initialDelay:s,exponentialBackoff:i}=this.config.retry;let o=null;for(let r=0;r<=n;r++)try{return await this.apiClient.chat(e,{sessionId:t?.sessionId,context:t?.context})}catch(e){o=e;const t=this.normalizeError(e);if("AUTH_ERROR"===t.code||"RATE_LIMIT"===t.code)throw e;if(r<n){const e=i?s*Math.pow(2,r):s;await this.sleep(e)}}throw o}async fallbackAsk(e){if(this.setStatus("offline"),this.omegaRAG?.isReady())try{const t=await this.omegaRAG.ask(e);if(!t.degraded){return{reply:this.licenseManager.processResponse(t.answer),confidence:t.confidence,sources:t.sources.map(e=>({title:e.heading,snippet:e.content.substring(0,200)+"...",relevance:e.score})),offline:!0,degradedReason:"Omega hybrid retrieval (offline)"}}}catch(e){console.warn("[Cybernetic] Omega RAG failed, falling back to TF-IDF:",e)}const t=this.localRAG.getExportStatus();if(t.loaded&&t.documentCount>0)try{const n=await this.localRAG.ask(e);let s="medium";n.topScore<.3?s="low":n.topScore>.7&&(s="medium");return{reply:this.licenseManager.processResponse(n.answer),confidence:s,sources:n.sources.map(e=>({title:e.title,snippet:e.snippet,relevance:e.score})),offline:!0,degradedReason:t.loadedFromExport?"Using pre-exported vectors (offline)":"Processed locally with TF-IDF"}}catch(e){console.error("[Cybernetic] Local RAG error:",e)}const n=this.cache.getStatus();if(0===n.documentCount&&!t.loaded)return{reply:"I'm currently offline and don't have any cached information. Please check your connection and try again.",confidence:"none",sources:[],offline:!0,degradedReason:"No cached documents or offline vectors available"};try{const t=await this.cache.retrieve();this.localRAG.isIndexed()||await this.localRAG.index(t);const s=await this.localRAG.ask(e);let i="medium";s.topScore<.3?i="low":s.topScore>.7&&(i="medium");return{reply:this.licenseManager.processResponse(s.answer),confidence:i,sources:s.sources.map(e=>({title:e.title,snippet:e.snippet,relevance:e.score})),offline:!0,degradedReason:n.isStale?"Using stale cached data":"Processed locally without server"}}catch(e){return console.error("[Cybernetic] Local RAG error:",e),{reply:"I'm having trouble processing your request offline. Please try again when you're back online.",confidence:"none",sources:[],offline:!0,degradedReason:"Local RAG processing failed"}}}monitorConnection(){"undefined"!=typeof window&&(window.addEventListener("online",()=>{this.syncCache().catch(()=>{})}),window.addEventListener("offline",()=>{this.setStatus("offline")}),navigator.onLine||this.setStatus("offline"))}setStatus(e){this.status!==e&&(this.status=e,this.config.onStatusChange(e))}normalizeError(e){if(e instanceof Error){if(e.message.includes("401")||e.message.includes("Unauthorized"))return{code:"AUTH_ERROR",message:"Invalid or expired API key",originalError:e};if(e.message.includes("429")||e.message.includes("Rate limit")){const t=e.message.match(/retry after (\d+)/i);return{code:"RATE_LIMIT",message:"Rate limit exceeded",retryAfter:t?parseInt(t[1],10):60,originalError:e}}return e.message.includes("5")||e.message.includes("Server")?{code:"SERVER_ERROR",message:"Server error occurred",originalError:e}:{code:"NETWORK_ERROR",message:e.message||"Network error",originalError:e}}return{code:"NETWORK_ERROR",message:"Unknown error occurred"}}createErrorResponse(e,t,n){return{reply:e,confidence:t,sources:[],offline:!1,retryAfter:n}}sleep(e){return new Promise(t=>setTimeout(t,e))}}const $="https://api.astermind.ai";function T(e){if(!e||"object"!=typeof e)throw new Error("Config must be an object");const t=e;if(!t.apiUrl||"string"!=typeof t.apiUrl)throw new Error("apiUrl is required and must be a string");if(!t.apiKey||"string"!=typeof t.apiKey)throw new Error("apiKey is required and must be a string");if(!t.apiKey.startsWith("am_"))throw new Error('apiKey must start with "am_"');return!0}class F{constructor(e,t,n){this.staticEntries=[],this.discoveredEntries=[],this.backendEntries=[],this.backendCache=null,this.isInitialized=!1,this.initPromise=null,this.config=e,this.apiUrl=t,this.apiKey=n,e.static&&(this.staticEntries=this.enhanceEntries(e.static,"props"))}async initialize(){if(!this.isInitialized){if(this.initPromise)return this.initPromise;this.initPromise=this.performInitialization(),await this.initPromise,this.isInitialized=!0}}async performInitialization(){const e=[];!1!==this.config.discovery?.enabled&&e.push(this.discoverFromFramework()),!1!==this.config.backend?.enabled&&this.config.backend?.endpoint&&e.push(this.fetchFromBackend());const t=await Promise.allSettled(e);for(const e of t)if("fulfilled"===e.status){const{entries:t,source:n}=e.value;"discovery"===n?this.discoveredEntries=t:"backend"===n&&(this.backendEntries=t)}else console.warn("[SiteMapDiscovery] Source failed:",e.reason);const n=this.staticEntries.length+this.discoveredEntries.length+this.backendEntries.length;console.log(`[SiteMapDiscovery] Initialized with ${n} total entries (${this.staticEntries.length} static, ${this.discoveredEntries.length} discovered, ${this.backendEntries.length} backend)`)}getMergedEntries(){return this.mergeEntries(this.staticEntries,this.discoveredEntries,this.backendEntries)}getLegacyEntries(){return this.getMergedEntries().map(e=>({path:e.path,name:e.name,description:e.description,params:e.params,dynamicParams:e.dynamicParams,aliases:e.aliases}))}async discoverFromFramework(){const e=this.config.discovery||{},t=[];try{const n=e.framework||this.detectFramework();let s=[];switch(n){case"react-router":s=this.discoverReactRouter();break;case"vue-router":s=this.discoverVueRouter();break;case"next":s=this.discoverNextRoutes();break;case"angular":s=this.discoverAngularRoutes();break;default:!1!==e.domFallback&&(s=this.discoverFromDOM(e.navSelectors))}for(const n of s){if(this.shouldExcludeRoute(n.path,e.excludePaths))continue;let s;s=e.transformRoute?e.transformRoute(n):this.defaultRouteTransform(n),s&&t.push(this.enhanceEntry(s,"discovery"))}console.log(`[SiteMapDiscovery] Discovered ${t.length} routes from ${n}`)}catch(e){return console.warn("[SiteMapDiscovery] Framework discovery failed:",e),{entries:[],source:"discovery",timestamp:Date.now(),error:String(e)}}return{entries:t,source:"discovery",timestamp:Date.now()}}detectFramework(){if("undefined"==typeof window)return"generic";const e=window;return e.__REACT_ROUTER_DATA_ROUTER__||e.__reactRouterContext?"react-router":e.__VUE_ROUTER__||e.__VUE_APP__?.$router?"vue-router":e.__NEXT_DATA__?"next":e.ng||document.querySelector("[ng-version]")?"angular":"generic"}discoverReactRouter(){const e=[];if("undefined"==typeof window)return e;const t=window.__REACT_ROUTER_DATA_ROUTER__;return t?.routes?(this.extractRoutesFromConfig(t.routes,e,""),e):e}extractRoutesFromConfig(e,t,n){for(const s of e){const e=this.normalizePath(n,s.path||""),i={path:e,name:s.handle?.name||s.handle?.title||s.id,meta:s.handle||{},children:[]};(s.path||s.index)&&t.push(i),s.children&&this.extractRoutesFromConfig(s.children,t,e)}}discoverVueRouter(){const e=[];if("undefined"==typeof window)return e;const t=window,n=t.__VUE_APP__,s=n?.$router||t.__VUE_ROUTER__;if(s?.getRoutes){const t=s.getRoutes();for(const n of t)e.push({path:n.path,name:n.name?.toString(),meta:n.meta||{},component:n.components?.default?.name})}return e}discoverNextRoutes(){const e=[];if("undefined"==typeof window)return e;const t=window.__NEXT_DATA__;if(!t)return e;const n=t.buildManifest?.pages||{};for(const t of Object.keys(n))t.startsWith("/_")||e.push({path:t,name:this.pathToName(t)});return e}discoverAngularRoutes(){return[]}discoverFromDOM(e){const t=[];if("undefined"==typeof document)return t;const n=e||["nav a[href]",'[role="navigation"] a[href]',".nav a[href]",".navigation a[href]",".sidebar a[href]",".menu a[href]","header a[href]"],s=new Set;for(const e of n)try{const n=document.querySelectorAll(e);for(const e of n){const n=e.getAttribute("href");if(!n)continue;if(n.startsWith("http")&&!n.startsWith(window.location.origin))continue;const i=n.startsWith("/")?n:`/${n}`;if(s.has(i)||i.startsWith("/#")||"/"===i||i.includes("javascript:"))continue;s.add(i);const o=i.split("?")[0].split("#")[0];t.push({path:o,name:e.textContent?.trim()||this.pathToName(o)})}}catch(e){}return t}async fetchFromBackend(){const e=this.config.backend||{},t=e.endpoint||"/api/external/sitemap";if(this.backendCache&&Date.now()<this.backendCache.expiresAt)return{entries:this.backendCache.entries,source:"backend",timestamp:this.backendCache.fetchedAt};try{const n=new URL(t,this.apiUrl);!1!==e.tenantScoped&&n.searchParams.set("tenantScoped","true"),!1!==e.includeGeneral&&n.searchParams.set("includeGeneral","true");const s=await fetch(n.toString(),{method:"GET",headers:{"X-API-Key":this.apiKey,"Content-Type":"application/json",...e.headers}});if(!s.ok)throw new Error(`Backend sitemap fetch failed: ${s.status}`);const i=await s.json(),o=this.transformBackendResponse(i),r=e.cacheTtl||3e5;return this.backendCache={entries:o,fetchedAt:Date.now(),expiresAt:Date.now()+r},console.log(`[SiteMapDiscovery] Loaded ${o.length} routes from backend`),{entries:o,source:"backend",timestamp:Date.now()}}catch(e){return console.warn("[SiteMapDiscovery] Backend fetch failed:",e),{entries:this.backendCache?.entries||[],source:"backend",timestamp:Date.now(),error:String(e)}}}transformBackendResponse(e){return(Array.isArray(e)?e:e.entries||e.sitemap||e.routes||[]).map(e=>this.enhanceEntry({path:e.url||e.path,name:e.title||e.name,description:e.description,aliases:e.keywords||e.aliases,params:e.params,dynamicParams:e.dynamicParams},"backend"))}mergeEntries(...e){const t=this.config.merge||{},n=t.sourcePriority||["props","backend","discovery"],s=t.deduplication||"path",i=new Map;n.forEach((e,t)=>{i.set(e,n.length-t)});const o=[];for(const t of e)for(const e of t){const t=i.get(e._source||"props")||0;o.push({...e,_priority:t})}o.sort((e,t)=>(t._priority||0)-(e._priority||0));const r=new Map;for(const e of o){let n;switch(s){case"name":n=e.name.toLowerCase();break;case"both":n=`${e.path}|${e.name.toLowerCase()}`;break;default:n=this.normalizePath("",e.path)}if(r.has(n)){if(!1!==t.keepNonConflicting){const t=r.get(n);!t.description&&e.description&&(t.description=e.description),!t.aliases?.length&&e.aliases?.length&&(t.aliases=e.aliases)}}else r.set(n,e)}return Array.from(r.values())}enhanceEntries(e,t){return e.map(e=>this.enhanceEntry(e,t))}enhanceEntry(e,t){return{...e,_source:t,_discoveredAt:Date.now()}}defaultRouteTransform(e){return e.path&&"*"!==e.path&&"**"!==e.path?{path:e.path,name:e.name||e.meta?.title||this.pathToName(e.path),description:e.meta?.description,aliases:e.meta?.keywords||e.meta?.aliases,dynamicParams:e.path.includes(":")||e.path.includes("[")}:null}normalizePath(e,t){return t&&"/"!==t?t.startsWith("/")?t:e&&"/"!==e?`${e}/${t}`.replace(/\/+/g,"/"):`/${t}`:e||"/"}pathToName(e){const t=e.split("/").filter(Boolean);return(t[t.length-1]||"Home").replace(/[-_]/g," ").replace(/\[.*?\]/g,"").replace(/:/g,"").split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ").trim()||"Page"}shouldExcludeRoute(e,t){if(!t?.length)return!1;for(const n of t){if(new RegExp("^"+n.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(e))return!0}return!1}async refresh(){this.backendCache=null,this.isInitialized=!1,this.initPromise=null,await this.initialize()}isReady(){return this.isInitialized}getStats(){return{static:this.staticEntries.length,discovered:this.discoveredEntries.length,backend:this.backendEntries.length,merged:this.getMergedEntries().length}}}const P={navigate:[{pattern:/^(go to|navigate to|take me to|open|show me|bring up)\s+(.+)/i,type:"navigate",weight:.9},{pattern:/^(i want to see|i need to go to|let me see)\s+(.+)/i,type:"navigate",weight:.85},{pattern:/^(where is|how do i get to)\s+(.+)/i,type:"navigate",weight:.6}],fillForm:[{pattern:/^(search for|find|look up|search)\s+(.+)/i,type:"fillForm",weight:.88},{pattern:/^(filter by|set .+ to|change .+ to)\s+(.+)/i,type:"fillForm",weight:.85},{pattern:/^(enter|type|put)\s+(.+)\s+(in|into)\s+(.+)/i,type:"fillForm",weight:.9}],clickElement:[{pattern:/^(click|press|hit|tap)\s+(the\s+)?(.+)\s+(button|link)/i,type:"clickElement",weight:.9},{pattern:/^(submit|send|confirm|save|cancel|delete)/i,type:"clickElement",weight:.85}],triggerModal:[{pattern:/^(open|show|display)\s+(the\s+)?(.+)\s+(modal|dialog|popup|window)/i,type:"triggerModal",weight:.9},{pattern:/^(open|show)\s+(help|settings|preferences|options)/i,type:"triggerModal",weight:.85}],scroll:[{pattern:/^(scroll to|jump to|go to)\s+(the\s+)?(.+)\s+(section|area|part)/i,type:"scroll",weight:.85},{pattern:/^(show me|take me to)\s+(the\s+)?(bottom|top|end|beginning)/i,type:"scroll",weight:.8}],highlight:[{pattern:/^(highlight|show me|point to|where is)\s+(the\s+)?(.+)/i,type:"highlight",weight:.7}],custom:[{pattern:/^(export|download|refresh|reload|sync)/i,type:"custom",weight:.85}]};class O{constructor(e,t="",n=""){this.categories=[],this.topicKeywords=new Map,this.siteMapDiscovery=null,this.config=e,this.siteMapIndex=new Map,this.formIndex=new Map,this.modalIndex=new Map,this.buildIndexes(),e.siteMapConfig&&(this.siteMapDiscovery=new F(e.siteMapConfig,t,n))}buildIndexes(){if(this.config.siteMap)for(const e of this.config.siteMap){const t=[e.name.toLowerCase(),e.path.toLowerCase(),...(e.aliases||[]).map(e=>e.toLowerCase())];for(const n of t)this.siteMapIndex.set(n,e)}if(this.config.forms)for(const[e,t]of Object.entries(this.config.forms)){const n=[e.toLowerCase(),t.name.toLowerCase(),...(t.aliases||[]).map(e=>e.toLowerCase())];for(const e of n)this.formIndex.set(e,t)}if(this.config.modals)for(const[e,t]of Object.entries(this.config.modals)){const n=[e.toLowerCase(),t.id.toLowerCase(),...(t.aliases||[]).map(e=>e.toLowerCase())];for(const e of n)this.modalIndex.set(e,t)}}classify(e){if(!this.config.enabled)return{action:null,shouldEscalate:!0,rawConfidence:0};const t=e.trim().toLowerCase();for(const[t,n]of Object.entries(P))for(const{pattern:s,weight:i}of n){const n=e.match(s);if(n){const e=this.buildAction(t,n,i);if(e)return e}}const n=this.fuzzyMatchSiteMap(t);if(n)return n;const s=this.matchCustomAction(t);return s||{action:null,shouldEscalate:!0,rawConfidence:0,matchedPatterns:[]}}buildAction(e,t,n){const s=this.config.confidenceThreshold??.8;switch(e){case"navigate":{const e=this.extractTarget(t),i=this.findSiteMapMatch(e);if(i){const e=n*i.similarity;return{action:{id:`action-${Date.now()}`,type:"navigate",target:i.entry.path,confidence:e,explanation:`Navigate to ${i.entry.name}`},shouldEscalate:e<s,rawConfidence:e,matchedPatterns:["navigate",i.entry.name]}}break}case"fillForm":{const e=this.extractTarget(t),{field:i,value:o}=this.parseFormIntent(t);if(i){const e=.95*n;return{action:{id:`action-${Date.now()}`,type:"fillForm",target:i.selector,params:{value:o},confidence:e,explanation:`Fill "${i.name}" with "${o}"`},shouldEscalate:e<s,rawConfidence:e,matchedPatterns:["fillForm",i.name]}}if(this.config.forms?.search){const t=.9*n;return{action:{id:`action-${Date.now()}`,type:"fillForm",target:this.config.forms.search.selector,params:{value:e},confidence:t,explanation:`Search for "${e}"`},shouldEscalate:t<s,rawConfidence:t,matchedPatterns:["fillForm","search"]}}break}case"clickElement":{const e=this.extractTarget(t),i=this.findButtonSelector(e);if(i){const t=.95*n;return{action:{id:`action-${Date.now()}`,type:"clickElement",target:i,confidence:t,explanation:`Click "${e}" button`},shouldEscalate:t<s,rawConfidence:t,matchedPatterns:["clickElement",e]}}break}case"triggerModal":{const e=this.extractTarget(t),i=this.findModalConfig(e);if(i){const e=.95*n;return{action:{id:`action-${Date.now()}`,type:"triggerModal",target:i.trigger,confidence:e,explanation:`Open ${i.id} modal`},shouldEscalate:e<s,rawConfidence:e,matchedPatterns:["triggerModal",i.id]}}break}case"scroll":{const e=this.extractTarget(t),i=this.findScrollTarget(e);if(i){const t=.9*n;return{action:{id:`action-${Date.now()}`,type:"scroll",target:i,confidence:t,explanation:`Scroll to ${e}`},shouldEscalate:t<s,rawConfidence:t,matchedPatterns:["scroll",e]}}break}case"highlight":{const e=this.extractTarget(t),i=this.findElementByDescription(e);if(i){const t=.85*n;return{action:{id:`action-${Date.now()}`,type:"highlight",target:i,confidence:t,explanation:`Highlight ${e}`},shouldEscalate:t<s,rawConfidence:t,matchedPatterns:["highlight",e]}}break}case"custom":{const e=t[1]?.toLowerCase();if(this.config.customActions?.[e]){const t=.95*n;return{action:{id:`action-${Date.now()}`,type:"custom",target:e,confidence:t,explanation:`Execute ${e} action`},shouldEscalate:t<s,rawConfidence:t,matchedPatterns:["custom",e]}}break}}return null}extractTarget(e){for(let t=e.length-1;t>=1;t--)if(e[t])return e[t].trim();return""}stripArticles(e){return e.replace(/^(the|a|an|my|our|your|this|that)\s+/gi,"").replace(/\s+(page|section|screen|view)$/gi,"").trim()}findSiteMapMatch(e){const t=e.toLowerCase().replace(/[^a-z0-9\s]/g,""),n=this.stripArticles(t),s=this.siteMapIndex.get(t)||this.siteMapIndex.get(n);if(s)return{entry:s,similarity:1};let i=null,o=0;for(const[e,s]of this.siteMapIndex){const r=this.calculateSimilarity(t,e),a=this.calculateSimilarity(n,e),c=Math.max(r,a);c>o&&c>.5&&(o=c,i=s)}return i?{entry:i,similarity:o}:null}fuzzyMatchSiteMap(e){const t=this.config.confidenceThreshold??.8;for(const[n,s]of this.siteMapIndex)if(e.includes(n)){const e=.75;return{action:{id:`action-${Date.now()}`,type:"navigate",target:s.path,confidence:e,explanation:`Navigate to ${s.name}`},shouldEscalate:e<t,rawConfidence:e,matchedPatterns:["fuzzy-sitemap",n]}}return null}matchCustomAction(e){if(!this.config.customActions)return null;const t=this.config.confidenceThreshold??.8;for(const n of Object.keys(this.config.customActions))if(e.includes(n.toLowerCase())){const e=.85;return{action:{id:`action-${Date.now()}`,type:"custom",target:n,confidence:e,explanation:`Execute ${n}`},shouldEscalate:e<t,rawConfidence:e,matchedPatterns:["custom",n]}}return null}parseFormIntent(e){const t=e[0];for(const[,e]of this.formIndex)if(t.toLowerCase().includes(e.name.toLowerCase())){const n=t.match(new RegExp(`${e.name}[^a-z]*(.+)`,"i"));return{field:e,value:n?.[1]?.trim()||""}}return{field:null,value:this.extractTarget(e)}}findButtonSelector(e){const t=e.toLowerCase();if("undefined"==typeof document)return`button:contains("${e}")`;const n=[`[data-action="${t}"]`,`[aria-label*="${t}" i]`,`.btn-${t}`,`#${t}-button`,`button.${t}`];for(const e of n)try{if(document.querySelector(e))return e}catch{}const s=document.querySelectorAll('button, [role="button"], a.btn');for(const e of s)if(e.textContent?.toLowerCase().includes(t))return this.generateUniqueSelector(e);return null}findModalConfig(e){return this.modalIndex.get(e.toLowerCase())||null}findScrollTarget(e){const t=e.toLowerCase();if("top"===t||"beginning"===t)return"body";if("bottom"===t||"end"===t)return"body:last-child";if("undefined"==typeof document)return`#${t.replace(/\s+/g,"-")}`;const n=[`#${t.replace(/\s+/g,"-")}`,`[data-section="${t}"]`,`.${t.replace(/\s+/g,"-")}-section`,`section[aria-label*="${t}" i]`];for(const e of n)try{if(document.querySelector(e))return e}catch{continue}return null}findElementByDescription(e){const t=e.toLowerCase();if("undefined"==typeof document)return`[aria-label*="${t}" i]`;const n=[`[aria-label*="${t}" i]`,`[data-testid*="${t}" i]`,`[title*="${t}" i]`];for(const e of n)try{if(document.querySelector(e))return e}catch{continue}return null}generateUniqueSelector(e){if(e.id)return`#${e.id}`;if(e.getAttribute("data-testid"))return`[data-testid="${e.getAttribute("data-testid")}"]`;const t=[];let n=e;for(;n&&n!==document.body;){let e=n.tagName.toLowerCase();if(n.className&&"string"==typeof n.className){const t=n.className.split(" ").filter(e=>e&&!e.includes(" "));t.length>0&&(e+=`.${t.slice(0,2).join(".")}`)}t.unshift(e),n=n.parentElement}return t.join(" > ")}calculateSimilarity(e,t){const n=new Set(e.split(/\s+/)),s=new Set(t.split(/\s+/)),i=new Set([...n].filter(e=>s.has(e))),o=new Set([...n,...s]);return i.size/o.size}getConfig(){return this.config}async trainFromExport(e){if(e.categories){this.categories=e.categories;for(const t of e.categories)for(const e of t.keywords){const n=this.topicKeywords.get(t.name)||[];n.push(e.toLowerCase()),this.topicKeywords.set(t.name,n)}}const t=this.extractTopicsFromDocuments(e.documents);for(const[e,n]of t){const t=this.topicKeywords.get(e)||[];t.push(...n),this.topicKeywords.set(e,[...new Set(t)])}e.sitemap&&this.loadSitemapEntries(e.sitemap),console.log(`[CyberneticIntentClassifier] Trained with ${this.categories.length} categories, ${this.topicKeywords.size} topics`)}async loadSitemap(e){if(e.enabled)if(e.sitemapData)this.loadSitemapEntries(e.sitemapData);else if(e.sitemapUrl)try{const t=await fetch(e.sitemapUrl);if(!t.ok)throw new Error(`Failed to fetch sitemap: ${t.status}`);const n=await t.json();this.loadSitemapEntries(n)}catch(e){console.error("[CyberneticIntentClassifier] Failed to load sitemap:",e)}}loadSitemapEntries(e){for(const t of e){const e={path:t.url,name:t.title,description:t.description,aliases:t.keywords},n=[t.title.toLowerCase(),t.url.toLowerCase(),...(t.keywords||[]).map(e=>e.toLowerCase())];if(t.description){const e=t.description.toLowerCase().split(/\s+/).filter(e=>e.length>4);n.push(...e)}for(const t of n)this.siteMapIndex.set(t,e)}console.log(`[CyberneticIntentClassifier] Loaded ${e.length} sitemap entries`)}extractTopicsFromDocuments(e){const t=new Map;for(const n of e){const e=n.title.toLowerCase(),s=[];n.metadata?.keywords&&s.push(...n.metadata.keywords.map(e=>e.toLowerCase()));const i=n.title.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(e=>e.length>3&&!this.isStopWord(e));s.push(...i);const o=n.content.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(e=>e.length>4&&!this.isStopWord(e)),r=new Map;for(const e of o)r.set(e,(r.get(e)||0)+1);const a=[...r.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5).map(([e])=>e);s.push(...a),t.set(e,[...new Set(s)])}return t}isStopWord(e){return new Set(["the","a","an","and","or","but","in","on","at","to","for","of","with","by","from","up","about","into","through","during","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","this","that","these","those","it","its","they","them","their","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","not","only","same","so","than","too","very","can","just","dont","now","here","there","also","your","you"]).has(e)}getCategories(){return this.categories}getTopicKeywords(){return this.topicKeywords}isTrained(){return this.categories.length>0||this.topicKeywords.size>0}async initializeDiscovery(){if(this.siteMapDiscovery)try{await this.siteMapDiscovery.initialize(),this.rebuildIndexesFromDiscovery(),console.log(`[CyberneticIntentClassifier] Discovery complete, indexed ${this.siteMapIndex.size} entries`)}catch(e){console.error("[CyberneticIntentClassifier] Discovery initialization failed:",e)}else console.log("[CyberneticIntentClassifier] No siteMapConfig provided, skipping discovery")}rebuildIndexesFromDiscovery(){if(!this.siteMapDiscovery)return;const e=this.siteMapDiscovery.getLegacyEntries();this.siteMapIndex.clear();for(const t of e){const e={path:t.path,name:t.name,description:t.description,params:t.params,aliases:t.aliases},n=[t.name.toLowerCase(),t.path.toLowerCase(),...(t.aliases||[]).map(e=>e.toLowerCase())];if(t.description){const e=t.description.toLowerCase().split(/\s+/).filter(e=>e.length>4&&!this.isStopWord(e));n.push(...e)}for(const t of n)this.siteMapIndex.set(t,e)}}isSiteMapReady(){return this.siteMapDiscovery?this.siteMapDiscovery.isReady():this.siteMapIndex.size>0||(this.config.siteMap?.length??0)>0}async ensureSiteMapReady(){this.isSiteMapReady()||await this.initializeDiscovery()}async refreshSiteMap(){this.siteMapDiscovery?(await this.siteMapDiscovery.refresh(),this.rebuildIndexesFromDiscovery()):console.log("[CyberneticIntentClassifier] No siteMapConfig provided, cannot refresh")}getSiteMapDiscovery(){return this.siteMapDiscovery}getSiteMapEntries(){return this.siteMapDiscovery?this.siteMapDiscovery.getLegacyEntries():this.config.siteMap||[]}}class U{constructor(e){this.highlightOverlay=null,this.actionCount=0,this.lastActionReset=Date.now(),this.config=e,this.classifier=new O(e),"undefined"!=typeof document&&this.injectStyles()}interpretIntent(e){return this.classifier.classify(e)}async executeAction(e){const t=Date.now();t-this.lastActionReset>6e4&&(this.actionCount=0,this.lastActionReset=t);const n=this.config.maxActionsPerTurn??5;if(this.actionCount>=n)return{success:!1,message:`Rate limit exceeded. Maximum ${n} actions per minute.`};if(!this.isActionAllowed(e))return{success:!1,message:`Action type "${e.type}" is not allowed`};switch(this.actionCount++,e.type){case"navigate":return this.navigate(e.target,e.params);case"fillForm":return this.fillForm(e.target,e.params?.value);case"clickElement":return this.clickElement(e.target);case"triggerModal":return this.triggerModal(e.target);case"scroll":return this.scrollToElement(e.target);case"highlight":return this.highlightElement(e.target);case"custom":return this.executeCustomAction(e.target,e.params);default:return{success:!1,message:`Unknown action type: ${e.type}`}}}isActionAllowed(e){const t=this.config.allowedActions;if(!t)return!0;const n={navigate:"navigate",fillForm:"fill",clickElement:"click",scroll:"scroll",highlight:"click",triggerModal:"click",custom:"click"}[e.type];return t.includes(n)}isSelectorAllowed(e){if(this.config.blockedSelectors)for(const t of this.config.blockedSelectors)if(e.includes(t))return!1;return!(this.config.allowedSelectors&&this.config.allowedSelectors.length>0)||this.config.allowedSelectors.some(t=>e.includes(t))}async navigate(e,t){try{if(!this.validateNavigationUrl(e))return{success:!1,message:"Invalid or blocked URL"};let n=e;if(t){const e=new URLSearchParams;for(const[n,s]of Object.entries(t))null!=s&&e.set(n,String(s));const s=e.toString();s&&(n+=(n.includes("?")?"&":"?")+s)}return"undefined"==typeof window?{success:!0,message:`Navigation to ${e} would be executed (server-side)`}:this.isInternalUrl(n)?this.tryClientSideNavigation(n)?{success:!0,message:`Navigated to ${e}`}:(window.location.href=n,{success:!0,message:`Navigating to ${e}...`}):(window.open(n,"_blank","noopener,noreferrer"),{success:!0,message:`Opened ${n} in new tab`})}catch(e){return{success:!1,message:"Navigation failed",error:String(e)}}}async fillForm(e,t){if(!this.isSelectorAllowed(e))return{success:!1,message:`Selector "${e}" is not allowed`};const n=this.sanitizeSelector(e);if("undefined"==typeof document)return{success:!0,message:`Form fill would set "${n}" to "${t}" (server-side)`};try{const e=document.querySelector(n);if(!e)return{success:!1,message:`Element not found: ${n}`};if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement))return{success:!1,message:"Element is not a form field"};if(e.focus(),e instanceof HTMLSelectElement){const n=Array.from(e.options).find(e=>e.value.toLowerCase()===t.toLowerCase()||e.text.toLowerCase()===t.toLowerCase());if(!n)return{success:!1,message:`Option "${t}" not found`};e.value=n.value}else e.value=t;e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}));const s=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set;return s&&e instanceof HTMLInputElement&&(s.call(e,t),e.dispatchEvent(new Event("input",{bubbles:!0}))),{success:!0,message:`Filled field with "${t}"`}}catch(e){return{success:!1,message:"Failed to fill form field",error:String(e)}}}async clickElement(e){if(!this.isSelectorAllowed(e))return{success:!1,message:`Selector "${e}" is not allowed`};const t=this.sanitizeSelector(e);if("undefined"==typeof document)return{success:!0,message:`Click on "${t}" would be executed (server-side)`};try{const e=document.querySelector(t);return e?e instanceof HTMLElement?(e.scrollIntoView({behavior:"smooth",block:"center"}),await this.sleep(300),e.click(),{success:!0,message:"Element clicked"}):{success:!1,message:"Element is not clickable"}:{success:!1,message:`Element not found: ${t}`}}catch(e){return{success:!1,message:"Failed to click element",error:String(e)}}}async triggerModal(e){return this.clickElement(e)}async scrollToElement(e){if("undefined"==typeof window)return{success:!0,message:`Scroll to "${e}" would be executed (server-side)`};try{if("body"===e)return window.scrollTo({top:0,behavior:"smooth"}),{success:!0,message:"Scrolled to top"};if("body:last-child"===e)return window.scrollTo({top:document.body.scrollHeight,behavior:"smooth"}),{success:!0,message:"Scrolled to bottom"};const t=document.querySelector(e);return t?(t.scrollIntoView({behavior:"smooth",block:"start"}),{success:!0,message:"Scrolled to element"}):{success:!1,message:`Element not found: ${e}`}}catch(e){return{success:!1,message:"Failed to scroll",error:String(e)}}}async highlightElement(e){if(!this.isSelectorAllowed(e))return{success:!1,message:`Selector "${e}" is not allowed`};if("undefined"==typeof document)return{success:!0,message:`Highlight on "${e}" would be shown (server-side)`};try{const t=document.querySelector(e);if(!t)return{success:!1,message:`Element not found: ${e}`};this.removeHighlight(),t.scrollIntoView({behavior:"smooth",block:"center"}),await this.sleep(300);const n=t.getBoundingClientRect(),s=document.createElement("div");return s.className="astermind-highlight-overlay",s.style.cssText=`\n position: fixed;\n top: ${n.top-4}px;\n left: ${n.left-4}px;\n width: ${n.width+8}px;\n height: ${n.height+8}px;\n border: 3px solid #4F46E5;\n border-radius: 4px;\n pointer-events: none;\n z-index: 999999;\n animation: astermind-highlight-pulse 1s ease-in-out 3;\n `,document.body.appendChild(s),this.highlightOverlay=s,setTimeout(()=>this.removeHighlight(),3e3),{success:!0,message:"Element highlighted"}}catch(e){return{success:!1,message:"Failed to highlight element",error:String(e)}}}async executeCustomAction(e,t){if(!this.isAllowedCustomAction(e))return{success:!1,message:`Custom action "${e}" not found`};const n=this.config.customActions[e];try{return await n(t)}catch(t){return{success:!1,message:`Custom action "${e}" failed`,error:String(t)}}}isInternalUrl(e){if(e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))return!0;if("undefined"==typeof window)return!0;try{return new URL(e,window.location.href).origin===window.location.origin}catch{return!0}}tryClientSideNavigation(e){if("undefined"==typeof window)return!1;try{return window.history.pushState({},"",e),window.dispatchEvent(new PopStateEvent("popstate")),e.includes("#")&&window.dispatchEvent(new HashChangeEvent("hashchange")),!0}catch{return!1}}validateNavigationUrl(e){if(/^(javascript|data):/i.test(e))return!1;if("undefined"==typeof window)return!0;try{return new URL(e,window.location.href).origin===window.location.origin||e.startsWith("/")}catch{return e.startsWith("/")}}sanitizeSelector(e){return e.replace(/[<>'"]/g,"").replace(/javascript:/gi,"").replace(/data:/gi,"").trim()}isAllowedCustomAction(e){return void 0!==this.config.customActions&&Object.prototype.hasOwnProperty.call(this.config.customActions,e)}removeHighlight(){this.highlightOverlay&&(this.highlightOverlay.remove(),this.highlightOverlay=null)}injectStyles(){if("undefined"==typeof document)return;if(document.getElementById("astermind-agent-styles"))return;const e=document.createElement("style");e.id="astermind-agent-styles",e.textContent="\n @keyframes astermind-highlight-pulse {\n 0%, 100% {\n box-shadow: 0 0 0 0 rgba(79, 70, 229, 0.4);\n }\n 50% {\n box-shadow: 0 0 0 10px rgba(79, 70, 229, 0);\n }\n }\n\n .astermind-highlight-overlay {\n transition: all 0.2s ease-out;\n }\n ",document.head.appendChild(e)}sleep(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return this.config}getClassifier(){return this.classifier}resetActionCount(){this.actionCount=0,this.lastActionReset=Date.now()}}const z={hiddenUnits:50,activation:"relu",ridgeLambda:.01,weightInit:"xavier",seed:1337,dropout:0,log:{verbose:!0,toFile:!1,modelName:"Unnamed ELM Model",level:"info"}};function N(e){let t=0,n=0;for(;0===t;)t=e();for(;0===n;)n=e();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*n)}Object.assign(Object.assign({},z),{useTokenizer:!1}),Object.assign(Object.assign({},z),{useTokenizer:!0,maxLen:30,charSet:"abcdefghijklmnopqrstuvwxyz",tokenizerDelimiter:/\s+/});class j{constructor(e,t,n=1e-4){this.p=e,this.m=t,this.lambda=n,this.Ainv=new Float64Array(e*e),this.Beta=new Float64Array(e*t);const s=1/Math.max(1e-12,n);for(let t=0;t<e;t++)this.Ainv[t*e+t]=s}update(e,t){const{p:n,m:s,Ainv:i,Beta:o}=this,r=new Float64Array(n);for(let t=0;t<n;t++){let s=0,o=t*n;for(let t=0;t<n;t++)s+=i[o+t]*e[t];r[t]=s}let a=1;for(let t=0;t<n;t++)a+=e[t]*r[t];a=Math.max(a,1e-12);const c=1/a;for(let e=0;e<n;e++){const t=r[e]*c;for(let s=0;s<n;s++)i[e*n+s]-=t*r[s]}for(let t=0;t<n;t++){let s=0,o=t*n;for(let t=0;t<n;t++)s+=i[o+t]*e[t];r[t]=s}for(let e=0;e<n;e++){const n=r[e];for(let i=0;i<s;i++)o[e*s+i]+=n*t[i]}}predict(e){const{p:t,m:n,Beta:s}=this,i=new Float64Array(n);for(let o=0;o<n;o++){let r=0;for(let i=0;i<t;i++)r+=e[i]*s[i*n+o];i[o]=r}return i}}function K(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(Math.max(0,t))}function G(e,t){var n,s;const i=Math.min(e.length,t.length);if(0===i)return 0;let o=0,r=0,a=0;for(let c=0;c<i;c++){const i=null!==(n=e[c])&&void 0!==n?n:0,l=null!==(s=t[c])&&void 0!==s?s:0;o+=i*l,r+=i*i,a+=l*l}const c=o/Math.sqrt(Math.max(r*a,1e-12));return Number.isFinite(c)?c:0}function B(e,t,n,s){return new(n||(n=Promise))(function(i,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}c((s=s.apply(e,t||[])).next())})}function W(e){return e.replace(/\s+/g," ").split(/(?<=[.?!])\s+/).map(e=>e.trim()).filter(e=>e.length>8&&/\w/.test(e))}function q(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]+`/g," ").replace(/\[[^\]]*\]\([^)]*\)/g,"").replace(/[-–>•→]/g," ").replace(/\s+/g," ").trim()}function V(e,t){return B(this,arguments,void 0,function*(e,t,n={}){if(!(null==t?void 0:t.length))return"No results found.";const{dim:s=64,features:i=32,sigma:o=1,rounds:r=3,topSentences:a=8,personality:c="neutral"}=n;let l=W(t.map(e=>q(e.content)).join(" ")).filter(e=>!function(e){return/^(\*|#)/.test(e)||/chapter/i.test(e)||/part\s*\d+/i.test(e)||/section/i.test(e)||/^\s*[A-Z]\)\s*$/.test(e)||e.length<15}(e)).slice(0,120);if(0===l.length)return q(t[0].content).slice(0,400);const h=function(e,t,n=1,s=Math.random){const i=new Float64Array(t*e),o=new Float64Array(t),r=1/Math.max(1e-12,n);for(let n=0;n<t*e;n++)i[n]=N(s)*r;for(let e=0;e<t;e++)o[e]=2*s()*Math.PI;return{W:i,b:o,D:t,d:e,sigma:n}}(s,i,o),d=new j(2*i,1,.001),u=e=>{const t=new Float64Array(s),n=Math.min(e.length,s);for(let s=0;s<n;s++)t[s]=e.charCodeAt(s)/255;return function(e,t){const{W:n,b:s,D:i,d:o}=e,r=new Float64Array(2*i);for(let e=0;e<i;e++){let a=s[e];const c=e*o;for(let e=0;e<o;e++)a+=n[c+e]*(t[e]||0);r[e]=Math.cos(a),r[i+e]=Math.sin(a)}let a=0;for(let e=0;e<r.length;e++)a+=r[e]*r[e];const c=1/Math.sqrt(Math.max(a,1e-12));for(let e=0;e<r.length;e++)r[e]*=c;return r}(h,function(e,t=1e-12){const n=K(e);if(!(n>t&&Number.isFinite(n)))return new Float64Array(e.length);const s=new Float64Array(e.length),i=1/n;for(let t=0;t<e.length;t++)s[t]=e[t]*i;return s}(t))},f=u(e),g=e.toLowerCase().split(/\W+/).filter(e=>e.length>2),m=l.map(e=>{const t=u(e);let n=G(t,f);const s=e.toLowerCase();for(const e of g)s.includes(e)&&(n+=.02);return{s:e,v:t,w:n}});m.sort((e,t)=>t.w-e.w);let p=m.slice(0,a).map(e=>e.s).join(" "),y=new Float64Array(2*i);for(let e=0;e<r;e++){const e=W(p).slice(0,a),t=e.map(e=>u(e)),n=t.map(e=>G(e,f));for(let e=0;e<t.length;e++)d.update(t[e],new Float64Array([n[e]]));y.fill(0);for(let e=0;e<t.length;e++){const s=t[e],i=n[e];for(let e=0;e<s.length;e++)y[e]+=s[e]*i}const s=K(y)||1;for(let e=0;e<y.length;e++)y[e]/=s;const i=e.map(e=>({s:e,w:G(u(e),y)}));i.sort((e,t)=>t.w-e.w),p=i.slice(0,Math.max(3,Math.floor(a/2))).map(e=>e.s).join(" ")}p=function(e){return e.replace(/\s+[-–>•→]\s+/g," ").replace(/\s+\.\s+/g,". ").replace(/([a-z]) - ([a-z])/gi,"$1-$2").replace(/\s{2,}/g," ").trim()}(p);return`${"teacher"===c?"Here’s a simple way to think about it:\n\n":"scientist"===c?"From the retrieved material, we can infer:\n\n":""}${p.charAt(0).toUpperCase()+p.slice(1)}\n\n(${t[0].heading||"Answer"}, Ω-synthesized)`})}function H(e,t){let n=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s];return n}function J(e,t,n,s){if("cosine"===n){const n=H(e,t),s=Math.hypot(...e),i=Math.hypot(...t);return s&&i?n/(s*i):0}if("poly2"===n){const n=H(e,t);return Math.pow(n+1,2)}{let n=0;for(let s=0;s<e.length;s++){const i=e[s]-t[s];n+=i*i}return Math.exp(-n/Math.max(1e-9,2*s*s))}}function Q(e,t,n,s,i){const o=function(e,t){const n=new Float64Array(t);for(const[t,s]of e)n[t]=s;return n}(e,t),r=new Float64Array(n.length);for(let e=0;e<n.length;e++){const t=n[e];r[e]=J(o,t,s,i)}const a=Math.hypot(...r);if(a>0)for(let e=0;e<r.length;e++)r[e]/=a;return r}"function"==typeof SuppressedError&&SuppressedError;const Y=new Map;function X(e){const t=e,n=Y.get(t);if(n)return n;let s=e.toLowerCase();if(s=s.replace(/^[^a-z0-9]+|[^a-z0-9]+$/g,""),s.length<=2)return Y.set(t,s),s;s.endsWith("ies")&&s.length>4?s=s.slice(0,-3)+"y":/(xes|ches|shes|zes|sses)$/.test(s)&&s.length>4?s=s.replace(/(xes|ches|shes|zes|sses)$/,e=>"sses"===e?"ss":e.replace(/es$/,"")):s.endsWith("s")&&!/(ss|us)$/.test(s)&&s.length>3&&(s=s.slice(0,-1));const i=[[/ization$|isation$/,"ize"],[/ational$/,"ate"],[/fulness$/,"ful"],[/ousness$/,"ous"],[/iveness$/,"ive"],[/ability$/,"able"],[/ness$/,""],[/ment$/,""],[/ations?$/,"ate"],[/izer$|iser$/,"ize"],[/ally$/,"al"],[/ically$/,"ic"],[/ingly$|edly$/,""],[/ing$|ed$/,""]];for(const[e,t]of i)if(e.test(s)&&s.length-t.length>=4){s=s.replace(e,t);break}return Y.set(t,s),s}function Z(e,t){const n=Array.from(e,(e,t)=>t);return n.sort((t,n)=>e[n]-e[t]),n.slice(0,t)}function ee(e){const{query:t,chunks:n,vocabMap:s,idf:i,tfidfDocs:o,denseDocs:r,landmarksIdx:a,landmarkMat:c,vocabSize:l,kernel:h,sigma:d,alpha:u,beta:f,ridge:g,headingW:m,useStem:p,expandQuery:y,topK:w,prefilter:b}=e,v=function(e,t,n,s=1){const i=new Map;for(let t=0;t<e.length;t++){const o=e[t],r=n.get(o);if(void 0===r)continue;const a=t<8?s:1;i.set(r,(i.get(r)||0)+a)}const o=Math.max(1,...i.values()),r=new Map;for(const[e,n]of i){const s=.5+n/o*.5;r.set(e,s*(t[e]||0))}return r}(function(e,t){const n=e.toLowerCase().replace(/[`*_>~]/g," ").replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(Boolean);if(!t)return n;const s=[];for(const e of n){const t=X(e);t&&t.length>1&&s.push(t)}return s}(y?function(e){const t=[];return/\bmap\b/.test(e)&&t.push("dict key value make"),/\bchan|channel\b/.test(e)&&t.push("goroutine concurrency select buffer"),/\berror\b/.test(e)&&t.push("fmt wrap unwrap sentinel try catch"),/\bstruct\b/.test(e)&&t.push("field method receiver init zero value"),e+" "+t.join(" ")}(t):t,p),i,s,m),S=Q(v,l,c,h,d),C=o.map(e=>function(e,t){let n=0,s=0,i=0;for(const[i,o]of e){s+=o*o;const e=t.get(i);e&&(n+=o*e)}for(const[,e]of t)i+=e*e;return s&&i?n/(Math.sqrt(s)*Math.sqrt(i)):0}(e,v)),M=r.map(e=>function(e,t,n,s){if("cosine"===n){const n=H(e,t),s=Math.hypot(...e),i=Math.hypot(...t);return s&&i?n/(s*i):0}if("poly2"===n){const n=H(e,t);return Math.pow(n+1,2)}{let n=0;for(let s=0;s<e.length;s++){const i=e[s]-t[s];n+=i*i}return Math.exp(-n/Math.max(1e-9,2*s*s))}}(e,S,h,d)),A=function(e,t){const n=Array.from(new Set(t.toLowerCase().split(/\W+/).filter(e=>e.length>2))),s=/\b(define|declare|syntax|example|function|struct|map|interface)\b/i.test(t);return e.map(e=>{const t=e.rich||e.content||"",i=t.toLowerCase();let o=0;for(const e of n)i.includes(e)&&o++;return s&&/```/.test(t)&&(o+=5),Math.min(1,.03*o)})}(n,t),k=(E=u,x=0,R=1,Math.max(x,Math.min(R,E)));var E,x,R;const I=null!=g?g:.08,D=M.map((e,t)=>{const n=C[t],s=f*A[t],i=1/(1+I*(e*e+n*n+.5*s*s))*(k*e+(1-k)*n+s);return Math.tanh(i)}),L=Math.max(w,null!=b?b:0),_=Z(D,L),$=Z(_.map(e=>D[e]),w).map(e=>_[e]);return{items:$.map(e=>{const t=n[e],s=t.rich&&t.rich.trim()||t.content&&t.content.trim()||"(see subsections)";return{score:D[e],heading:t.heading,content:s,index:e}}),scores:$.map(e=>D[e]),indices:$,tfidfScores:$.map(e=>C[e]),denseScores:$.map(e=>M[e])}}const te=new Set(["a","an","the","and","or","but","if","then","else","for","to","of","in","on","at","by","with","is","are","was","were","be","been","being","as","from","that","this","it","its","you","your","i","we","they","he","she","them","his","her","our","us","do","does","did","done","not","no","yes","can","could","should","would","may","might","into","about","over","under","between"]);function ne(e){return e.toLowerCase().replace(/[`*_#>~=\[\]{}()!?.:,;'"<>|/\\+-]+/g," ").split(/\s+/).filter(e=>e&&!te.has(e))}function se(e){const t=new Map,n=[],s=[];let i=0;for(const o of e){const e=ne(o);s.push(e.length);const r=new Map;for(const n of e){let e=t.get(n);void 0===e&&(e=i++,t.set(n,e)),r.set(e,(r.get(e)||0)+1)}n.push(r)}const o=e.length,r=Array(i).fill(0);for(const e of n)for(const t of e.keys())r[t]+=1;return{stats:{vocab:t,idf:r.map(e=>Math.log((o+1)/(e+1))+1),avgLen:s.reduce((e,t)=>e+t,0)/Math.max(1,o),df:r},tf:n,docLens:s}}function ie(e,t){const n=new Map;let s=0;for(const[i,o]of e){const e=o*(t[i]||0);n.set(i,e),s+=e*e}const i=Math.sqrt(s)||1e-12;for(const[e,t]of n)n.set(e,t/i);return n}function oe(e,t){const[n,s]=e.size<t.size?[e,t]:[t,e];let i=0;for(const[e,t]of n){const n=s.get(e);void 0!==n&&(i+=t*n)}return i}function re(e,t,n=1337){const s=new Float64Array(t);for(const[n,i]of e){let e=2654435761*n>>>0;for(let n=0;n<t;n++){e^=e<<13,e^=e>>>17,e^=e<<5;const t=(e>>>0)/4294967296*2-1;s[n]+=i*t}}let i=0;for(let e=0;e<t;e++)i+=s[e]*s[e];const o=Math.sqrt(i)||1e-12;for(let e=0;e<t;e++)s[e]/=o;return s}function ae(e){return/```+\s*go([\s\S]*?)```/i.test(e)||/\bfunc\s+\w+\s*\(.*\)\s*\w*\s*{/.test(e)}function ce(e){return/```+/.test(e)||/{[^}]*}/.test(e)}function le(e,t){const n=(s=ne(e),Array.from(new Set(s)));var s;const i=new Set(ne(t));if(0===n.length||0===i.size)return 0;let o=0;for(const e of n)i.has(e)&&o++;return o/n.length}function he(e,t,n,s,i,o,r,a,c,l){var h;const d=[],u=[],f=oe(n,s);d.push(f),u.push("cosine_tfidf");const g=function(e,t,n,s,i=1.5,o=.75){let r=0;for(const[a]of e){const e=t.get(a)||0;e<=0||(r+=Math.log(((n.df[a]||0)+.5)/(n.idf.length-(n.df[a]||0)+.5)+1)*(e*(i+1)/(e+i*(1-o+o*(s/(n.avgLen||1)))||1e-12)))}return r}(i,o,r,a);d.push(g),u.push("bm25");const m=le(t.heading||"",e);d.push(m),u.push("heading_match_frac");const p=function(e,t){const n=new Set(ne(e)),s=new Set(ne(t));let i=0;for(const e of n)s.has(e)&&i++;const o=n.size+s.size-i;return 0===o?0:i/o}(e,t.content||"");d.push(p),u.push("jaccard_tokens");const y=ae(t.rich||t.content||""),w=ce(t.rich||t.content||"");var b;d.push(y?1:0),u.push("flag_go_code"),d.push(w?1:0),u.push("flag_any_code"),d.push((b=t.content||"",!/(golang\.org|go\.dev|pkg\.go\.dev)/i.test(b)?0:1)),u.push("flag_go_spec_link"),d.push(null!==(h=t.score_base)&&void 0!==h?h:0),u.push("prior_score_base");const v=(t.content||"").length;if(d.push(1/Math.sqrt(1+v)),u.push("len_inv_sqrt"),c&&l){let e=0,t=0;for(let n=0;n<c.length;n++)e+=c[n]*l[n],t+=Math.abs(c[n]-l[n]);d.push(e),u.push("proj_dot"),d.push(t/c.length),u.push("proj_l1mean")}return{names:u,values:d}}class de{constructor(){this.w=null,this.mu=null,this.sigma=null}fit(e,t,n=.01){var s;const i=e.length,o=(null===(s=e[0])||void 0===s?void 0:s.length)||0;if(0===i||0===o)return void(this.w=new Float64Array(o));const r=new Float64Array(o),a=new Float64Array(o);for(let t=0;t<o;t++){let n=0;for(let s=0;s<i;s++)n+=e[s][t];n/=i,r[t]=n;let s=0;for(let o=0;o<i;o++){const i=e[o][t]-n;s+=i*i}a[t]=Math.sqrt(s/i)||1}const c=Array.from({length:i},(e,t)=>new Float64Array(o));for(let t=0;t<i;t++)for(let n=0;n<o;n++)c[t][n]=(e[t][n]-r[n])/a[n];const l=Array.from({length:o},()=>new Float64Array(o)),h=new Float64Array(o);for(let e=0;e<i;e++){const n=c[e],s=t[e];for(let e=0;e<o;e++){h[e]+=n[e]*s;const t=n[e];for(let s=0;s<=e;s++)l[e][s]+=t*n[s]}}for(let e=0;e<o;e++){for(let t=0;t<e;t++)l[t][e]=l[e][t];l[e][e]+=n}const d=Array.from({length:o},()=>new Float64Array(o));for(let e=0;e<o;e++)for(let t=0;t<=e;t++){let n=l[e][t];for(let s=0;s<t;s++)n-=d[e][s]*d[t][s];d[e][t]=e===t?Math.sqrt(Math.max(n,1e-12)):n/(d[t][t]||1e-12)}const u=new Float64Array(o);for(let e=0;e<o;e++){let t=h[e];for(let n=0;n<e;n++)t-=d[e][n]*u[n];u[e]=t/(d[e][e]||1e-12)}const f=new Float64Array(o);for(let e=o-1;e>=0;e--){let t=u[e];for(let n=e+1;n<o;n++)t-=d[n][e]*f[n];f[e]=t/(d[e][e]||1e-12)}this.w=f,this.mu=r,this.sigma=a}predict(e){if(!this.w||!this.mu||!this.sigma)return 0;let t=0;for(let n=0;n<this.w.length;n++){const s=(e[n]-this.mu[n])/this.sigma[n];t+=this.w[n]*s}return t}}function ue(e,t,n){var s;const i=t.rich||t.content||"";let o=0;/\bgo\b/.test(e.toLowerCase())&&/(define|declare|function|func)/i.test(e)&&ae(i)&&(o=Math.max(o,1));le(t.heading||"",e)>=.34&&ce(i)&&(o=Math.max(o,.8));const r=n.names.indexOf("cosine_tfidf"),a=n.names.indexOf("bm25"),c=r>=0?n.values[r]:0,l=a>=0?n.values[a]:0;c>.25&&(o=Math.max(o,.6)),l>1&&(o=Math.max(o,.6));const h=n.names.indexOf("prior_score_base"),d=h>=0?n.values[h]:0;return(null!==(s=t.score_base)&&void 0!==s?s:0)>0&&(o=Math.max(o,Math.min(.6,.2+.5*d))),o}function fe(e,t,n={}){var s,i;const{lambdaRidge:o=.01,randomProjDim:r=32,exposeFeatures:a=!0,attachFeatureNames:c=!1}=n,l=[e,...t.map(e=>e.content||"")],{stats:h,tf:d,docLens:u}=se(l),f=d.map(e=>ie(e,h.idf)),g=d[0],m=f[0],p=r>0?re(m,r):void 0,y=[],w=[],b=[];for(let n=0;n<t.length;n++){const s=t[n],i=d[n+1],o=f[n+1],a=r>0?re(o,r,1337+n):void 0,c=he(e,s,m,o,g,i,h,u[n+1]||1,p,a);b.push(c),y.push(c.values);const l=ue(e,s,c);w.push(l)}if(w.every(e=>Math.abs(e-w[0])<1e-9)){const e=b[0].names.indexOf("cosine_tfidf");if(e>=0)for(let t=0;t<w.length;t++)w[t]=Math.max(0,Math.min(1,.2+.6*y[t][e]))}const v=new de;v.fit(y,w,o);let S=1/0,C=-1/0;const M=y.map(e=>v.predict(e));for(const e of M)e<S&&(S=e),e>C&&(C=e);const A=Math.max(1e-9,C-S),k=c?null!==(i=null===(s=b[0])||void 0===s?void 0:s.names)&&void 0!==i?i:[]:void 0,E=t.map((e,t)=>{const n=(M[t]-S)/A,s=function(e){if(e>=0)return 1/(1+Math.exp(-e));{const t=Math.exp(e);return t/(1+t)}}((M[t]-.5*(S+C))/(.2*A+1e-6)),i=Object.assign(Object.assign({},e),{score_rr:n,p_relevant:s});return a&&(i._features=y[t]),k&&(i._feature_names=k),i});return E.sort((e,t)=>t.score_rr-e.score_rr),E}function ge(e,t={}){const{probThresh:n=.45,epsilonTop:s=.05,useMMR:i=!0,mmrLambda:o=.7,budgetChars:r=1200}=t;if(0===e.length)return[];const a=e[0].score_rr,c=e.filter(e=>e.p_relevant>=n&&e.score_rr>=a-s),l=c.length>0?c:[e[0]];if(!i){const e=[];let t=0;for(const n of l){const s=(n.content||"").length;if(t+s>r&&e.length>0)break;e.push(n),t+=s}return e}return function(e,t=.7,n=1200){const s=[],i=e.map(e=>e.content||""),{stats:o,tf:r}=se(i),a=r.map(e=>ie(e,o.idf)),c=new Set;let l=0;for(;c.size<e.length;){let i=-1,o=-1/0;for(let n=0;n<e.length;n++){if(c.has(n))continue;const s=e[n];let r=0;for(const e of c){const t=oe(a[n],a[e]);t>r&&(r=t)}const l=t*s.score_rr-(1-t)*r;l>o&&(o=l,i=n)}if(i<0)break;const r=e[i],h=(r.content||"").length;if(l+h>n&&s.length>0)break;s.push(r),l+=h,c.add(i)}return s}(e.map(e=>Object.assign(Object.assign({},e),{score_rr:l.includes(e)?e.score_rr+.01:e.score_rr})),o,r)}class me{constructor(e){this.modelState=null,this.model=null,this.config={reranking:{enabled:e?.reranking?.enabled??!0,lambdaRidge:e?.reranking?.lambdaRidge??.1,useMMR:e?.reranking?.useMMR??!0,mmrLambda:e?.reranking?.mmrLambda??.5,probThresh:e?.reranking?.probThresh??.1},topK:e?.topK??5,verbose:e?.verbose??!1}}async loadModel(e){const t=performance.now();if(this.model=e,this.modelState=function(e){if("astermind-pro-v1"!==e.version&&"astermind-elm-v1"!==e.version)throw new Error(`Unsupported model version: ${e.version}. Expected 'astermind-pro-v1' or 'astermind-elm-v1'`);const t=JSON.parse(JSON.stringify(e.settings||{})),n=new Map(e.vocab),s=Float64Array.from(e.idf),i=e.chunks.map(e=>({heading:e.heading,content:e.content||"",rich:e.rich,level:e.level,secId:e.secId})),o=e.tfidfDocs.map(e=>{const t=new Map;for(const[n,s]of e)t.set(n,s);return t}),r=Array.from(e.landmarksIdx),a=e.landmarkMat.map(e=>Float64Array.from(e));let c;if(!e.denseDocs||e.denseDocs.length!==o.length)throw new Error("recomputeDense=true but buildDense function not provided");return c=e.denseDocs.map(e=>Float64Array.from(e)),{settings:t,vocabMap:n,idf:s,chunks:i,tfidfDocs:o,landmarksIdx:r,landmarkMat:a,denseDocs:c}}(e),this.config.verbose){const e=performance.now()-t;console.log(`[OmegaOfflineRAG] Model loaded in ${e.toFixed(0)}ms`),console.log(`[OmegaOfflineRAG] ${this.modelState.chunks.length} chunks, ${this.modelState.vocabMap.size} vocab`)}}async loadModelFromUrl(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch model from ${e}: ${t.status}`);const n=await t.json();await this.loadModel(n)}isReady(){return null!==this.modelState}getModelInfo(){return this.model&&this.modelState?{version:this.model.version,savedAt:this.model.savedAt,documentCount:this.modelState.chunks.length,vocabularySize:this.modelState.vocabMap.size,landmarkCount:this.modelState.landmarksIdx.length,hasDenseVectors:this.modelState.denseDocs.length>0,settings:this.model.settings}:null}async ask(e){const t=performance.now();if(!this.modelState||!this.model)return{answer:"Omega model not loaded. Please load a model first.",confidence:"none",sources:[],processingTime:0,degraded:!0,degradedReason:"Model not loaded"};try{const n=this.model.settings,s=n.kernel??"rbf",i=n.sigma??1,o=n.alpha??.5,r=n.beta??.3,a=n.ridge??.001,c=n.headingW??.2,l=n.useStem??!0,h=n.expandQuery??!1,d=n.prefilter??100,u=ee({query:e,chunks:this.modelState.chunks,vocabMap:this.modelState.vocabMap,idf:this.modelState.idf,tfidfDocs:this.modelState.tfidfDocs,denseDocs:this.modelState.denseDocs,landmarksIdx:this.modelState.landmarksIdx,landmarkMat:this.modelState.landmarkMat,vocabSize:this.modelState.vocabMap.size,kernel:s,sigma:i,alpha:o,beta:r,ridge:a,headingW:c,useStem:l,expandQuery:h,topK:2*this.config.topK,prefilter:d});let f;if(this.config.reranking.enabled&&u.items.length>0){const t=function(e,t,n={}){return ge(fe(e,t,n),n)}(e,u.items.map((e,t)=>({heading:e.heading,content:e.content,rich:e.rich,score_base:u.scores[t]})),{lambdaRidge:this.config.reranking.lambdaRidge,useMMR:this.config.reranking.useMMR,mmrLambda:this.config.reranking.mmrLambda,probThresh:this.config.reranking.probThresh});f=t.slice(0,this.config.topK).map(e=>({heading:e.heading,content:e.content,rich:e.rich,score:e.score_base??0,rerankScore:e.score_rr,probability:e.p_relevant}))}else f=u.items.slice(0,this.config.topK).map((e,t)=>({heading:e.heading,content:e.content,rich:e.rich,score:u.scores[t]}));const g=await V(e,f.map(e=>({heading:e.heading,content:e.content,score:e.score}))),m=performance.now()-t,p=f[0]?.score??0,y=this.determineConfidence(p,f.length);return{answer:g,confidence:y,sources:f,processingTime:m,degraded:!1,queryClassification:this.classifyQuery(e)}}catch(e){const n=performance.now()-t;return console.error("[OmegaOfflineRAG] Error during retrieval:",e),{answer:"An error occurred while processing your question offline.",confidence:"none",sources:[],processingTime:n,degraded:!0,degradedReason:e instanceof Error?e.message:"Unknown error"}}}async retrieve(e,t){if(!this.modelState||!this.model)return[];const n=t??this.config.topK,s=this.model.settings,i=s.kernel??"rbf",o=s.sigma??1,r=s.alpha??.5,a=s.beta??.3,c=s.ridge??.001,l=s.headingW??.2,h=s.useStem??!0,d=s.expandQuery??!1,u=s.prefilter??100,f=ee({query:e,chunks:this.modelState.chunks,vocabMap:this.modelState.vocabMap,idf:this.modelState.idf,tfidfDocs:this.modelState.tfidfDocs,denseDocs:this.modelState.denseDocs,landmarksIdx:this.modelState.landmarksIdx,landmarkMat:this.modelState.landmarkMat,vocabSize:this.modelState.vocabMap.size,kernel:i,sigma:o,alpha:r,beta:a,ridge:c,headingW:l,useStem:h,expandQuery:d,topK:n,prefilter:u});return f.items.map((e,t)=>({heading:e.heading,content:e.content,rich:e.rich,score:f.scores[t]}))}classifyQuery(e){const t=e.toLowerCase(),n=t.split(/\s+/),s=["what","who","when","where","which","is","are","was","were"],i=["how","steps","guide","tutorial","process","procedure"],o=["why","explain","describe","meaning","definition","concept"],r=["go to","navigate","find","page","link","take me","show me"];let a="unknown",c=.5;const l=[];for(const e of r)if(t.includes(e)){a="navigational",c=.8,l.push(e);break}if("unknown"===a){const e=n[0];i.includes(e)||i.some(e=>t.includes(e))?(a="procedural",c=.7,l.push(...i.filter(e=>t.includes(e)))):o.includes(e)||o.some(e=>t.includes(e))?(a="conceptual",c=.7,l.push(...o.filter(e=>t.includes(e)))):s.includes(e)&&(a="factual",c=.7,l.push(e))}return{type:a,confidence:c,keywords:l}}determineConfidence(e,t){return 0===t?"none":e>=.7||e>=.4?"medium":"low"}clear(){this.modelState=null,this.model=null}}var pe=Object.freeze({__proto__:null,OmegaOfflineRAG:me});e.ApiClient=n,e.CyberneticAgent=U,e.CyberneticCache=v,e.CyberneticClient=_,e.CyberneticIntentClassifier=O,e.CyberneticLocalRAG=S,e.CyberneticOfflineStorage=C,e.LicenseManager=L,e.OmegaOfflineRAG=me,e.REQUIRED_FEATURES=R,e.createClient=function(e){return new _(e)},e.createLicenseManager=async function(e){const t=new L(e);return await t.verify(),t},e.detectEnvironment=I,e.getEnforcementMode=D,e.getTokenExpiration=function(e){const t=k(e);return t&&"number"==typeof t.payload.exp?new Date(1e3*t.payload.exp):null},e.isValidJWTFormat=function(e){return null!==k(e)},e.loadConfig=function(e={}){const{throwOnMissingKey:t=!0}=e,n=function(){if("undefined"==typeof process||!process.env)return null;const e=process.env.ASTERMIND_RAG_API_KEY,t=process.env.ASTERMIND_RAG_API_SERVER_URL;if(e)return{apiKey:e,apiUrl:t||$,_source:"env"};const n=process.env.REACT_APP_ASTERMIND_RAG_API_KEY,s=process.env.REACT_APP_ASTERMIND_RAG_API_SERVER_URL;return n?{apiKey:n,apiUrl:s||$,_source:"env"}:null}();if(n)return n;const s=function(){if("undefined"!=typeof window){const e=window.__ASTERMIND_CONFIG__;if(e&&"object"==typeof e&&e.apiKey)return{...e,apiUrl:e.apiUrl||$,_source:"vite"}}try{const e=globalThis.import?.meta?.env;if(e){const t=e.VITE_ASTERMIND_RAG_API_KEY,n=e.VITE_ASTERMIND_RAG_API_SERVER_URL;if(t)return{apiKey:t,apiUrl:n||$,_source:"vite"}}}catch{}return null}();if(s)return s;const i=function(){if("undefined"==typeof window)return null;const e=window.astermindConfig;return e&&"object"==typeof e&&e.apiKey?{...e,apiUrl:e.apiUrl||$,_source:"window"}:null}();if(i)return T(i),i;const o=function(){if("undefined"==typeof window||"undefined"==typeof document)return null;const e=document.querySelector("script[data-astermind-key]");if(e){const t=e.getAttribute("data-astermind-key");if(t)return{apiKey:t,apiUrl:e.getAttribute("data-astermind-url")||$,_source:"data-attr"}}return null}();if(o)return o;if(t)throw new Error('AsterMind API key is required. Configure using one of these methods:\n 1. Set VITE_ASTERMIND_RAG_API_KEY environment variable (Vite)\n 2. Set REACT_APP_ASTERMIND_RAG_API_KEY environment variable (CRA)\n 3. Set window.astermindConfig = { apiKey: "am_...", apiUrl: "..." }\n 4. Add data-astermind-key attribute to your script tag\n 5. Pass apiKey directly to createClient() or CyberneticClient constructor');return console.warn("[AsterMind] No API key found. Chatbot will not function until configured."),null},e.registerAgenticCapabilities=function(e){const t={agent:U,intentClassifier:O};e.registerAgentic(t)},e.validateConfig=T,e.verifyLicenseToken=x});
2
2
  //# sourceMappingURL=cybernetic-chatbot-client-full.min.js.map