@intelliweave/embedded 1.6.53 → 1.6.54

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.
@@ -6,7 +6,7 @@ import{v4 as ne}from"uuid";function q(d){let s=(d||"").split(`
6
6
  `);for(let l of c){n=l.indexOf(": ");let a=l.slice(0,n),h=l.slice(n+2);n==-1&&(a=l,h=""),a&&(r[a]!==void 0?r[a]+=`
7
7
  `+h:r[a]=h)}yield r}},t=new TextDecoder,i=d.getReader();for(;;){let{done:n,value:o}=await i.read();if(n)break;s+=t.decode(o,{stream:!0}),yield*e()}s+=t.decode()+`
8
8
 
9
- `,yield*e()}function ae(){if(p().userID)return p().userID;if(typeof localStorage<"u"){let d=localStorage.getItem("intelliweave.uid")||"";return d||(d=ne(),localStorage.setItem("intelliweave.uid",d),d)}else return ne()}var T=class T{constructor(s){this.module="IntelliWeave";this.module=s}get debugEnabled(){return T.debug?!0:typeof window<"u"&&p().debug}log(...s){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...s)}debug(...s){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...s)}info(...s){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...s)}warn(...s){console.warn(`[IntelliWeave > ${this.module}]`,...s)}error(...s){console.error(`[IntelliWeave > ${this.module}]`,...s)}timer(s,...e){let t=Date.now();return this.debug(`[${s} 0ms] Started`,...e),(...i)=>this.debug(`[${s} ${Math.floor(Date.now()-t)}ms]`,...i)}};T.debug=!1;var u=T;var y=new u("ChatGPT"),L=class{constructor(s){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...s}}async sendMessage(s){this.messages.push({role:"user",content:s}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let e=this.messages[this.messages.length-1];return e?.role=="assistant"&&e.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),y.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let s=this.messages[this.messages.length-1];if(s?.role=="user"||s?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(s?.role=="assistant"&&s?.tool_calls?.length){for(let e of s.tool_calls)await this.processToolCall(e);await this.processMessages()}}async trimMessages(){for(;;){let s=await this.sendToAPI(!0);if(JSON.stringify(s).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){y.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(s){let e=0;for(let c=this.messages.length-1;c>=0;c--)if(this.messages[c].role=="assistant"&&this.messages[c].tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[c].role=="user")break;y.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let c of this.tools){c.description&&c.description.length>1024&&y.warn(`Tool description for "${c.name}" is too long, it will be truncated.`);let l={type:"function",function:{name:c.name,description:(c.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(c.params))for(let a of c.params)l.function.parameters.properties[a.name]={type:a.type,description:a.description};else if(c.params){let a=c.params;for(let h in a)l.function.parameters.properties[h]={type:"string",description:a[h]}}t.tools.push(l)}t.user||delete t.user,t.tools.length||delete t.tools;let i={};if(i["Content-Type"]="application/json",this.config.apiKey&&(i.Authorization=`Bearer ${this.config.apiKey}`),s)return t;let n=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(t)});if(!n.ok){let c=`${n.status} ${n.statusText}`;try{let a=await n.json();c=a.errorText||a.error?.message||a.error||c}catch{}let l=new Error(c);throw l.code=n.status,l}let o=null,r=null;if(this.config.stream)for await(let c of oe(n.body)){if(c.data=="[DONE]")break;if(!c.data)continue;let l=JSON.parse(c.data);if(r){for(let a in l.choices[0].delta)if(typeof l.choices[0].delta[a]=="string"){if(a=="role"&&r[a]==l.choices[0].delta[a])continue;r[a]=(r[a]||"")+l.choices[0].delta[a]}for(let a of l.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[a.index]){r.tool_calls[a.index]=a;continue}let h=r.tool_calls[a.index];h.function=h.function||{},h.function.name=(h.function.name||"")+(a.function?.name||""),h.function.arguments=(h.function.arguments||"")+(a.function?.arguments||"")}}else r={chunkID:l.id,...l.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}else o=await n.json(),this.stats.tokensUsed+=o.usage?.total_tokens||0,y.debug(`Used ${o.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),r=o.choices?.[0]?.message;if(r||(y.warn("No response block in API response."),r={role:"assistant",content:""}),r.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(r),this.messages.push(r),r.content&&this.config.onAIMessage?.(r.content,!1)}processIncomingMessage(s){}registerTool(s){this.tools.push(s)}async processToolCall(s){try{let e=this.tools.find(n=>n.name==s.function.name);if(!e)throw new Error(`Tool "${s.function.name}" not found.`);let t=JSON.parse(s.function.arguments);this.config.onAIToolStart?.(s.function.name,t);let i=await e.callback(t);if(typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){y.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(n=>n.role!="assistant"||!n.tool_calls?.find(o=>o.id==s.id));return}else e.removeFromMessageHistory&&y.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${e.name}"`);this.messages.push({role:"tool",content:i,tool_call_id:s.id})}catch(e){y.warn(`Unable to process tool call for "${s?.function?.name}"`,e),this.messages.push({role:"tool",content:`Error: ${e.message}`,tool_call_id:s.id})}}resetConversation(){this.messages=[]}};import{v4 as de}from"uuid";import ve from"minisearch";var re=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(d,s)=>{let e=await s.knowledgeBase.search(d.query),t=s;t._lastKBsearch=d.query,t._nextRequestUseKBitems=e,s.submitAnalyticsEvent({type:"kb-search",query:d.query,results:e});let i=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${n}.`}}];var x=new u("KnowledgeBase"),le=1,k=class d{constructor(s){this._sources=[{id:"core.internal",query:async()=>re}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=s}registerSource(s,e){let t=s;return typeof s=="function"&&(e=s,t=`source.${le++}`),this._sources.push({id:t,query:e}),t}removeSource(s){this._sources=this.sources.filter(e=>e.id!==s&&e.query!==s)}addEntry(s){this.manualEntries.push(s)}removeEntry(s){this.manualEntries=this.manualEntries.filter(e=>e.id!==s)}get sources(){let s=this._sources;return typeof window<"u"&&p().knowledgeBaseSources&&(s=s.concat(p().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),s=s.concat(this._windowSources),s=s.filter(e=>!e.disabled),s}async search(s){x.debug(`Searching knowledge base for: ${s}`);let e=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});e.query=s,e.entries=[],e.sources=[],typeof document<"u"&&document.dispatchEvent(e),this._windowSources=e.sources;let i=(await Promise.all(this.sources.map(async c=>{try{let l=Date.now(),a=await c.query(s);return x.debug(`Source '${c.id}' took ${Date.now()-l}ms`),a||[]}catch(l){return x.warn(`Knowledge source '${c.id}' failed:`,l),[]}}))).flat();i=i.concat(e.entries),i=i.concat(this.manualEntries),p().knowledgeBase&&(i=i.concat(p().knowledgeBase)),i=i.filter(c=>c&&!c.disabled);for(let c=0;c<i.length;c++){let l=i[c];if(l.id=l.id||`temp.${c}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!l.action&&l.type=="tour"&&(l.action=a=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=a=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),l.parameters&&!Array.isArray(l.parameters)){let a=l.parameters,h=[];for(let w in a)h.push({name:w,type:"string",description:l.parameters[w]});l.parameters=h}}let n=new ve({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});n.addAll(i);let r=n.search(s).map(c=>i.find(l=>l.id==c.id));for(let c of i)c.isContext&&(r.find(l=>l.id===c.id)||r.push(c));return this.lastResults=r,x.debug("Found results:",r),r}getCachedEntry(s){return this.lastResults.find(e=>e.id==s||e._functionID==s)}registerSourceFromURL(s,e){e||(e=`external.${le++}`),x.debug(`Registering remote knowledge base source: ${s}`);let t=[],i=[],n=!0,o=async(c,l)=>{x.debug(`Calling remote knowledge base action: ${c.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:c.id,parameters:l},h=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!h.ok)throw new Error(`HTTP Error ${h.status} ${h.statusText}`);let w=await h.json();return r(w.updateItems||[]),w.response},r=c=>{for(let l of c){if(!l.id){x.warn("KB item skipped since it has no ID.",l);continue}let a=t.find(h=>h.id==l.id);if(a){a.name=l.name||a.name||"",a.content=l.content||a.content||"",a.disabled=l.disabled??a.disabled,a.isContext=l.isContext??a.isContext,a.parameters=l.parameters||a.parameters||[],a.tags=l.tags||a.tags,a.type=l.type||a.type;continue}t.push({...l,action:h=>o(l,h)})}};this.registerSource(e,async c=>{if(n&&i.includes(c))return t;let l={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:c},a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let h=await a.json();return n=!h.noCache,i.includes(c)||i.push(c),r(h.items),t})}clone(){let s=new d(this.ai);return s._sources=this._sources,s._windowSources=this._windowSources,s.manualEntries=this.manualEntries,s}};var ce={name:"@intelliweave/embedded",version:"1.6.53",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var B=class{constructor(s){this.ai=s}async boolean(s,e){let t=this.ai.clone();t.resetConversation(),t.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let i=await t.sendMessage(s+`
9
+ `,yield*e()}function ae(){if(p().userID)return p().userID;if(typeof localStorage<"u"){let d=localStorage.getItem("intelliweave.uid")||"";return d||(d=ne(),localStorage.setItem("intelliweave.uid",d),d)}else return ne()}var T=class T{constructor(s){this.module="IntelliWeave";this.module=s}get debugEnabled(){return T.debug?!0:typeof window<"u"&&p().debug}log(...s){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...s)}debug(...s){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...s)}info(...s){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...s)}warn(...s){console.warn(`[IntelliWeave > ${this.module}]`,...s)}error(...s){console.error(`[IntelliWeave > ${this.module}]`,...s)}timer(s,...e){let t=Date.now();return this.debug(`[${s} 0ms] Started`,...e),(...i)=>this.debug(`[${s} ${Math.floor(Date.now()-t)}ms]`,...i)}};T.debug=!1;var u=T;var y=new u("ChatGPT"),L=class{constructor(s){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...s}}async sendMessage(s){this.messages.push({role:"user",content:s}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let e=this.messages[this.messages.length-1];return e?.role=="assistant"&&e.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),y.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let s=this.messages[this.messages.length-1];if(s?.role=="user"||s?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(s?.role=="assistant"&&s?.tool_calls?.length){for(let e of s.tool_calls)await this.processToolCall(e);await this.processMessages()}}async trimMessages(){for(;;){let s=await this.sendToAPI(!0);if(JSON.stringify(s).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){y.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(s){let e=0;for(let c=this.messages.length-1;c>=0;c--)if(this.messages[c].role=="assistant"&&this.messages[c].tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[c].role=="user")break;y.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let c of this.tools){c.description&&c.description.length>1024&&y.warn(`Tool description for "${c.name}" is too long, it will be truncated.`);let l={type:"function",function:{name:c.name,description:(c.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(c.params))for(let a of c.params)l.function.parameters.properties[a.name]={type:a.type,description:a.description};else if(c.params){let a=c.params;for(let h in a)l.function.parameters.properties[h]={type:"string",description:a[h]}}t.tools.push(l)}t.user||delete t.user,t.tools.length||delete t.tools;let i={};if(i["Content-Type"]="application/json",this.config.apiKey&&(i.Authorization=`Bearer ${this.config.apiKey}`),s)return t;let n=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(t)});if(!n.ok){let c=`${n.status} ${n.statusText}`;try{let a=await n.json();c=a.errorText||a.error?.message||a.error||c}catch{}let l=new Error(c);throw l.code=n.status,l}let o=null,r=null;if(this.config.stream)for await(let c of oe(n.body)){if(c.data=="[DONE]")break;if(!c.data)continue;let l=JSON.parse(c.data);if(r){for(let a in l.choices[0].delta)if(typeof l.choices[0].delta[a]=="string"){if(a=="role"&&r[a]==l.choices[0].delta[a])continue;r[a]=(r[a]||"")+l.choices[0].delta[a]}for(let a of l.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[a.index]){r.tool_calls[a.index]=a;continue}let h=r.tool_calls[a.index];h.function=h.function||{},h.function.name=(h.function.name||"")+(a.function?.name||""),h.function.arguments=(h.function.arguments||"")+(a.function?.arguments||"")}}else r={chunkID:l.id,...l.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}else o=await n.json(),this.stats.tokensUsed+=o.usage?.total_tokens||0,y.debug(`Used ${o.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),r=o.choices?.[0]?.message;if(r||(y.warn("No response block in API response."),r={role:"assistant",content:""}),r.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(r),this.messages.push(r),r.content&&this.config.onAIMessage?.(r.content,!1)}processIncomingMessage(s){}registerTool(s){this.tools.push(s)}async processToolCall(s){try{let e=this.tools.find(n=>n.name==s.function.name);if(!e)throw new Error(`Tool "${s.function.name}" not found.`);let t=JSON.parse(s.function.arguments);this.config.onAIToolStart?.(s.function.name,t);let i=await e.callback(t);if(typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){y.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(n=>n.role!="assistant"||!n.tool_calls?.find(o=>o.id==s.id));return}else e.removeFromMessageHistory&&y.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${e.name}"`);this.messages.push({role:"tool",content:i,tool_call_id:s.id})}catch(e){y.warn(`Unable to process tool call for "${s?.function?.name}"`,e),this.messages.push({role:"tool",content:`Error: ${e.message}`,tool_call_id:s.id})}}resetConversation(){this.messages=[]}};import{v4 as de}from"uuid";import ve from"minisearch";var re=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(d,s)=>{let e=await s.knowledgeBase.search(d.query),t=s;t._lastKBsearch=d.query,t._nextRequestUseKBitems=e,s.submitAnalyticsEvent({type:"kb-search",query:d.query,results:e});let i=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${n}.`}}];var x=new u("KnowledgeBase"),le=1,k=class d{constructor(s){this._sources=[{id:"core.internal",query:async()=>re}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=s}registerSource(s,e){let t=s;return typeof s=="function"&&(e=s,t=`source.${le++}`),this._sources.push({id:t,query:e}),t}removeSource(s){this._sources=this.sources.filter(e=>e.id!==s&&e.query!==s)}addEntry(s){this.manualEntries.push(s)}removeEntry(s){this.manualEntries=this.manualEntries.filter(e=>e.id!==s)}get sources(){let s=this._sources;return typeof window<"u"&&p().knowledgeBaseSources&&(s=s.concat(p().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),s=s.concat(this._windowSources),s=s.filter(e=>!e.disabled),s}async search(s){x.debug(`Searching knowledge base for: ${s}`);let e=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});e.query=s,e.entries=[],e.sources=[],typeof document<"u"&&document.dispatchEvent(e),this._windowSources=e.sources;let i=(await Promise.all(this.sources.map(async c=>{try{let l=Date.now(),a=await c.query(s);return x.debug(`Source '${c.id}' took ${Date.now()-l}ms`),a||[]}catch(l){return x.warn(`Knowledge source '${c.id}' failed:`,l),[]}}))).flat();i=i.concat(e.entries),i=i.concat(this.manualEntries),p().knowledgeBase&&(i=i.concat(p().knowledgeBase)),i=i.filter(c=>c&&!c.disabled);for(let c=0;c<i.length;c++){let l=i[c];if(l.id=l.id||`temp.${c}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!l.action&&l.type=="tour"&&(l.action=a=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=a=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),l.parameters&&!Array.isArray(l.parameters)){let a=l.parameters,h=[];for(let w in a)h.push({name:w,type:"string",description:l.parameters[w]});l.parameters=h}}let n=new ve({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});n.addAll(i);let r=n.search(s).map(c=>i.find(l=>l.id==c.id));for(let c of i)c.isContext&&(r.find(l=>l.id===c.id)||r.push(c));return this.lastResults=r,x.debug("Found results:",r),r}getCachedEntry(s){return this.lastResults.find(e=>e.id==s||e._functionID==s)}registerSourceFromURL(s,e){e||(e=`external.${le++}`),x.debug(`Registering remote knowledge base source: ${s}`);let t=[],i=[],n=!0,o=async(c,l)=>{x.debug(`Calling remote knowledge base action: ${c.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:c.id,parameters:l},h=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!h.ok)throw new Error(`HTTP Error ${h.status} ${h.statusText}`);let w=await h.json();return r(w.updateItems||[]),w.response},r=c=>{for(let l of c){if(!l.id){x.warn("KB item skipped since it has no ID.",l);continue}let a=t.find(h=>h.id==l.id);if(a){a.name=l.name||a.name||"",a.content=l.content||a.content||"",a.disabled=l.disabled??a.disabled,a.isContext=l.isContext??a.isContext,a.parameters=l.parameters||a.parameters||[],a.tags=l.tags||a.tags,a.type=l.type||a.type;continue}t.push({...l,action:h=>o(l,h)})}};this.registerSource(e,async c=>{if(n&&i.includes(c))return t;let l={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:c},a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let h=await a.json();return n=!h.noCache,i.includes(c)||i.push(c),r(h.items),t})}clone(){let s=new d(this.ai);return s._sources=this._sources,s._windowSources=this._windowSources,s.manualEntries=this.manualEntries,s}};var ce={name:"@intelliweave/embedded",version:"1.6.54",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var B=class{constructor(s){this.ai=s}async boolean(s,e){let t=this.ai.clone();t.resetConversation(),t.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let i=await t.sendMessage(s+`
10
10
 
11
11
  `+JSON.stringify(e))||"";if(i.toLowerCase().includes("true"))return!0;if(i.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+i)}async choose(s,e,t){t=t.map(o=>o.trim());let i=this.ai.clone();i.resetConversation(),i.getContextPrefix=async()=>"You will receive a question and some data and options. Answer the question by replying with the option you want to choose. Only say the option you want, no additional text.";let n=await i.sendMessage("question:"+s+`
12
12
 
@@ -257,25 +257,27 @@ You have access to a database of knowledge base items. These include "info" type
257
257
 
258
258
  #root {
259
259
  position: fixed;
260
- display: flex;
261
- flex-direction: column;
262
260
  width: 64px;
263
261
  height: 64px;
264
262
  z-index: 200000;
265
263
  background-color: #20262C;
266
- border-radius: 32px;
264
+ border-radius: 50%;
267
265
  box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
268
266
  transition: width 0.25s, height 0.25s, border-radius 0.25s;
269
267
  overflow: hidden;
270
268
  color: white;
271
269
  font-family: "Karla", sans-serif;
270
+ overlow: hidden;
272
271
  }
273
272
  #root.open {
274
273
  border-radius: 32px 32px 16px 16px;
274
+ display: flex;
275
+ flex-direction: column;
275
276
  width: 400px;
276
277
  height: 600px;
277
278
  max-width: calc(100vw - 40px);
278
279
  max-height: calc(max(50vh, 100vh - 320px));
280
+ overflow: visible;
279
281
  }
280
282
 
281
283
  #root #web-weaver-logo {
@@ -285,6 +287,7 @@ You have access to a database of knowledge base items. These include "info" type
285
287
  top: 0px;
286
288
  left: 0px;
287
289
  background-color: #21262c;
290
+ border-radius:50%;
288
291
  z-index:999;
289
292
  }
290
293
 
@@ -303,6 +306,8 @@ You have access to a database of knowledge base items. These include "info" type
303
306
  overflow: hidden;
304
307
  font-size: 9px;
305
308
  color: #abacad;
309
+ border-bottom-right-radius: 16px;
310
+ border-bottom-left-radius: 16px;
306
311
  }
307
312
 
308
313
  #root .green-accent {
Binary file
package/dist/node/node.js CHANGED
@@ -6,7 +6,7 @@ import{v4 as A}from"uuid";function k(c){let t=(c||"").split(`
6
6
  `);for(let o of r){a=o.indexOf(": ");let i=o.slice(0,a),h=o.slice(a+2);a==-1&&(i=o,h=""),i&&(u[i]!==void 0?u[i]+=`
7
7
  `+h:u[i]=h)}yield u}},s=new TextDecoder,n=c.getReader();for(;;){let{done:a,value:l}=await n.read();if(a)break;t+=s.decode(l,{stream:!0}),yield*e()}t+=s.decode()+`
8
8
 
9
- `,yield*e()}function D(){if(f().userID)return f().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=A(),localStorage.setItem("intelliweave.uid",c),c)}else return A()}var I=class I{constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return I.debug?!0:typeof window<"u"&&f().debug}log(...t){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...t)}debug(...t){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...t)}info(...t){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...t)}warn(...t){console.warn(`[IntelliWeave > ${this.module}]`,...t)}error(...t){console.error(`[IntelliWeave > ${this.module}]`,...t)}timer(t,...e){let s=Date.now();return this.debug(`[${t} 0ms] Started`,...e),(...n)=>this.debug(`[${t} ${Math.floor(Date.now()-s)}ms]`,...n)}};I.debug=!1;var g=I;var y=new g("ONNXModel"),_=class c{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,y.debug(`Model input parameters: ${t.inputNames.join(", ")}`),y.debug(`Model output parameters: ${t.outputNames.join(", ")}`)}static isSupported(){return!!c.lib}static async load(t){if(!c.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(y.debug("Loading ONNX runtime"),this.onnx=await c.lib()),y.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new c(e)}makeTensor(t,e,s=0){let n=1;for(let l of e)n*=l;let a;if(t=="float32")a=new c.onnx.Tensor(new Float32Array(n),e);else if(t=="int8")a=new c.onnx.Tensor(new Int8Array(n),e);else if(t=="int16")a=new c.onnx.Tensor(new Int16Array(n),e);else if(t=="int32")a=new c.onnx.Tensor(new Int32Array(n),e);else if(t=="int64")a=new c.onnx.Tensor(new BigInt64Array(n),e);else if(t=="uint8")a=new c.onnx.Tensor(new Uint8Array(n),e);else if(t=="uint16")a=new c.onnx.Tensor(new Uint16Array(n),e);else if(t=="uint32")a=new c.onnx.Tensor(new Uint32Array(n),e);else if(t=="uint64")a=new c.onnx.Tensor(new BigUint64Array(n),e);else throw new Error(`Invalid type: ${t}`);return s!==0&&(t=="int64"||t=="uint64")?a.data.fill(BigInt(s)):s!==0&&a.data.fill(s),a}registerConstant(t,e){if(!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);return this.constantTensors[t]=e,e}makeConstant(t,e,s,n=0){return this.registerConstant(t,this.makeTensor(e,s,n))}registerState(t,e,s){if(e||(e=t),!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[t]={outputName:e,tensor:s},s}makeState(t,e,s,n,a=0){return this.registerState(t,e,this.makeTensor(s,n,a))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return y.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)t[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)t[e]=this.constantTensors[e];try{let e=await this.session.run(t);for(let s in this.stateTensors){let n=e[this.stateTensors[s].outputName];this.stateTensors[s].tensor=n}return e}finally{this._runActive=!1}}resetState(){y.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};function V(c,t){let e=t.reduce((r,o)=>r+o.byteLength,0),s=new DataView(new ArrayBuffer(44));s.setUint8(0,82),s.setUint8(1,73),s.setUint8(2,70),s.setUint8(3,70),s.setUint32(4,44+e,!0),s.setUint8(8,87),s.setUint8(9,65),s.setUint8(10,86),s.setUint8(11,69);let n=1,a=32,l=n*a/8,u=c*l;return s.setUint8(12,102),s.setUint8(13,109),s.setUint8(14,116),s.setUint8(15,32),s.setUint32(16,16,!0),s.setUint16(20,3,!0),s.setUint16(22,n,!0),s.setUint32(24,c,!0),s.setUint32(28,u,!0),s.setUint16(32,l,!0),s.setUint16(34,a,!0),s.setUint8(36,100),s.setUint8(37,97),s.setUint8(38,116),s.setUint8(39,97),s.setUint32(40,e,!0),new File([s,...t],"audio.wav",{type:"audio/wav"})}var O=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var K=class{constructor(t,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!t)throw new Error(`Invalid array class: ${t}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=t,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((t,e)=>t+e.length,0)}feed(t){this.partialBuffers.push(t)}get canDrain(){return this.partialBuffers.reduce((e,s)=>e+s.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let t=this.ArrayClass,e=new t(this.outputBufferSize),s=0;for(;s!=e.length;){if(s>e.length)throw new Error(`Buffer overflow: ${s} > ${e.length}`);let n=e.length-s,a=this.partialBuffers[0],l=a.length-this.partialBufferOffset;l<n?(e.set(a.subarray(this.partialBufferOffset),s),s+=l,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(a.subarray(this.partialBufferOffset,this.partialBufferOffset+n),s),s+=n,this.partialBufferOffset+=n)}return e}pad(){let t=this.queuedSize%this.outputBufferSize;if(t==0)return;let e=this.ArrayClass,s=new e(t);this.feed(s)}};var W=class{constructor(t,e,s,n){if(!t||!e||!s)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=t,this.toSampleRate=e,this.channels=s||0,this.inputBufferSize=n,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=t=>t,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(t){try{return this.outputBuffer.subarray(0,t)}catch{try{return this.outputBuffer.length=t,this.outputBuffer}catch{return this.outputBuffer.slice(0,t)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=t=>{let e=t.length,s=this.channels,n,a,l,u,r,o,i,h,d;if(e%s!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(n=this.outputBufferSize,a=this.ratioWeight,l=this.lastWeight,u=0,r=0,o=0,i=0,h=this.outputBuffer;l<1;l+=a)for(r=l%1,u=1-r,this.lastWeight=l%1,d=0;d<this.channels;++d)h[i++]=this.lastOutput[d]*u+t[d]*r;for(l-=1,e-=s,o=Math.floor(l)*s;i<n&&o<e;){for(r=l%1,u=1-r,d=0;d<this.channels;++d)h[i++]=t[o+(d>0?d:0)]*u+t[o+(s+d)]*r;l+=a,o=Math.floor(l)*s}for(d=0;d<s;++d)this.lastOutput[d]=t[o++];return this.bufferSlice(i)}}multiTap(){this.resampler=t=>{let e=t.length,s,n,a=this.channels,l,u,r,o,i,h,d,v,x;if(e%a!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,n=[],l=this.ratioWeight,u=0,o=0,i=0,h=!this.tailExists,this.tailExists=!1,d=this.outputBuffer,v=0,x=0,r=0;r<a;++r)n[r]=0;do{if(h)for(u=l,r=0;r<a;++r)n[r]=0;else{for(u=this.lastWeight,r=0;r<a;++r)n[r]=this.lastOutput[r];h=!0}for(;u>0&&o<e;)if(i=1+o-x,u>=i){for(r=0;r<a;++r)n[r]+=t[o++]*i;x=o,u-=i}else{for(r=0;r<a;++r)n[r]+=t[o+(r>0?r:0)]*u;x+=u,u=0;break}if(u===0)for(r=0;r<a;++r)d[v++]=n[r]/l;else{for(this.lastWeight=u,r=0;r<a;++r)this.lastOutput[r]=n[r];this.tailExists=!0;break}}while(o<e&&v<s);return this.bufferSlice(v)}}resample(t){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(t)}};function te(c){let t=c.length,e=new Int16Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,c[t]));e[t]=s<0?s*32768:s*32767}return e}function se(c){let t=c.length,e=new BigInt64Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,c[t]));e[t]=BigInt(Math.floor(s<0?s*32768:s*32767))*0x100000000000n}return e}function ne(c){let t=c.length,e=new Float32Array(t);for(;t--;){let s=c[t];e[t]=s>=32768?-(65536-s)/32768:s/32767}return e}var p=new g("ChatGPT"),S=class{constructor(t){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...t}}async sendMessage(t){this.messages.push({role:"user",content:t}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let e=this.messages[this.messages.length-1];return e?.role=="assistant"&&e.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),p.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let t=this.messages[this.messages.length-1];if(t?.role=="user"||t?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(t?.role=="assistant"&&t?.tool_calls?.length){for(let e of t.tool_calls)await this.processToolCall(e);await this.processMessages()}}async trimMessages(){for(;;){let t=await this.sendToAPI(!0);if(JSON.stringify(t).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){p.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(t){let e=0;for(let r=this.messages.length-1;r>=0;r--)if(this.messages[r].role=="assistant"&&this.messages[r].tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[r].role=="user")break;p.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let s={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let r of this.tools){r.description&&r.description.length>1024&&p.warn(`Tool description for "${r.name}" is too long, it will be truncated.`);let o={type:"function",function:{name:r.name,description:(r.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(r.params))for(let i of r.params)o.function.parameters.properties[i.name]={type:i.type,description:i.description};else if(r.params){let i=r.params;for(let h in i)o.function.parameters.properties[h]={type:"string",description:i[h]}}s.tools.push(o)}s.user||delete s.user,s.tools.length||delete s.tools;let n={};if(n["Content-Type"]="application/json",this.config.apiKey&&(n.Authorization=`Bearer ${this.config.apiKey}`),t)return s;let a=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:n,body:JSON.stringify(s)});if(!a.ok){let r=`${a.status} ${a.statusText}`;try{let i=await a.json();r=i.errorText||i.error?.message||i.error||r}catch{}let o=new Error(r);throw o.code=a.status,o}let l=null,u=null;if(this.config.stream)for await(let r of P(a.body)){if(r.data=="[DONE]")break;if(!r.data)continue;let o=JSON.parse(r.data);if(u){for(let i in o.choices[0].delta)if(typeof o.choices[0].delta[i]=="string"){if(i=="role"&&u[i]==o.choices[0].delta[i])continue;u[i]=(u[i]||"")+o.choices[0].delta[i]}for(let i of o.choices[0].delta.tool_calls||[]){if(u.tool_calls||(u.tool_calls=[]),!u.tool_calls[i.index]){u.tool_calls[i.index]=i;continue}let h=u.tool_calls[i.index];h.function=h.function||{},h.function.name=(h.function.name||"")+(i.function?.name||""),h.function.arguments=(h.function.arguments||"")+(i.function?.arguments||"")}}else u={chunkID:o.id,...o.choices[0].delta};u?.content&&!u.content.startsWith("{")&&this.config.onAIMessage?.(u.content,!0)}else l=await a.json(),this.stats.tokensUsed+=l.usage?.total_tokens||0,p.debug(`Used ${l.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),u=l.choices?.[0]?.message;if(u||(p.warn("No response block in API response."),u={role:"assistant",content:""}),u.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(u),this.messages.push(u),u.content&&this.config.onAIMessage?.(u.content,!1)}processIncomingMessage(t){}registerTool(t){this.tools.push(t)}async processToolCall(t){try{let e=this.tools.find(a=>a.name==t.function.name);if(!e)throw new Error(`Tool "${t.function.name}" not found.`);let s=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,s);let n=await e.callback(s);if(typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){p.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(a=>a.role!="assistant"||!a.tool_calls?.find(l=>l.id==t.id));return}else e.removeFromMessageHistory&&p.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${e.name}"`);this.messages.push({role:"tool",content:n,tool_call_id:t.id})}catch(e){p.warn(`Unable to process tool call for "${t?.function?.name}"`,e),this.messages.push({role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id})}}resetConversation(){this.messages=[]}};import L from"minisearch";var $=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(c,t)=>{let e=await t.knowledgeBase.search(c.query),s=t;s._lastKBsearch=c.query,s._nextRequestUseKBitems=e,t.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let n=e.filter(l=>l.type!="action").map(l=>"id="+l.id).join(", ")||"(none)",a=e.filter(l=>l.type=="action").map(l=>"name="+l._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${a}.`}}];var m=new g("KnowledgeBase"),N=1,E=class c{constructor(t){this._sources=[{id:"core.internal",query:async()=>$}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${N++}`),this._sources.push({id:s,query:e}),s}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return typeof window<"u"&&f().knowledgeBaseSources&&(t=t.concat(f().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){m.debug(`Searching knowledge base for: ${t}`);let e=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});e.query=t,e.entries=[],e.sources=[],typeof document<"u"&&document.dispatchEvent(e),this._windowSources=e.sources;let n=(await Promise.all(this.sources.map(async r=>{try{let o=Date.now(),i=await r.query(t);return m.debug(`Source '${r.id}' took ${Date.now()-o}ms`),i||[]}catch(o){return m.warn(`Knowledge source '${r.id}' failed:`,o),[]}}))).flat();n=n.concat(e.entries),n=n.concat(this.manualEntries),f().knowledgeBase&&(n=n.concat(f().knowledgeBase)),n=n.filter(r=>r&&!r.disabled);for(let r=0;r<n.length;r++){let o=n[r];if(o.id=o.id||`temp.${r}`,o._functionID=o.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!o.action&&o.type=="tour"&&(o.action=i=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!o.action&&o.type=="info"&&(o.action=i=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),o.parameters&&!Array.isArray(o.parameters)){let i=o.parameters,h=[];for(let d in i)h.push({name:d,type:"string",description:o.parameters[d]});o.parameters=h}}let a=new L({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});a.addAll(n);let u=a.search(t).map(r=>n.find(o=>o.id==r.id));for(let r of n)r.isContext&&(u.find(o=>o.id===r.id)||u.push(r));return this.lastResults=u,m.debug("Found results:",u),u}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${N++}`),m.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],a=!0,l=async(r,o)=>{m.debug(`Calling remote knowledge base action: ${r.id}`);let i={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:r.id,parameters:o},h=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!h.ok)throw new Error(`HTTP Error ${h.status} ${h.statusText}`);let d=await h.json();return u(d.updateItems||[]),d.response},u=r=>{for(let o of r){if(!o.id){m.warn("KB item skipped since it has no ID.",o);continue}let i=s.find(h=>h.id==o.id);if(i){i.name=o.name||i.name||"",i.content=o.content||i.content||"",i.disabled=o.disabled??i.disabled,i.isContext=o.isContext??i.isContext,i.parameters=o.parameters||i.parameters||[],i.tags=o.tags||i.tags,i.type=o.type||i.type;continue}s.push({...o,action:h=>l(o,h)})}};this.registerSource(e,async r=>{if(a&&n.includes(r))return s;let o={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:r},i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let h=await i.json();return a=!h.noCache,n.includes(r)||n.push(r),u(h.items),s})}clone(){let t=new c(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}};import{v4 as R}from"uuid";var U={name:"@intelliweave/embedded",version:"1.6.53",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var T=class{constructor(t){this.ai=t}async boolean(t,e){let s=this.ai.clone();s.resetConversation(),s.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let n=await s.sendMessage(t+`
9
+ `,yield*e()}function D(){if(f().userID)return f().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=A(),localStorage.setItem("intelliweave.uid",c),c)}else return A()}var I=class I{constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return I.debug?!0:typeof window<"u"&&f().debug}log(...t){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...t)}debug(...t){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...t)}info(...t){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...t)}warn(...t){console.warn(`[IntelliWeave > ${this.module}]`,...t)}error(...t){console.error(`[IntelliWeave > ${this.module}]`,...t)}timer(t,...e){let s=Date.now();return this.debug(`[${t} 0ms] Started`,...e),(...n)=>this.debug(`[${t} ${Math.floor(Date.now()-s)}ms]`,...n)}};I.debug=!1;var g=I;var y=new g("ONNXModel"),_=class c{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,y.debug(`Model input parameters: ${t.inputNames.join(", ")}`),y.debug(`Model output parameters: ${t.outputNames.join(", ")}`)}static isSupported(){return!!c.lib}static async load(t){if(!c.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(y.debug("Loading ONNX runtime"),this.onnx=await c.lib()),y.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new c(e)}makeTensor(t,e,s=0){let n=1;for(let l of e)n*=l;let a;if(t=="float32")a=new c.onnx.Tensor(new Float32Array(n),e);else if(t=="int8")a=new c.onnx.Tensor(new Int8Array(n),e);else if(t=="int16")a=new c.onnx.Tensor(new Int16Array(n),e);else if(t=="int32")a=new c.onnx.Tensor(new Int32Array(n),e);else if(t=="int64")a=new c.onnx.Tensor(new BigInt64Array(n),e);else if(t=="uint8")a=new c.onnx.Tensor(new Uint8Array(n),e);else if(t=="uint16")a=new c.onnx.Tensor(new Uint16Array(n),e);else if(t=="uint32")a=new c.onnx.Tensor(new Uint32Array(n),e);else if(t=="uint64")a=new c.onnx.Tensor(new BigUint64Array(n),e);else throw new Error(`Invalid type: ${t}`);return s!==0&&(t=="int64"||t=="uint64")?a.data.fill(BigInt(s)):s!==0&&a.data.fill(s),a}registerConstant(t,e){if(!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);return this.constantTensors[t]=e,e}makeConstant(t,e,s,n=0){return this.registerConstant(t,this.makeTensor(e,s,n))}registerState(t,e,s){if(e||(e=t),!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[t]={outputName:e,tensor:s},s}makeState(t,e,s,n,a=0){return this.registerState(t,e,this.makeTensor(s,n,a))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return y.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)t[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)t[e]=this.constantTensors[e];try{let e=await this.session.run(t);for(let s in this.stateTensors){let n=e[this.stateTensors[s].outputName];this.stateTensors[s].tensor=n}return e}finally{this._runActive=!1}}resetState(){y.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};function V(c,t){let e=t.reduce((r,o)=>r+o.byteLength,0),s=new DataView(new ArrayBuffer(44));s.setUint8(0,82),s.setUint8(1,73),s.setUint8(2,70),s.setUint8(3,70),s.setUint32(4,44+e,!0),s.setUint8(8,87),s.setUint8(9,65),s.setUint8(10,86),s.setUint8(11,69);let n=1,a=32,l=n*a/8,u=c*l;return s.setUint8(12,102),s.setUint8(13,109),s.setUint8(14,116),s.setUint8(15,32),s.setUint32(16,16,!0),s.setUint16(20,3,!0),s.setUint16(22,n,!0),s.setUint32(24,c,!0),s.setUint32(28,u,!0),s.setUint16(32,l,!0),s.setUint16(34,a,!0),s.setUint8(36,100),s.setUint8(37,97),s.setUint8(38,116),s.setUint8(39,97),s.setUint32(40,e,!0),new File([s,...t],"audio.wav",{type:"audio/wav"})}var O=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var K=class{constructor(t,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!t)throw new Error(`Invalid array class: ${t}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=t,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((t,e)=>t+e.length,0)}feed(t){this.partialBuffers.push(t)}get canDrain(){return this.partialBuffers.reduce((e,s)=>e+s.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let t=this.ArrayClass,e=new t(this.outputBufferSize),s=0;for(;s!=e.length;){if(s>e.length)throw new Error(`Buffer overflow: ${s} > ${e.length}`);let n=e.length-s,a=this.partialBuffers[0],l=a.length-this.partialBufferOffset;l<n?(e.set(a.subarray(this.partialBufferOffset),s),s+=l,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(a.subarray(this.partialBufferOffset,this.partialBufferOffset+n),s),s+=n,this.partialBufferOffset+=n)}return e}pad(){let t=this.queuedSize%this.outputBufferSize;if(t==0)return;let e=this.ArrayClass,s=new e(t);this.feed(s)}};var W=class{constructor(t,e,s,n){if(!t||!e||!s)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=t,this.toSampleRate=e,this.channels=s||0,this.inputBufferSize=n,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=t=>t,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(t){try{return this.outputBuffer.subarray(0,t)}catch{try{return this.outputBuffer.length=t,this.outputBuffer}catch{return this.outputBuffer.slice(0,t)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=t=>{let e=t.length,s=this.channels,n,a,l,u,r,o,i,h,d;if(e%s!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(n=this.outputBufferSize,a=this.ratioWeight,l=this.lastWeight,u=0,r=0,o=0,i=0,h=this.outputBuffer;l<1;l+=a)for(r=l%1,u=1-r,this.lastWeight=l%1,d=0;d<this.channels;++d)h[i++]=this.lastOutput[d]*u+t[d]*r;for(l-=1,e-=s,o=Math.floor(l)*s;i<n&&o<e;){for(r=l%1,u=1-r,d=0;d<this.channels;++d)h[i++]=t[o+(d>0?d:0)]*u+t[o+(s+d)]*r;l+=a,o=Math.floor(l)*s}for(d=0;d<s;++d)this.lastOutput[d]=t[o++];return this.bufferSlice(i)}}multiTap(){this.resampler=t=>{let e=t.length,s,n,a=this.channels,l,u,r,o,i,h,d,v,x;if(e%a!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,n=[],l=this.ratioWeight,u=0,o=0,i=0,h=!this.tailExists,this.tailExists=!1,d=this.outputBuffer,v=0,x=0,r=0;r<a;++r)n[r]=0;do{if(h)for(u=l,r=0;r<a;++r)n[r]=0;else{for(u=this.lastWeight,r=0;r<a;++r)n[r]=this.lastOutput[r];h=!0}for(;u>0&&o<e;)if(i=1+o-x,u>=i){for(r=0;r<a;++r)n[r]+=t[o++]*i;x=o,u-=i}else{for(r=0;r<a;++r)n[r]+=t[o+(r>0?r:0)]*u;x+=u,u=0;break}if(u===0)for(r=0;r<a;++r)d[v++]=n[r]/l;else{for(this.lastWeight=u,r=0;r<a;++r)this.lastOutput[r]=n[r];this.tailExists=!0;break}}while(o<e&&v<s);return this.bufferSlice(v)}}resample(t){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(t)}};function te(c){let t=c.length,e=new Int16Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,c[t]));e[t]=s<0?s*32768:s*32767}return e}function se(c){let t=c.length,e=new BigInt64Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,c[t]));e[t]=BigInt(Math.floor(s<0?s*32768:s*32767))*0x100000000000n}return e}function ne(c){let t=c.length,e=new Float32Array(t);for(;t--;){let s=c[t];e[t]=s>=32768?-(65536-s)/32768:s/32767}return e}var p=new g("ChatGPT"),S=class{constructor(t){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...t}}async sendMessage(t){this.messages.push({role:"user",content:t}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let e=this.messages[this.messages.length-1];return e?.role=="assistant"&&e.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),p.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let t=this.messages[this.messages.length-1];if(t?.role=="user"||t?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(t?.role=="assistant"&&t?.tool_calls?.length){for(let e of t.tool_calls)await this.processToolCall(e);await this.processMessages()}}async trimMessages(){for(;;){let t=await this.sendToAPI(!0);if(JSON.stringify(t).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){p.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(t){let e=0;for(let r=this.messages.length-1;r>=0;r--)if(this.messages[r].role=="assistant"&&this.messages[r].tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[r].role=="user")break;p.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let s={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let r of this.tools){r.description&&r.description.length>1024&&p.warn(`Tool description for "${r.name}" is too long, it will be truncated.`);let o={type:"function",function:{name:r.name,description:(r.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(r.params))for(let i of r.params)o.function.parameters.properties[i.name]={type:i.type,description:i.description};else if(r.params){let i=r.params;for(let h in i)o.function.parameters.properties[h]={type:"string",description:i[h]}}s.tools.push(o)}s.user||delete s.user,s.tools.length||delete s.tools;let n={};if(n["Content-Type"]="application/json",this.config.apiKey&&(n.Authorization=`Bearer ${this.config.apiKey}`),t)return s;let a=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:n,body:JSON.stringify(s)});if(!a.ok){let r=`${a.status} ${a.statusText}`;try{let i=await a.json();r=i.errorText||i.error?.message||i.error||r}catch{}let o=new Error(r);throw o.code=a.status,o}let l=null,u=null;if(this.config.stream)for await(let r of P(a.body)){if(r.data=="[DONE]")break;if(!r.data)continue;let o=JSON.parse(r.data);if(u){for(let i in o.choices[0].delta)if(typeof o.choices[0].delta[i]=="string"){if(i=="role"&&u[i]==o.choices[0].delta[i])continue;u[i]=(u[i]||"")+o.choices[0].delta[i]}for(let i of o.choices[0].delta.tool_calls||[]){if(u.tool_calls||(u.tool_calls=[]),!u.tool_calls[i.index]){u.tool_calls[i.index]=i;continue}let h=u.tool_calls[i.index];h.function=h.function||{},h.function.name=(h.function.name||"")+(i.function?.name||""),h.function.arguments=(h.function.arguments||"")+(i.function?.arguments||"")}}else u={chunkID:o.id,...o.choices[0].delta};u?.content&&!u.content.startsWith("{")&&this.config.onAIMessage?.(u.content,!0)}else l=await a.json(),this.stats.tokensUsed+=l.usage?.total_tokens||0,p.debug(`Used ${l.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),u=l.choices?.[0]?.message;if(u||(p.warn("No response block in API response."),u={role:"assistant",content:""}),u.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(u),this.messages.push(u),u.content&&this.config.onAIMessage?.(u.content,!1)}processIncomingMessage(t){}registerTool(t){this.tools.push(t)}async processToolCall(t){try{let e=this.tools.find(a=>a.name==t.function.name);if(!e)throw new Error(`Tool "${t.function.name}" not found.`);let s=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,s);let n=await e.callback(s);if(typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){p.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(a=>a.role!="assistant"||!a.tool_calls?.find(l=>l.id==t.id));return}else e.removeFromMessageHistory&&p.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${e.name}"`);this.messages.push({role:"tool",content:n,tool_call_id:t.id})}catch(e){p.warn(`Unable to process tool call for "${t?.function?.name}"`,e),this.messages.push({role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id})}}resetConversation(){this.messages=[]}};import L from"minisearch";var $=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(c,t)=>{let e=await t.knowledgeBase.search(c.query),s=t;s._lastKBsearch=c.query,s._nextRequestUseKBitems=e,t.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let n=e.filter(l=>l.type!="action").map(l=>"id="+l.id).join(", ")||"(none)",a=e.filter(l=>l.type=="action").map(l=>"name="+l._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${a}.`}}];var m=new g("KnowledgeBase"),N=1,E=class c{constructor(t){this._sources=[{id:"core.internal",query:async()=>$}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${N++}`),this._sources.push({id:s,query:e}),s}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return typeof window<"u"&&f().knowledgeBaseSources&&(t=t.concat(f().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){m.debug(`Searching knowledge base for: ${t}`);let e=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});e.query=t,e.entries=[],e.sources=[],typeof document<"u"&&document.dispatchEvent(e),this._windowSources=e.sources;let n=(await Promise.all(this.sources.map(async r=>{try{let o=Date.now(),i=await r.query(t);return m.debug(`Source '${r.id}' took ${Date.now()-o}ms`),i||[]}catch(o){return m.warn(`Knowledge source '${r.id}' failed:`,o),[]}}))).flat();n=n.concat(e.entries),n=n.concat(this.manualEntries),f().knowledgeBase&&(n=n.concat(f().knowledgeBase)),n=n.filter(r=>r&&!r.disabled);for(let r=0;r<n.length;r++){let o=n[r];if(o.id=o.id||`temp.${r}`,o._functionID=o.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!o.action&&o.type=="tour"&&(o.action=i=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!o.action&&o.type=="info"&&(o.action=i=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),o.parameters&&!Array.isArray(o.parameters)){let i=o.parameters,h=[];for(let d in i)h.push({name:d,type:"string",description:o.parameters[d]});o.parameters=h}}let a=new L({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});a.addAll(n);let u=a.search(t).map(r=>n.find(o=>o.id==r.id));for(let r of n)r.isContext&&(u.find(o=>o.id===r.id)||u.push(r));return this.lastResults=u,m.debug("Found results:",u),u}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${N++}`),m.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],a=!0,l=async(r,o)=>{m.debug(`Calling remote knowledge base action: ${r.id}`);let i={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:r.id,parameters:o},h=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!h.ok)throw new Error(`HTTP Error ${h.status} ${h.statusText}`);let d=await h.json();return u(d.updateItems||[]),d.response},u=r=>{for(let o of r){if(!o.id){m.warn("KB item skipped since it has no ID.",o);continue}let i=s.find(h=>h.id==o.id);if(i){i.name=o.name||i.name||"",i.content=o.content||i.content||"",i.disabled=o.disabled??i.disabled,i.isContext=o.isContext??i.isContext,i.parameters=o.parameters||i.parameters||[],i.tags=o.tags||i.tags,i.type=o.type||i.type;continue}s.push({...o,action:h=>l(o,h)})}};this.registerSource(e,async r=>{if(a&&n.includes(r))return s;let o={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:r},i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let h=await i.json();return a=!h.noCache,n.includes(r)||n.push(r),u(h.items),s})}clone(){let t=new c(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}};import{v4 as R}from"uuid";var U={name:"@intelliweave/embedded",version:"1.6.54",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var T=class{constructor(t){this.ai=t}async boolean(t,e){let s=this.ai.clone();s.resetConversation(),s.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let n=await s.sendMessage(t+`
10
10
 
11
11
  `+JSON.stringify(e))||"";if(n.toLowerCase().includes("true"))return!0;if(n.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+n)}async choose(t,e,s){s=s.map(l=>l.trim());let n=this.ai.clone();n.resetConversation(),n.getContextPrefix=async()=>"You will receive a question and some data and options. Answer the question by replying with the option you want to choose. Only say the option you want, no additional text.";let a=await n.sendMessage("question:"+t+`
12
12
 
@@ -6,7 +6,7 @@ import we,{createContext as Ae,useContext as Ye,useEffect as q,useMemo as He,use
6
6
  `);for(let d of c){n=d.indexOf(": ");let a=d.slice(0,n),u=d.slice(n+2);n==-1&&(a=d,u=""),a&&(r[a]!==void 0?r[a]+=`
7
7
  `+u:r[a]=u)}yield r}},t=new TextDecoder,s=l.getReader();for(;;){let{done:n,value:o}=await s.read();if(n)break;i+=t.decode(o,{stream:!0}),yield*e()}i+=t.decode()+`
8
8
 
9
- `,yield*e()}function le(){if(h().userID)return h().userID;if(typeof localStorage<"u"){let l=localStorage.getItem("intelliweave.uid")||"";return l||(l=ae(),localStorage.setItem("intelliweave.uid",l),l)}else return ae()}var T=class T{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return T.debug?!0:typeof window<"u"&&h().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...s)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...s)}};T.debug=!1;var p=T;var f=new p("ChatGPT"),L=class{constructor(i){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...i}}async sendMessage(i){this.messages.push({role:"user",content:i}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let e=this.messages[this.messages.length-1];return e?.role=="assistant"&&e.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),f.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let i=this.messages[this.messages.length-1];if(i?.role=="user"||i?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(i?.role=="assistant"&&i?.tool_calls?.length){for(let e of i.tool_calls)await this.processToolCall(e);await this.processMessages()}}async trimMessages(){for(;;){let i=await this.sendToAPI(!0);if(JSON.stringify(i).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){f.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(i){let e=0;for(let c=this.messages.length-1;c>=0;c--)if(this.messages[c].role=="assistant"&&this.messages[c].tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[c].role=="user")break;f.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let c of this.tools){c.description&&c.description.length>1024&&f.warn(`Tool description for "${c.name}" is too long, it will be truncated.`);let d={type:"function",function:{name:c.name,description:(c.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(c.params))for(let a of c.params)d.function.parameters.properties[a.name]={type:a.type,description:a.description};else if(c.params){let a=c.params;for(let u in a)d.function.parameters.properties[u]={type:"string",description:a[u]}}t.tools.push(d)}t.user||delete t.user,t.tools.length||delete t.tools;let s={};if(s["Content-Type"]="application/json",this.config.apiKey&&(s.Authorization=`Bearer ${this.config.apiKey}`),i)return t;let n=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:s,body:JSON.stringify(t)});if(!n.ok){let c=`${n.status} ${n.statusText}`;try{let a=await n.json();c=a.errorText||a.error?.message||a.error||c}catch{}let d=new Error(c);throw d.code=n.status,d}let o=null,r=null;if(this.config.stream)for await(let c of re(n.body)){if(c.data=="[DONE]")break;if(!c.data)continue;let d=JSON.parse(c.data);if(r){for(let a in d.choices[0].delta)if(typeof d.choices[0].delta[a]=="string"){if(a=="role"&&r[a]==d.choices[0].delta[a])continue;r[a]=(r[a]||"")+d.choices[0].delta[a]}for(let a of d.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[a.index]){r.tool_calls[a.index]=a;continue}let u=r.tool_calls[a.index];u.function=u.function||{},u.function.name=(u.function.name||"")+(a.function?.name||""),u.function.arguments=(u.function.arguments||"")+(a.function?.arguments||"")}}else r={chunkID:d.id,...d.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}else o=await n.json(),this.stats.tokensUsed+=o.usage?.total_tokens||0,f.debug(`Used ${o.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),r=o.choices?.[0]?.message;if(r||(f.warn("No response block in API response."),r={role:"assistant",content:""}),r.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(r),this.messages.push(r),r.content&&this.config.onAIMessage?.(r.content,!1)}processIncomingMessage(i){}registerTool(i){this.tools.push(i)}async processToolCall(i){try{let e=this.tools.find(n=>n.name==i.function.name);if(!e)throw new Error(`Tool "${i.function.name}" not found.`);let t=JSON.parse(i.function.arguments);this.config.onAIToolStart?.(i.function.name,t);let s=await e.callback(t);if(typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){f.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(n=>n.role!="assistant"||!n.tool_calls?.find(o=>o.id==i.id));return}else e.removeFromMessageHistory&&f.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${e.name}"`);this.messages.push({role:"tool",content:s,tool_call_id:i.id})}catch(e){f.warn(`Unable to process tool call for "${i?.function?.name}"`,e),this.messages.push({role:"tool",content:`Error: ${e.message}`,tool_call_id:i.id})}}resetConversation(){this.messages=[]}};import{v4 as ue}from"uuid";import Xe from"minisearch";var ce=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(l,i)=>{let e=await i.knowledgeBase.search(l.query),t=i;t._lastKBsearch=l.query,t._nextRequestUseKBitems=e,i.submitAnalyticsEvent({type:"kb-search",query:l.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${n}.`}}];var x=new p("KnowledgeBase"),de=1,k=class l{constructor(i){this._sources=[{id:"core.internal",query:async()=>ce}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${de++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return typeof window<"u"&&h().knowledgeBaseSources&&(i=i.concat(h().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){x.debug(`Searching knowledge base for: ${i}`);let e=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});e.query=i,e.entries=[],e.sources=[],typeof document<"u"&&document.dispatchEvent(e),this._windowSources=e.sources;let s=(await Promise.all(this.sources.map(async c=>{try{let d=Date.now(),a=await c.query(i);return x.debug(`Source '${c.id}' took ${Date.now()-d}ms`),a||[]}catch(d){return x.warn(`Knowledge source '${c.id}' failed:`,d),[]}}))).flat();s=s.concat(e.entries),s=s.concat(this.manualEntries),h().knowledgeBase&&(s=s.concat(h().knowledgeBase)),s=s.filter(c=>c&&!c.disabled);for(let c=0;c<s.length;c++){let d=s[c];if(d.id=d.id||`temp.${c}`,d._functionID=d.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!d.action&&d.type=="tour"&&(d.action=a=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!d.action&&d.type=="info"&&(d.action=a=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),d.parameters&&!Array.isArray(d.parameters)){let a=d.parameters,u=[];for(let w in a)u.push({name:w,type:"string",description:d.parameters[w]});d.parameters=u}}let n=new Xe({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});n.addAll(s);let r=n.search(i).map(c=>s.find(d=>d.id==c.id));for(let c of s)c.isContext&&(r.find(d=>d.id===c.id)||r.push(c));return this.lastResults=r,x.debug("Found results:",r),r}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${de++}`),x.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(c,d)=>{x.debug(`Calling remote knowledge base action: ${c.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:c.id,parameters:d},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let w=await u.json();return r(w.updateItems||[]),w.response},r=c=>{for(let d of c){if(!d.id){x.warn("KB item skipped since it has no ID.",d);continue}let a=t.find(u=>u.id==d.id);if(a){a.name=d.name||a.name||"",a.content=d.content||a.content||"",a.disabled=d.disabled??a.disabled,a.isContext=d.isContext??a.isContext,a.parameters=d.parameters||a.parameters||[],a.tags=d.tags||a.tags,a.type=d.type||a.type;continue}t.push({...d,action:u=>o(d,u)})}};this.registerSource(e,async c=>{if(n&&s.includes(c))return t;let d={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:c},a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let u=await a.json();return n=!u.noCache,s.includes(c)||s.push(c),r(u.items),t})}clone(){let i=new l(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}};var he={name:"@intelliweave/embedded",version:"1.6.53",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var B=class{constructor(i){this.ai=i}async boolean(i,e){let t=this.ai.clone();t.resetConversation(),t.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let s=await t.sendMessage(i+`
9
+ `,yield*e()}function le(){if(h().userID)return h().userID;if(typeof localStorage<"u"){let l=localStorage.getItem("intelliweave.uid")||"";return l||(l=ae(),localStorage.setItem("intelliweave.uid",l),l)}else return ae()}var T=class T{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return T.debug?!0:typeof window<"u"&&h().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...s)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...s)}};T.debug=!1;var p=T;var f=new p("ChatGPT"),L=class{constructor(i){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...i}}async sendMessage(i){this.messages.push({role:"user",content:i}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let e=this.messages[this.messages.length-1];return e?.role=="assistant"&&e.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),f.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let i=this.messages[this.messages.length-1];if(i?.role=="user"||i?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(i?.role=="assistant"&&i?.tool_calls?.length){for(let e of i.tool_calls)await this.processToolCall(e);await this.processMessages()}}async trimMessages(){for(;;){let i=await this.sendToAPI(!0);if(JSON.stringify(i).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){f.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(i){let e=0;for(let c=this.messages.length-1;c>=0;c--)if(this.messages[c].role=="assistant"&&this.messages[c].tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[c].role=="user")break;f.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let c of this.tools){c.description&&c.description.length>1024&&f.warn(`Tool description for "${c.name}" is too long, it will be truncated.`);let d={type:"function",function:{name:c.name,description:(c.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(c.params))for(let a of c.params)d.function.parameters.properties[a.name]={type:a.type,description:a.description};else if(c.params){let a=c.params;for(let u in a)d.function.parameters.properties[u]={type:"string",description:a[u]}}t.tools.push(d)}t.user||delete t.user,t.tools.length||delete t.tools;let s={};if(s["Content-Type"]="application/json",this.config.apiKey&&(s.Authorization=`Bearer ${this.config.apiKey}`),i)return t;let n=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:s,body:JSON.stringify(t)});if(!n.ok){let c=`${n.status} ${n.statusText}`;try{let a=await n.json();c=a.errorText||a.error?.message||a.error||c}catch{}let d=new Error(c);throw d.code=n.status,d}let o=null,r=null;if(this.config.stream)for await(let c of re(n.body)){if(c.data=="[DONE]")break;if(!c.data)continue;let d=JSON.parse(c.data);if(r){for(let a in d.choices[0].delta)if(typeof d.choices[0].delta[a]=="string"){if(a=="role"&&r[a]==d.choices[0].delta[a])continue;r[a]=(r[a]||"")+d.choices[0].delta[a]}for(let a of d.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[a.index]){r.tool_calls[a.index]=a;continue}let u=r.tool_calls[a.index];u.function=u.function||{},u.function.name=(u.function.name||"")+(a.function?.name||""),u.function.arguments=(u.function.arguments||"")+(a.function?.arguments||"")}}else r={chunkID:d.id,...d.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}else o=await n.json(),this.stats.tokensUsed+=o.usage?.total_tokens||0,f.debug(`Used ${o.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),r=o.choices?.[0]?.message;if(r||(f.warn("No response block in API response."),r={role:"assistant",content:""}),r.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(r),this.messages.push(r),r.content&&this.config.onAIMessage?.(r.content,!1)}processIncomingMessage(i){}registerTool(i){this.tools.push(i)}async processToolCall(i){try{let e=this.tools.find(n=>n.name==i.function.name);if(!e)throw new Error(`Tool "${i.function.name}" not found.`);let t=JSON.parse(i.function.arguments);this.config.onAIToolStart?.(i.function.name,t);let s=await e.callback(t);if(typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){f.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(n=>n.role!="assistant"||!n.tool_calls?.find(o=>o.id==i.id));return}else e.removeFromMessageHistory&&f.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${e.name}"`);this.messages.push({role:"tool",content:s,tool_call_id:i.id})}catch(e){f.warn(`Unable to process tool call for "${i?.function?.name}"`,e),this.messages.push({role:"tool",content:`Error: ${e.message}`,tool_call_id:i.id})}}resetConversation(){this.messages=[]}};import{v4 as ue}from"uuid";import Xe from"minisearch";var ce=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(l,i)=>{let e=await i.knowledgeBase.search(l.query),t=i;t._lastKBsearch=l.query,t._nextRequestUseKBitems=e,i.submitAnalyticsEvent({type:"kb-search",query:l.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${n}.`}}];var x=new p("KnowledgeBase"),de=1,k=class l{constructor(i){this._sources=[{id:"core.internal",query:async()=>ce}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${de++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return typeof window<"u"&&h().knowledgeBaseSources&&(i=i.concat(h().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){x.debug(`Searching knowledge base for: ${i}`);let e=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});e.query=i,e.entries=[],e.sources=[],typeof document<"u"&&document.dispatchEvent(e),this._windowSources=e.sources;let s=(await Promise.all(this.sources.map(async c=>{try{let d=Date.now(),a=await c.query(i);return x.debug(`Source '${c.id}' took ${Date.now()-d}ms`),a||[]}catch(d){return x.warn(`Knowledge source '${c.id}' failed:`,d),[]}}))).flat();s=s.concat(e.entries),s=s.concat(this.manualEntries),h().knowledgeBase&&(s=s.concat(h().knowledgeBase)),s=s.filter(c=>c&&!c.disabled);for(let c=0;c<s.length;c++){let d=s[c];if(d.id=d.id||`temp.${c}`,d._functionID=d.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!d.action&&d.type=="tour"&&(d.action=a=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!d.action&&d.type=="info"&&(d.action=a=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),d.parameters&&!Array.isArray(d.parameters)){let a=d.parameters,u=[];for(let w in a)u.push({name:w,type:"string",description:d.parameters[w]});d.parameters=u}}let n=new Xe({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});n.addAll(s);let r=n.search(i).map(c=>s.find(d=>d.id==c.id));for(let c of s)c.isContext&&(r.find(d=>d.id===c.id)||r.push(c));return this.lastResults=r,x.debug("Found results:",r),r}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${de++}`),x.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(c,d)=>{x.debug(`Calling remote knowledge base action: ${c.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:c.id,parameters:d},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let w=await u.json();return r(w.updateItems||[]),w.response},r=c=>{for(let d of c){if(!d.id){x.warn("KB item skipped since it has no ID.",d);continue}let a=t.find(u=>u.id==d.id);if(a){a.name=d.name||a.name||"",a.content=d.content||a.content||"",a.disabled=d.disabled??a.disabled,a.isContext=d.isContext??a.isContext,a.parameters=d.parameters||a.parameters||[],a.tags=d.tags||a.tags,a.type=d.type||a.type;continue}t.push({...d,action:u=>o(d,u)})}};this.registerSource(e,async c=>{if(n&&s.includes(c))return t;let d={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:c},a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let u=await a.json();return n=!u.noCache,s.includes(c)||s.push(c),r(u.items),t})}clone(){let i=new l(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}};var he={name:"@intelliweave/embedded",version:"1.6.54",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var B=class{constructor(i){this.ai=i}async boolean(i,e){let t=this.ai.clone();t.resetConversation(),t.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let s=await t.sendMessage(i+`
10
10
 
11
11
  `+JSON.stringify(e))||"";if(s.toLowerCase().includes("true"))return!0;if(s.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+s)}async choose(i,e,t){t=t.map(o=>o.trim());let s=this.ai.clone();s.resetConversation(),s.getContextPrefix=async()=>"You will receive a question and some data and options. Answer the question by replying with the option you want to choose. Only say the option you want, no additional text.";let n=await s.sendMessage("question:"+i+`
12
12
 
@@ -257,25 +257,27 @@ You have access to a database of knowledge base items. These include "info" type
257
257
 
258
258
  #root {
259
259
  position: fixed;
260
- display: flex;
261
- flex-direction: column;
262
260
  width: 64px;
263
261
  height: 64px;
264
262
  z-index: 200000;
265
263
  background-color: #20262C;
266
- border-radius: 32px;
264
+ border-radius: 50%;
267
265
  box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
268
266
  transition: width 0.25s, height 0.25s, border-radius 0.25s;
269
267
  overflow: hidden;
270
268
  color: white;
271
269
  font-family: "Karla", sans-serif;
270
+ overlow: hidden;
272
271
  }
273
272
  #root.open {
274
273
  border-radius: 32px 32px 16px 16px;
274
+ display: flex;
275
+ flex-direction: column;
275
276
  width: 400px;
276
277
  height: 600px;
277
278
  max-width: calc(100vw - 40px);
278
279
  max-height: calc(max(50vh, 100vh - 320px));
280
+ overflow: visible;
279
281
  }
280
282
 
281
283
  #root #web-weaver-logo {
@@ -285,6 +287,7 @@ You have access to a database of knowledge base items. These include "info" type
285
287
  top: 0px;
286
288
  left: 0px;
287
289
  background-color: #21262c;
290
+ border-radius:50%;
288
291
  z-index:999;
289
292
  }
290
293
 
@@ -303,6 +306,8 @@ You have access to a database of knowledge base items. These include "info" type
303
306
  overflow: hidden;
304
307
  font-size: 9px;
305
308
  color: #abacad;
309
+ border-bottom-right-radius: 16px;
310
+ border-bottom-left-radius: 16px;
306
311
  }
307
312
 
308
313
  #root .green-accent {
@@ -6,7 +6,7 @@ import{b as pr,c as _i,d as Hi}from"./chunk-FSRPMVAS.js";var gs=pr((vw,ms)=>{"us
6
6
  `);for(let c of l){o=c.indexOf(": ");let u=c.slice(0,o),p=c.slice(o+2);o==-1&&(u=c,p=""),u&&(s[u]!==void 0?s[u]+=`
7
7
  `+p:s[u]=p)}yield s}},r=new TextDecoder,i=e.getReader();for(;;){let{done:o,value:a}=await i.read();if(o)break;n+=r.decode(a,{stream:!0}),yield*t()}n+=r.decode()+`
8
8
 
9
- `,yield*t()}function Yi(){if(Q().userID)return Q().userID;if(typeof localStorage<"u"){let e=localStorage.getItem("intelliweave.uid")||"";return e||(e=Ue(),localStorage.setItem("intelliweave.uid",e),e)}else return Ue()}var Qt=class Qt{constructor(n){this.module="IntelliWeave";this.module=n}get debugEnabled(){return Qt.debug?!0:typeof window<"u"&&Q().debug}log(...n){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...n)}debug(...n){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...n)}info(...n){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...n)}warn(...n){console.warn(`[IntelliWeave > ${this.module}]`,...n)}error(...n){console.error(`[IntelliWeave > ${this.module}]`,...n)}timer(n,...t){let r=Date.now();return this.debug(`[${n} 0ms] Started`,...t),(...i)=>this.debug(`[${n} ${Math.floor(Date.now()-r)}ms]`,...i)}};Qt.debug=!1;var U=Qt;var Pe=new U("ChatGPT"),qt=class{constructor(n){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...n}}async sendMessage(n){this.messages.push({role:"user",content:n}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let t=this.messages[this.messages.length-1];return t?.role=="assistant"&&t.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),Pe.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let n=this.messages[this.messages.length-1];if(n?.role=="user"||n?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(n?.role=="assistant"&&n?.tool_calls?.length){for(let t of n.tool_calls)await this.processToolCall(t);await this.processMessages()}}async trimMessages(){for(;;){let n=await this.sendToAPI(!0);if(JSON.stringify(n).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){Pe.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(n){let t=0;for(let l=this.messages.length-1;l>=0;l--)if(this.messages[l].role=="assistant"&&this.messages[l].tool_calls){if(t+=1,t>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[l].role=="user")break;Pe.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let r={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let l of this.tools){l.description&&l.description.length>1024&&Pe.warn(`Tool description for "${l.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:l.name,description:(l.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(l.params))for(let u of l.params)c.function.parameters.properties[u.name]={type:u.type,description:u.description};else if(l.params){let u=l.params;for(let p in u)c.function.parameters.properties[p]={type:"string",description:u[p]}}r.tools.push(c)}r.user||delete r.user,r.tools.length||delete r.tools;let i={};if(i["Content-Type"]="application/json",this.config.apiKey&&(i.Authorization=`Bearer ${this.config.apiKey}`),n)return r;let o=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(r)});if(!o.ok){let l=`${o.status} ${o.statusText}`;try{let u=await o.json();l=u.errorText||u.error?.message||u.error||l}catch{}let c=new Error(l);throw c.code=o.status,c}let a=null,s=null;if(this.config.stream)for await(let l of Ki(o.body)){if(l.data=="[DONE]")break;if(!l.data)continue;let c=JSON.parse(l.data);if(s){for(let u in c.choices[0].delta)if(typeof c.choices[0].delta[u]=="string"){if(u=="role"&&s[u]==c.choices[0].delta[u])continue;s[u]=(s[u]||"")+c.choices[0].delta[u]}for(let u of c.choices[0].delta.tool_calls||[]){if(s.tool_calls||(s.tool_calls=[]),!s.tool_calls[u.index]){s.tool_calls[u.index]=u;continue}let p=s.tool_calls[u.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(u.function?.name||""),p.function.arguments=(p.function.arguments||"")+(u.function?.arguments||"")}}else s={chunkID:c.id,...c.choices[0].delta};s?.content&&!s.content.startsWith("{")&&this.config.onAIMessage?.(s.content,!0)}else a=await o.json(),this.stats.tokensUsed+=a.usage?.total_tokens||0,Pe.debug(`Used ${a.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),s=a.choices?.[0]?.message;if(s||(Pe.warn("No response block in API response."),s={role:"assistant",content:""}),s.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(s),this.messages.push(s),s.content&&this.config.onAIMessage?.(s.content,!1)}processIncomingMessage(n){}registerTool(n){this.tools.push(n)}async processToolCall(n){try{let t=this.tools.find(o=>o.name==n.function.name);if(!t)throw new Error(`Tool "${n.function.name}" not found.`);let r=JSON.parse(n.function.arguments);this.config.onAIToolStart?.(n.function.name,r);let i=await t.callback(r);if(typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&t.removeFromMessageHistory){Pe.debug(`Removing tool call history for "${t.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(o=>o.role!="assistant"||!o.tool_calls?.find(a=>a.id==n.id));return}else t.removeFromMessageHistory&&Pe.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${t.name}"`);this.messages.push({role:"tool",content:i,tool_call_id:n.id})}catch(t){Pe.warn(`Unable to process tool call for "${n?.function?.name}"`,t),this.messages.push({role:"tool",content:`Error: ${t.message}`,tool_call_id:n.id})}}resetConversation(){this.messages=[]}};var J=function(){return J=Object.assign||function(n){for(var t,r=1,i=arguments.length;r<i;r++){t=arguments[r];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(n[o]=t[o])}return n},J.apply(this,arguments)};function qs(e,n,t,r){function i(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function s(u){try{c(r.next(u))}catch(p){a(p)}}function l(u){try{c(r.throw(u))}catch(p){a(p)}}function c(u){u.done?o(u.value):i(u.value).then(s,l)}c((r=r.apply(e,n||[])).next())})}function $s(e,n){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,c[0]&&(t=0)),t;)try{if(r=1,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,i=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){t.label=c[1];break}if(c[0]===6&&t.label<o[1]){t.label=o[1],o=c;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(c);break}o[2]&&t.ops.pop(),t.trys.pop();continue}c=n.call(e,t)}catch(u){c=[6,u],i=0}finally{r=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function X(e){var n=typeof Symbol=="function"&&Symbol.iterator,t=n&&e[n],r=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function $(e,n){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var r=t.call(e),i,o=[],a;try{for(;(n===void 0||n-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(s){a={error:s}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o}var el="ENTRIES",$i="KEYS",eo="VALUES",le="",mr=function(){function e(n,t){var r=n._tree,i=Array.from(r.keys());this.set=n,this._type=t,this._path=i.length>0?[{node:r,keys:i}]:[]}return e.prototype.next=function(){var n=this.dive();return this.backtrack(),n},e.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var n=at(this._path),t=n.node,r=n.keys;if(at(r)===le)return{done:!1,value:this.result()};var i=t.get(at(r));return this._path.push({node:i,keys:Array.from(i.keys())}),this.dive()},e.prototype.backtrack=function(){if(this._path.length!==0){var n=at(this._path).keys;n.pop(),!(n.length>0)&&(this._path.pop(),this.backtrack())}},e.prototype.key=function(){return this.set._prefix+this._path.map(function(n){var t=n.keys;return at(t)}).filter(function(n){return n!==le}).join("")},e.prototype.value=function(){return at(this._path).node.get(le)},e.prototype.result=function(){switch(this._type){case eo:return this.value();case $i:return this.key();default:return[this.key(),this.value()]}},e.prototype[Symbol.iterator]=function(){return this},e}(),at=function(e){return e[e.length-1]},tl=function(e,n,t){var r=new Map;if(n===void 0)return r;for(var i=n.length+1,o=i+t,a=new Uint8Array(o*i).fill(t+1),s=0;s<i;++s)a[s]=s;for(var l=1;l<o;++l)a[l*i]=l;return to(e,n,t,r,a,1,i,""),r},to=function(e,n,t,r,i,o,a,s){var l,c,u=o*a;try{e:for(var p=X(e.keys()),d=p.next();!d.done;d=p.next()){var h=d.value;if(h===le){var g=i[u-1];g<=t&&r.set(s,[e.get(h),g])}else{for(var w=o,k=0;k<h.length;++k,++w){for(var y=h[k],I=a*w,v=I-a,z=i[I],P=Math.max(0,w-t-1),x=Math.min(a-1,w+t),A=P;A<x;++A){var F=y!==n[A],R=i[v+A]+ +F,Z=i[v+A+1]+1,D=i[I+A]+1,M=i[I+A+1]=Math.min(R,Z,D);M<z&&(z=M)}if(z>t)continue e}to(e.get(h),n,t,r,i,w,a,s+h)}}}catch(C){l={error:C}}finally{try{d&&!d.done&&(c=p.return)&&c.call(p)}finally{if(l)throw l.error}}},gr=function(){function e(n,t){n===void 0&&(n=new Map),t===void 0&&(t=""),this._size=void 0,this._tree=n,this._prefix=t}return e.prototype.atPrefix=function(n){var t,r;if(!n.startsWith(this._prefix))throw new Error("Mismatched prefix");var i=$(en(this._tree,n.slice(this._prefix.length)),2),o=i[0],a=i[1];if(o===void 0){var s=$(Er(a),2),l=s[0],c=s[1];try{for(var u=X(l.keys()),p=u.next();!p.done;p=u.next()){var d=p.value;if(d!==le&&d.startsWith(c)){var h=new Map;return h.set(d.slice(c.length),l.get(d)),new e(h,n)}}}catch(g){t={error:g}}finally{try{p&&!p.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}}return new e(o,n)},e.prototype.clear=function(){this._size=void 0,this._tree.clear()},e.prototype.delete=function(n){return this._size=void 0,nl(this._tree,n)},e.prototype.entries=function(){return new mr(this,el)},e.prototype.forEach=function(n){var t,r;try{for(var i=X(this),o=i.next();!o.done;o=i.next()){var a=$(o.value,2),s=a[0],l=a[1];n(s,l,this)}}catch(c){t={error:c}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},e.prototype.fuzzyGet=function(n,t){return tl(this._tree,n,t)},e.prototype.get=function(n){var t=vr(this._tree,n);return t!==void 0?t.get(le):void 0},e.prototype.has=function(n){var t=vr(this._tree,n);return t!==void 0&&t.has(le)},e.prototype.keys=function(){return new mr(this,$i)},e.prototype.set=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n);return r.set(le,t),this},Object.defineProperty(e.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var n=this.entries();!n.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),e.prototype.update=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n);return r.set(le,t(r.get(le))),this},e.prototype.fetch=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n),i=r.get(le);return i===void 0&&r.set(le,i=t()),i},e.prototype.values=function(){return new mr(this,eo)},e.prototype[Symbol.iterator]=function(){return this.entries()},e.from=function(n){var t,r,i=new e;try{for(var o=X(n),a=o.next();!a.done;a=o.next()){var s=$(a.value,2),l=s[0],c=s[1];i.set(l,c)}}catch(u){t={error:u}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return i},e.fromObject=function(n){return e.from(Object.entries(n))},e}(),en=function(e,n,t){var r,i;if(t===void 0&&(t=[]),n.length===0||e==null)return[e,t];try{for(var o=X(e.keys()),a=o.next();!a.done;a=o.next()){var s=a.value;if(s!==le&&n.startsWith(s))return t.push([e,s]),en(e.get(s),n.slice(s.length),t)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}return t.push([e,n]),en(void 0,"",t)},vr=function(e,n){var t,r;if(n.length===0||e==null)return e;try{for(var i=X(e.keys()),o=i.next();!o.done;o=i.next()){var a=o.value;if(a!==le&&n.startsWith(a))return vr(e.get(a),n.slice(a.length))}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},yr=function(e,n){var t,r,i=n.length;e:for(var o=0;e&&o<i;){try{for(var a=(t=void 0,X(e.keys())),s=a.next();!s.done;s=a.next()){var l=s.value;if(l!==le&&n[o]===l[0]){for(var c=Math.min(i-o,l.length),u=1;u<c&&n[o+u]===l[u];)++u;var p=e.get(l);if(u===l.length)e=p;else{var d=new Map;d.set(l.slice(u),p),e.set(n.slice(o,o+u),d),e.delete(l),e=d}o+=u;continue e}}}catch(g){t={error:g}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}var h=new Map;return e.set(n.slice(o),h),h}return e},nl=function(e,n){var t=$(en(e,n),2),r=t[0],i=t[1];if(r!==void 0){if(r.delete(le),r.size===0)no(i);else if(r.size===1){var o=$(r.entries().next().value,2),a=o[0],s=o[1];ro(i,a,s)}}},no=function(e){if(e.length!==0){var n=$(Er(e),2),t=n[0],r=n[1];if(t.delete(r),t.size===0)no(e.slice(0,-1));else if(t.size===1){var i=$(t.entries().next().value,2),o=i[0],a=i[1];o!==le&&ro(e.slice(0,-1),o,a)}}},ro=function(e,n,t){if(e.length!==0){var r=$(Er(e),2),i=r[0],o=r[1];i.set(o+n,t),i.delete(o)}},Er=function(e){return e[e.length-1]},kt,Cr="or",io="and",rl="and_not",oo=function(){function e(n){if(n?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');var t=n.autoVacuum==null||n.autoVacuum===!0?wr:n.autoVacuum;this._options=J(J(J({},br),n),{autoVacuum:t,searchOptions:J(J({},ji),n.searchOptions||{}),autoSuggestOptions:J(J({},ll),n.autoSuggestOptions||{})}),this._index=new gr,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Sr,this.addFields(this._options.fields)}return e.prototype.add=function(n){var t,r,i,o,a,s,l=this._options,c=l.extractField,u=l.tokenize,p=l.processTerm,d=l.fields,h=l.idField,g=c(n,h);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(h,'"'));if(this._idToShortId.has(g))throw new Error("MiniSearch: duplicate ID ".concat(g));var w=this.addDocumentId(g);this.saveStoredFields(w,n);try{for(var k=X(d),y=k.next();!y.done;y=k.next()){var I=y.value,v=c(n,I);if(v!=null){var z=u(v.toString(),I),P=this._fieldIds[I],x=new Set(z).size;this.addFieldLength(w,P,this._documentCount-1,x);try{for(var A=(i=void 0,X(z)),F=A.next();!F.done;F=A.next()){var R=F.value,Z=p(R,I);if(Array.isArray(Z))try{for(var D=(a=void 0,X(Z)),M=D.next();!M.done;M=D.next()){var C=M.value;this.addTerm(P,w,C)}}catch(L){a={error:L}}finally{try{M&&!M.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else Z&&this.addTerm(P,w,Z)}}catch(L){i={error:L}}finally{try{F&&!F.done&&(o=A.return)&&o.call(A)}finally{if(i)throw i.error}}}}}catch(L){t={error:L}}finally{try{y&&!y.done&&(r=k.return)&&r.call(k)}finally{if(t)throw t.error}}},e.prototype.addAll=function(n){var t,r;try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;this.add(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},e.prototype.addAllAsync=function(n,t){var r=this;t===void 0&&(t={});var i=t.chunkSize,o=i===void 0?10:i,a={chunk:[],promise:Promise.resolve()},s=n.reduce(function(u,p,d){var h=u.chunk,g=u.promise;return h.push(p),(d+1)%o===0?{chunk:[],promise:g.then(function(){return new Promise(function(w){return setTimeout(w,0)})}).then(function(){return r.addAll(h)})}:{chunk:h,promise:g}},a),l=s.chunk,c=s.promise;return c.then(function(){return r.addAll(l)})},e.prototype.remove=function(n){var t,r,i,o,a,s,l=this._options,c=l.tokenize,u=l.processTerm,p=l.extractField,d=l.fields,h=l.idField,g=p(n,h);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(h,'"'));var w=this._idToShortId.get(g);if(w==null)throw new Error("MiniSearch: cannot remove document with ID ".concat(g,": it is not in the index"));try{for(var k=X(d),y=k.next();!y.done;y=k.next()){var I=y.value,v=p(n,I);if(v!=null){var z=c(v.toString(),I),P=this._fieldIds[I],x=new Set(z).size;this.removeFieldLength(w,P,this._documentCount,x);try{for(var A=(i=void 0,X(z)),F=A.next();!F.done;F=A.next()){var R=F.value,Z=u(R,I);if(Array.isArray(Z))try{for(var D=(a=void 0,X(Z)),M=D.next();!M.done;M=D.next()){var C=M.value;this.removeTerm(P,w,C)}}catch(L){a={error:L}}finally{try{M&&!M.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else Z&&this.removeTerm(P,w,Z)}}catch(L){i={error:L}}finally{try{F&&!F.done&&(o=A.return)&&o.call(A)}finally{if(i)throw i.error}}}}}catch(L){t={error:L}}finally{try{y&&!y.done&&(r=k.return)&&r.call(k)}finally{if(t)throw t.error}}this._storedFields.delete(w),this._documentIds.delete(w),this._idToShortId.delete(g),this._fieldLength.delete(w),this._documentCount-=1},e.prototype.removeAll=function(n){var t,r;if(n)try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;this.remove(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new gr,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},e.prototype.discard=function(n){var t=this,r=this._idToShortId.get(n);if(r==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(n,": it is not in the index"));this._idToShortId.delete(n),this._documentIds.delete(r),this._storedFields.delete(r),(this._fieldLength.get(r)||[]).forEach(function(i,o){t.removeFieldLength(r,o,t._documentCount,i)}),this._fieldLength.delete(r),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},e.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var n=this._options.autoVacuum,t=n.minDirtFactor,r=n.minDirtCount,i=n.batchSize,o=n.batchWait;this.conditionalVacuum({batchSize:i,batchWait:o},{minDirtCount:r,minDirtFactor:t})}},e.prototype.discardAll=function(n){var t,r,i=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var o=X(n),a=o.next();!a.done;a=o.next()){var s=a.value;this.discard(s)}}catch(l){t={error:l}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}}finally{this._options.autoVacuum=i}this.maybeAutoVacuum()},e.prototype.replace=function(n){var t=this._options,r=t.idField,i=t.extractField,o=i(n,r);this.discard(o),this.add(n)},e.prototype.vacuum=function(n){return n===void 0&&(n={}),this.conditionalVacuum(n)},e.prototype.conditionalVacuum=function(n,t){var r=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&t,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var i=r._enqueuedVacuumConditions;return r._enqueuedVacuumConditions=Sr,r.performVacuuming(n,i)}),this._enqueuedVacuum)):this.vacuumConditionsMet(t)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(n),this._currentVacuum)},e.prototype.performVacuuming=function(n,t){return qs(this,void 0,void 0,function(){var r,i,o,a,s,l,c,u,p,d,h,g,w,k,y,I,v,z,P,x,A,F,R,Z,D;return $s(this,function(M){switch(M.label){case 0:if(r=this._dirtCount,!this.vacuumConditionsMet(t))return[3,10];i=n.batchSize||kr.batchSize,o=n.batchWait||kr.batchWait,a=1,M.label=1;case 1:M.trys.push([1,7,8,9]),s=X(this._index),l=s.next(),M.label=2;case 2:if(l.done)return[3,6];c=$(l.value,2),u=c[0],p=c[1];try{for(d=(F=void 0,X(p)),h=d.next();!h.done;h=d.next()){g=$(h.value,2),w=g[0],k=g[1];try{for(y=(Z=void 0,X(k)),I=y.next();!I.done;I=y.next())v=$(I.value,1),z=v[0],!this._documentIds.has(z)&&(k.size<=1?p.delete(w):k.delete(z))}catch(C){Z={error:C}}finally{try{I&&!I.done&&(D=y.return)&&D.call(y)}finally{if(Z)throw Z.error}}}}catch(C){F={error:C}}finally{try{h&&!h.done&&(R=d.return)&&R.call(d)}finally{if(F)throw F.error}}return this._index.get(u).size===0&&this._index.delete(u),a%i!==0?[3,4]:[4,new Promise(function(C){return setTimeout(C,o)})];case 3:M.sent(),M.label=4;case 4:a+=1,M.label=5;case 5:return l=s.next(),[3,2];case 6:return[3,9];case 7:return P=M.sent(),x={error:P},[3,9];case 8:try{l&&!l.done&&(A=s.return)&&A.call(s)}finally{if(x)throw x.error}return[7];case 9:this._dirtCount-=r,M.label=10;case 10:return[4,null];case 11:return M.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},e.prototype.vacuumConditionsMet=function(n){if(n==null)return!0;var t=n.minDirtCount,r=n.minDirtFactor;return t=t||wr.minDirtCount,r=r||wr.minDirtFactor,this.dirtCount>=t&&this.dirtFactor>=r},Object.defineProperty(e.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),e.prototype.has=function(n){return this._idToShortId.has(n)},e.prototype.getStoredFields=function(n){var t=this._idToShortId.get(n);if(t!=null)return this._storedFields.get(t)},e.prototype.search=function(n,t){var r,i;t===void 0&&(t={});var o=this.executeQuery(n,t),a=[];try{for(var s=X(o),l=s.next();!l.done;l=s.next()){var c=$(l.value,2),u=c[0],p=c[1],d=p.score,h=p.terms,g=p.match,w=h.length||1,k={id:this._documentIds.get(u),score:d*w,terms:Object.keys(g),queryTerms:h,match:g};Object.assign(k,this._storedFields.get(u)),(t.filter==null||t.filter(k))&&a.push(k)}}catch(y){r={error:y}}finally{try{l&&!l.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return n===e.wildcard&&t.boostDocument==null&&this._options.searchOptions.boostDocument==null||a.sort(Qi),a},e.prototype.autoSuggest=function(n,t){var r,i,o,a;t===void 0&&(t={}),t=J(J({},this._options.autoSuggestOptions),t);var s=new Map;try{for(var l=X(this.search(n,t)),c=l.next();!c.done;c=l.next()){var u=c.value,p=u.score,d=u.terms,h=d.join(" "),g=s.get(h);g!=null?(g.score+=p,g.count+=1):s.set(h,{score:p,terms:d,count:1})}}catch(P){r={error:P}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(r)throw r.error}}var w=[];try{for(var k=X(s),y=k.next();!y.done;y=k.next()){var I=$(y.value,2),g=I[0],v=I[1],p=v.score,d=v.terms,z=v.count;w.push({suggestion:g,terms:d,score:p/z})}}catch(P){o={error:P}}finally{try{y&&!y.done&&(a=k.return)&&a.call(k)}finally{if(o)throw o.error}}return w.sort(Qi),w},Object.defineProperty(e.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),e.loadJSON=function(n,t){if(t==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(n),t)},e.getDefault=function(n){if(br.hasOwnProperty(n))return xr(br,n);throw new Error('MiniSearch: unknown option "'.concat(n,'"'))},e.loadJS=function(n,t){var r,i,o,a,s,l,c=n.index,u=n.documentCount,p=n.nextId,d=n.documentIds,h=n.fieldIds,g=n.fieldLength,w=n.averageFieldLength,k=n.storedFields,y=n.dirtCount,I=n.serializationVersion;if(I!==1&&I!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var v=new e(t);v._documentCount=u,v._nextId=p,v._documentIds=$t(d),v._idToShortId=new Map,v._fieldIds=h,v._fieldLength=$t(g),v._avgFieldLength=w,v._storedFields=$t(k),v._dirtCount=y||0,v._index=new gr;try{for(var z=X(v._documentIds),P=z.next();!P.done;P=z.next()){var x=$(P.value,2),A=x[0],F=x[1];v._idToShortId.set(F,A)}}catch(ne){r={error:ne}}finally{try{P&&!P.done&&(i=z.return)&&i.call(z)}finally{if(r)throw r.error}}try{for(var R=X(c),Z=R.next();!Z.done;Z=R.next()){var D=$(Z.value,2),M=D[0],C=D[1],L=new Map;try{for(var N=(s=void 0,X(Object.keys(C))),H=N.next();!H.done;H=N.next()){var Y=H.value,re=C[Y];I===1&&(re=re.ds),L.set(parseInt(Y,10),$t(re))}}catch(ne){s={error:ne}}finally{try{H&&!H.done&&(l=N.return)&&l.call(N)}finally{if(s)throw s.error}}v._index.set(M,L)}}catch(ne){o={error:ne}}finally{try{Z&&!Z.done&&(a=R.return)&&a.call(R)}finally{if(o)throw o.error}}return v},e.prototype.executeQuery=function(n,t){var r=this;if(t===void 0&&(t={}),n===e.wildcard)return this.executeWildcardQuery(t);if(typeof n!="string"){var i=J(J(J({},t),n),{queries:void 0}),o=n.queries.map(function(k){return r.executeQuery(k,i)});return this.combineResults(o,i.combineWith)}var a=this._options,s=a.tokenize,l=a.processTerm,c=a.searchOptions,u=J(J({tokenize:s,processTerm:l},c),t),p=u.tokenize,d=u.processTerm,h=p(n).flatMap(function(k){return d(k)}).filter(function(k){return!!k}),g=h.map(sl(u)),w=g.map(function(k){return r.executeQuerySpec(k,u)});return this.combineResults(w,u.combineWith)},e.prototype.executeQuerySpec=function(n,t){var r,i,o,a,s=J(J({},this._options.searchOptions),t),l=(s.fields||this._options.fields).reduce(function(Y,re){var ne;return J(J({},Y),(ne={},ne[re]=xr(s.boost,re)||1,ne))},{}),c=s.boostDocument,u=s.weights,p=s.maxFuzzy,d=s.bm25,h=J(J({},ji.weights),u),g=h.fuzzy,w=h.prefix,k=this._index.get(n.term),y=this.termResults(n.term,n.term,1,k,l,c,d),I,v;if(n.prefix&&(I=this._index.atPrefix(n.term)),n.fuzzy){var z=n.fuzzy===!0?.2:n.fuzzy,P=z<1?Math.min(p,Math.round(n.term.length*z)):z;P&&(v=this._index.fuzzyGet(n.term,P))}if(I)try{for(var x=X(I),A=x.next();!A.done;A=x.next()){var F=$(A.value,2),R=F[0],Z=F[1],D=R.length-n.term.length;if(D){v?.delete(R);var M=w*R.length/(R.length+.3*D);this.termResults(n.term,R,M,Z,l,c,d,y)}}}catch(Y){r={error:Y}}finally{try{A&&!A.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}if(v)try{for(var C=X(v.keys()),L=C.next();!L.done;L=C.next()){var R=L.value,N=$(v.get(R),2),H=N[0],D=N[1];if(D){var M=g*R.length/(R.length+D);this.termResults(n.term,R,M,H,l,c,d,y)}}}catch(Y){o={error:Y}}finally{try{L&&!L.done&&(a=C.return)&&a.call(C)}finally{if(o)throw o.error}}return y},e.prototype.executeWildcardQuery=function(n){var t,r,i=new Map,o=J(J({},this._options.searchOptions),n);try{for(var a=X(this._documentIds),s=a.next();!s.done;s=a.next()){var l=$(s.value,2),c=l[0],u=l[1],p=o.boostDocument?o.boostDocument(u,"",this._storedFields.get(c)):1;i.set(c,{score:p,terms:[],match:{}})}}catch(d){t={error:d}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return i},e.prototype.combineResults=function(n,t){if(t===void 0&&(t=Cr),n.length===0)return new Map;var r=t.toLowerCase();return n.reduce(il[r])||new Map},e.prototype.toJSON=function(){var n,t,r,i,o=[];try{for(var a=X(this._index),s=a.next();!s.done;s=a.next()){var l=$(s.value,2),c=l[0],u=l[1],p={};try{for(var d=(r=void 0,X(u)),h=d.next();!h.done;h=d.next()){var g=$(h.value,2),w=g[0],k=g[1];p[w]=Object.fromEntries(k)}}catch(y){r={error:y}}finally{try{h&&!h.done&&(i=d.return)&&i.call(d)}finally{if(r)throw r.error}}o.push([c,p])}}catch(y){n={error:y}}finally{try{s&&!s.done&&(t=a.return)&&t.call(a)}finally{if(n)throw n.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:o,serializationVersion:2}},e.prototype.termResults=function(n,t,r,i,o,a,s,l){var c,u,p,d,h;if(l===void 0&&(l=new Map),i==null)return l;try{for(var g=X(Object.keys(o)),w=g.next();!w.done;w=g.next()){var k=w.value,y=o[k],I=this._fieldIds[k],v=i.get(I);if(v!=null){var z=v.size,P=this._avgFieldLength[I];try{for(var x=(p=void 0,X(v.keys())),A=x.next();!A.done;A=x.next()){var F=A.value;if(!this._documentIds.has(F)){this.removeTerm(I,F,t),z-=1;continue}var R=a?a(this._documentIds.get(F),t,this._storedFields.get(F)):1;if(R){var Z=v.get(F),D=this._fieldLength.get(F)[I],M=al(Z,z,this._documentCount,D,P,s),C=r*y*R*M,L=l.get(F);if(L){L.score+=C,ul(L.terms,n);var N=xr(L.match,t);N?N.push(k):L.match[t]=[k]}else l.set(F,{score:C,terms:[n],match:(h={},h[t]=[k],h)})}}}catch(H){p={error:H}}finally{try{A&&!A.done&&(d=x.return)&&d.call(x)}finally{if(p)throw p.error}}}}}catch(H){c={error:H}}finally{try{w&&!w.done&&(u=g.return)&&u.call(g)}finally{if(c)throw c.error}}return l},e.prototype.addTerm=function(n,t,r){var i=this._index.fetch(r,qi),o=i.get(n);if(o==null)o=new Map,o.set(t,1),i.set(n,o);else{var a=o.get(t);o.set(t,(a||0)+1)}},e.prototype.removeTerm=function(n,t,r){if(!this._index.has(r)){this.warnDocumentChanged(t,n,r);return}var i=this._index.fetch(r,qi),o=i.get(n);o==null||o.get(t)==null?this.warnDocumentChanged(t,n,r):o.get(t)<=1?o.size<=1?i.delete(n):o.delete(t):o.set(t,o.get(t)-1),this._index.get(r).size===0&&this._index.delete(r)},e.prototype.warnDocumentChanged=function(n,t,r){var i,o;try{for(var a=X(Object.keys(this._fieldIds)),s=a.next();!s.done;s=a.next()){var l=s.value;if(this._fieldIds[l]===t){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(n),' has changed before removal: term "').concat(r,'" was not present in field "').concat(l,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(c){i={error:c}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(i)throw i.error}}},e.prototype.addDocumentId=function(n){var t=this._nextId;return this._idToShortId.set(n,t),this._documentIds.set(t,n),this._documentCount+=1,this._nextId+=1,t},e.prototype.addFields=function(n){for(var t=0;t<n.length;t++)this._fieldIds[n[t]]=t},e.prototype.addFieldLength=function(n,t,r,i){var o=this._fieldLength.get(n);o==null&&this._fieldLength.set(n,o=[]),o[t]=i;var a=this._avgFieldLength[t]||0,s=a*r+i;this._avgFieldLength[t]=s/(r+1)},e.prototype.removeFieldLength=function(n,t,r,i){if(r===1){this._avgFieldLength[t]=0;return}var o=this._avgFieldLength[t]*r-i;this._avgFieldLength[t]=o/(r-1)},e.prototype.saveStoredFields=function(n,t){var r,i,o=this._options,a=o.storeFields,s=o.extractField;if(!(a==null||a.length===0)){var l=this._storedFields.get(n);l==null&&this._storedFields.set(n,l={});try{for(var c=X(a),u=c.next();!u.done;u=c.next()){var p=u.value,d=s(t,p);d!==void 0&&(l[p]=d)}}catch(h){r={error:h}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(r)throw r.error}}}},e.wildcard=Symbol("*"),e}(),xr=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0},il=(kt={},kt[Cr]=function(e,n){var t,r;try{for(var i=X(n.keys()),o=i.next();!o.done;o=i.next()){var a=o.value,s=e.get(a);if(s==null)e.set(a,n.get(a));else{var l=n.get(a),c=l.score,u=l.terms,p=l.match;s.score=s.score+c,s.match=Object.assign(s.match,p),Ji(s.terms,u)}}}catch(d){t={error:d}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return e},kt[io]=function(e,n){var t,r,i=new Map;try{for(var o=X(n.keys()),a=o.next();!a.done;a=o.next()){var s=a.value,l=e.get(s);if(l!=null){var c=n.get(s),u=c.score,p=c.terms,d=c.match;Ji(l.terms,p),i.set(s,{score:l.score+u,terms:l.terms,match:Object.assign(l.match,d)})}}}catch(h){t={error:h}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return i},kt[rl]=function(e,n){var t,r;try{for(var i=X(n.keys()),o=i.next();!o.done;o=i.next()){var a=o.value;e.delete(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return e},kt),ol={k:1.2,b:.7,d:.5},al=function(e,n,t,r,i,o){var a=o.k,s=o.b,l=o.d,c=Math.log(1+(t-n+.5)/(n+.5));return c*(l+e*(a+1)/(e+a*(1-s+s*r/i)))},sl=function(e){return function(n,t,r){var i=typeof e.fuzzy=="function"?e.fuzzy(n,t,r):e.fuzzy||!1,o=typeof e.prefix=="function"?e.prefix(n,t,r):e.prefix===!0;return{term:n,fuzzy:i,prefix:o}}},br={idField:"id",extractField:function(e,n){return e[n]},tokenize:function(e){return e.split(cl)},processTerm:function(e){return e.toLowerCase()},fields:void 0,searchOptions:void 0,storeFields:[],logger:function(e,n){typeof console?.[e]=="function"&&console[e](n)},autoVacuum:!0},ji={combineWith:Cr,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:ol},ll={combineWith:io,prefix:function(e,n,t){return n===t.length-1}},kr={batchSize:1e3,batchWait:10},Sr={minDirtFactor:.1,minDirtCount:20},wr=J(J({},kr),Sr),ul=function(e,n){e.includes(n)||e.push(n)},Ji=function(e,n){var t,r;try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;e.includes(a)||e.push(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},Qi=function(e,n){var t=e.score,r=n.score;return r-t},qi=function(){return new Map},$t=function(e){var n,t,r=new Map;try{for(var i=X(Object.keys(e)),o=i.next();!o.done;o=i.next()){var a=o.value;r.set(parseInt(a,10),e[a])}}catch(s){n={error:s}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(n)throw n.error}}return r},cl=/[\n\r -#%-*,-/:;?@[-\]_{}\u00A0\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]+/u;var ao=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,n)=>{let t=await n.knowledgeBase.search(e.query),r=n;r._lastKBsearch=e.query,r._nextRequestUseKBitems=t,n.submitAnalyticsEvent({type:"kb-search",query:e.query,results:t});let i=t.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=t.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${o}.`}}];var Ke=new U("KnowledgeBase"),so=1,tn=class e{constructor(n){this._sources=[{id:"core.internal",query:async()=>ao}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=n}registerSource(n,t){let r=n;return typeof n=="function"&&(t=n,r=`source.${so++}`),this._sources.push({id:r,query:t}),r}removeSource(n){this._sources=this.sources.filter(t=>t.id!==n&&t.query!==n)}addEntry(n){this.manualEntries.push(n)}removeEntry(n){this.manualEntries=this.manualEntries.filter(t=>t.id!==n)}get sources(){let n=this._sources;return typeof window<"u"&&Q().knowledgeBaseSources&&(n=n.concat(Q().knowledgeBaseSources.map(t=>({id:t.name,query:t})))),n=n.concat(this._windowSources),n=n.filter(t=>!t.disabled),n}async search(n){Ke.debug(`Searching knowledge base for: ${n}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=n,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let i=(await Promise.all(this.sources.map(async l=>{try{let c=Date.now(),u=await l.query(n);return Ke.debug(`Source '${l.id}' took ${Date.now()-c}ms`),u||[]}catch(c){return Ke.warn(`Knowledge source '${l.id}' failed:`,c),[]}}))).flat();i=i.concat(t.entries),i=i.concat(this.manualEntries),Q().knowledgeBase&&(i=i.concat(Q().knowledgeBase)),i=i.filter(l=>l&&!l.disabled);for(let l=0;l<i.length;l++){let c=i[l];if(c.id=c.id||`temp.${l}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!c.action&&c.type=="tour"&&(c.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!c.action&&c.type=="info"&&(c.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),c.parameters&&!Array.isArray(c.parameters)){let u=c.parameters,p=[];for(let d in u)p.push({name:d,type:"string",description:c.parameters[d]});c.parameters=p}}let o=new oo({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let s=o.search(n).map(l=>i.find(c=>c.id==l.id));for(let l of i)l.isContext&&(s.find(c=>c.id===l.id)||s.push(l));return this.lastResults=s,Ke.debug("Found results:",s),s}getCachedEntry(n){return this.lastResults.find(t=>t.id==n||t._functionID==n)}registerSourceFromURL(n,t){t||(t=`external.${so++}`),Ke.debug(`Registering remote knowledge base source: ${n}`);let r=[],i=[],o=!0,a=async(l,c)=>{Ke.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:c},p=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw new Error(`HTTP Error ${p.status} ${p.statusText}`);let d=await p.json();return s(d.updateItems||[]),d.response},s=l=>{for(let c of l){if(!c.id){Ke.warn("KB item skipped since it has no ID.",c);continue}let u=r.find(p=>p.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}r.push({...c,action:p=>a(c,p)})}};this.registerSource(t,async l=>{if(o&&i.includes(l))return r;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:l},u=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return o=!p.noCache,i.includes(l)||i.push(l),s(p.items),r})}clone(){let n=new e(this.ai);return n._sources=this._sources,n._windowSources=this._windowSources,n.manualEntries=this.manualEntries,n}};var lo={name:"@intelliweave/embedded",version:"1.6.53",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var nn=class{constructor(n){this.ai=n}async boolean(n,t){let r=this.ai.clone();r.resetConversation(),r.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let i=await r.sendMessage(n+`
9
+ `,yield*t()}function Yi(){if(Q().userID)return Q().userID;if(typeof localStorage<"u"){let e=localStorage.getItem("intelliweave.uid")||"";return e||(e=Ue(),localStorage.setItem("intelliweave.uid",e),e)}else return Ue()}var Qt=class Qt{constructor(n){this.module="IntelliWeave";this.module=n}get debugEnabled(){return Qt.debug?!0:typeof window<"u"&&Q().debug}log(...n){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...n)}debug(...n){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...n)}info(...n){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...n)}warn(...n){console.warn(`[IntelliWeave > ${this.module}]`,...n)}error(...n){console.error(`[IntelliWeave > ${this.module}]`,...n)}timer(n,...t){let r=Date.now();return this.debug(`[${n} 0ms] Started`,...t),(...i)=>this.debug(`[${n} ${Math.floor(Date.now()-r)}ms]`,...i)}};Qt.debug=!1;var U=Qt;var Pe=new U("ChatGPT"),qt=class{constructor(n){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...n}}async sendMessage(n){this.messages.push({role:"user",content:n}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let t=this.messages[this.messages.length-1];return t?.role=="assistant"&&t.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),Pe.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let n=this.messages[this.messages.length-1];if(n?.role=="user"||n?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(n?.role=="assistant"&&n?.tool_calls?.length){for(let t of n.tool_calls)await this.processToolCall(t);await this.processMessages()}}async trimMessages(){for(;;){let n=await this.sendToAPI(!0);if(JSON.stringify(n).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){Pe.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(n){let t=0;for(let l=this.messages.length-1;l>=0;l--)if(this.messages[l].role=="assistant"&&this.messages[l].tool_calls){if(t+=1,t>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[l].role=="user")break;Pe.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let r={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let l of this.tools){l.description&&l.description.length>1024&&Pe.warn(`Tool description for "${l.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:l.name,description:(l.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(l.params))for(let u of l.params)c.function.parameters.properties[u.name]={type:u.type,description:u.description};else if(l.params){let u=l.params;for(let p in u)c.function.parameters.properties[p]={type:"string",description:u[p]}}r.tools.push(c)}r.user||delete r.user,r.tools.length||delete r.tools;let i={};if(i["Content-Type"]="application/json",this.config.apiKey&&(i.Authorization=`Bearer ${this.config.apiKey}`),n)return r;let o=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(r)});if(!o.ok){let l=`${o.status} ${o.statusText}`;try{let u=await o.json();l=u.errorText||u.error?.message||u.error||l}catch{}let c=new Error(l);throw c.code=o.status,c}let a=null,s=null;if(this.config.stream)for await(let l of Ki(o.body)){if(l.data=="[DONE]")break;if(!l.data)continue;let c=JSON.parse(l.data);if(s){for(let u in c.choices[0].delta)if(typeof c.choices[0].delta[u]=="string"){if(u=="role"&&s[u]==c.choices[0].delta[u])continue;s[u]=(s[u]||"")+c.choices[0].delta[u]}for(let u of c.choices[0].delta.tool_calls||[]){if(s.tool_calls||(s.tool_calls=[]),!s.tool_calls[u.index]){s.tool_calls[u.index]=u;continue}let p=s.tool_calls[u.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(u.function?.name||""),p.function.arguments=(p.function.arguments||"")+(u.function?.arguments||"")}}else s={chunkID:c.id,...c.choices[0].delta};s?.content&&!s.content.startsWith("{")&&this.config.onAIMessage?.(s.content,!0)}else a=await o.json(),this.stats.tokensUsed+=a.usage?.total_tokens||0,Pe.debug(`Used ${a.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),s=a.choices?.[0]?.message;if(s||(Pe.warn("No response block in API response."),s={role:"assistant",content:""}),s.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(s),this.messages.push(s),s.content&&this.config.onAIMessage?.(s.content,!1)}processIncomingMessage(n){}registerTool(n){this.tools.push(n)}async processToolCall(n){try{let t=this.tools.find(o=>o.name==n.function.name);if(!t)throw new Error(`Tool "${n.function.name}" not found.`);let r=JSON.parse(n.function.arguments);this.config.onAIToolStart?.(n.function.name,r);let i=await t.callback(r);if(typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&t.removeFromMessageHistory){Pe.debug(`Removing tool call history for "${t.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(o=>o.role!="assistant"||!o.tool_calls?.find(a=>a.id==n.id));return}else t.removeFromMessageHistory&&Pe.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${t.name}"`);this.messages.push({role:"tool",content:i,tool_call_id:n.id})}catch(t){Pe.warn(`Unable to process tool call for "${n?.function?.name}"`,t),this.messages.push({role:"tool",content:`Error: ${t.message}`,tool_call_id:n.id})}}resetConversation(){this.messages=[]}};var J=function(){return J=Object.assign||function(n){for(var t,r=1,i=arguments.length;r<i;r++){t=arguments[r];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(n[o]=t[o])}return n},J.apply(this,arguments)};function qs(e,n,t,r){function i(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function s(u){try{c(r.next(u))}catch(p){a(p)}}function l(u){try{c(r.throw(u))}catch(p){a(p)}}function c(u){u.done?o(u.value):i(u.value).then(s,l)}c((r=r.apply(e,n||[])).next())})}function $s(e,n){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,c[0]&&(t=0)),t;)try{if(r=1,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,i=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){t.label=c[1];break}if(c[0]===6&&t.label<o[1]){t.label=o[1],o=c;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(c);break}o[2]&&t.ops.pop(),t.trys.pop();continue}c=n.call(e,t)}catch(u){c=[6,u],i=0}finally{r=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function X(e){var n=typeof Symbol=="function"&&Symbol.iterator,t=n&&e[n],r=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function $(e,n){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var r=t.call(e),i,o=[],a;try{for(;(n===void 0||n-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(s){a={error:s}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o}var el="ENTRIES",$i="KEYS",eo="VALUES",le="",mr=function(){function e(n,t){var r=n._tree,i=Array.from(r.keys());this.set=n,this._type=t,this._path=i.length>0?[{node:r,keys:i}]:[]}return e.prototype.next=function(){var n=this.dive();return this.backtrack(),n},e.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var n=at(this._path),t=n.node,r=n.keys;if(at(r)===le)return{done:!1,value:this.result()};var i=t.get(at(r));return this._path.push({node:i,keys:Array.from(i.keys())}),this.dive()},e.prototype.backtrack=function(){if(this._path.length!==0){var n=at(this._path).keys;n.pop(),!(n.length>0)&&(this._path.pop(),this.backtrack())}},e.prototype.key=function(){return this.set._prefix+this._path.map(function(n){var t=n.keys;return at(t)}).filter(function(n){return n!==le}).join("")},e.prototype.value=function(){return at(this._path).node.get(le)},e.prototype.result=function(){switch(this._type){case eo:return this.value();case $i:return this.key();default:return[this.key(),this.value()]}},e.prototype[Symbol.iterator]=function(){return this},e}(),at=function(e){return e[e.length-1]},tl=function(e,n,t){var r=new Map;if(n===void 0)return r;for(var i=n.length+1,o=i+t,a=new Uint8Array(o*i).fill(t+1),s=0;s<i;++s)a[s]=s;for(var l=1;l<o;++l)a[l*i]=l;return to(e,n,t,r,a,1,i,""),r},to=function(e,n,t,r,i,o,a,s){var l,c,u=o*a;try{e:for(var p=X(e.keys()),d=p.next();!d.done;d=p.next()){var h=d.value;if(h===le){var g=i[u-1];g<=t&&r.set(s,[e.get(h),g])}else{for(var w=o,k=0;k<h.length;++k,++w){for(var y=h[k],I=a*w,v=I-a,z=i[I],P=Math.max(0,w-t-1),x=Math.min(a-1,w+t),A=P;A<x;++A){var F=y!==n[A],R=i[v+A]+ +F,Z=i[v+A+1]+1,D=i[I+A]+1,M=i[I+A+1]=Math.min(R,Z,D);M<z&&(z=M)}if(z>t)continue e}to(e.get(h),n,t,r,i,w,a,s+h)}}}catch(C){l={error:C}}finally{try{d&&!d.done&&(c=p.return)&&c.call(p)}finally{if(l)throw l.error}}},gr=function(){function e(n,t){n===void 0&&(n=new Map),t===void 0&&(t=""),this._size=void 0,this._tree=n,this._prefix=t}return e.prototype.atPrefix=function(n){var t,r;if(!n.startsWith(this._prefix))throw new Error("Mismatched prefix");var i=$(en(this._tree,n.slice(this._prefix.length)),2),o=i[0],a=i[1];if(o===void 0){var s=$(Er(a),2),l=s[0],c=s[1];try{for(var u=X(l.keys()),p=u.next();!p.done;p=u.next()){var d=p.value;if(d!==le&&d.startsWith(c)){var h=new Map;return h.set(d.slice(c.length),l.get(d)),new e(h,n)}}}catch(g){t={error:g}}finally{try{p&&!p.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}}return new e(o,n)},e.prototype.clear=function(){this._size=void 0,this._tree.clear()},e.prototype.delete=function(n){return this._size=void 0,nl(this._tree,n)},e.prototype.entries=function(){return new mr(this,el)},e.prototype.forEach=function(n){var t,r;try{for(var i=X(this),o=i.next();!o.done;o=i.next()){var a=$(o.value,2),s=a[0],l=a[1];n(s,l,this)}}catch(c){t={error:c}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},e.prototype.fuzzyGet=function(n,t){return tl(this._tree,n,t)},e.prototype.get=function(n){var t=vr(this._tree,n);return t!==void 0?t.get(le):void 0},e.prototype.has=function(n){var t=vr(this._tree,n);return t!==void 0&&t.has(le)},e.prototype.keys=function(){return new mr(this,$i)},e.prototype.set=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n);return r.set(le,t),this},Object.defineProperty(e.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var n=this.entries();!n.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),e.prototype.update=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n);return r.set(le,t(r.get(le))),this},e.prototype.fetch=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n),i=r.get(le);return i===void 0&&r.set(le,i=t()),i},e.prototype.values=function(){return new mr(this,eo)},e.prototype[Symbol.iterator]=function(){return this.entries()},e.from=function(n){var t,r,i=new e;try{for(var o=X(n),a=o.next();!a.done;a=o.next()){var s=$(a.value,2),l=s[0],c=s[1];i.set(l,c)}}catch(u){t={error:u}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return i},e.fromObject=function(n){return e.from(Object.entries(n))},e}(),en=function(e,n,t){var r,i;if(t===void 0&&(t=[]),n.length===0||e==null)return[e,t];try{for(var o=X(e.keys()),a=o.next();!a.done;a=o.next()){var s=a.value;if(s!==le&&n.startsWith(s))return t.push([e,s]),en(e.get(s),n.slice(s.length),t)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}return t.push([e,n]),en(void 0,"",t)},vr=function(e,n){var t,r;if(n.length===0||e==null)return e;try{for(var i=X(e.keys()),o=i.next();!o.done;o=i.next()){var a=o.value;if(a!==le&&n.startsWith(a))return vr(e.get(a),n.slice(a.length))}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},yr=function(e,n){var t,r,i=n.length;e:for(var o=0;e&&o<i;){try{for(var a=(t=void 0,X(e.keys())),s=a.next();!s.done;s=a.next()){var l=s.value;if(l!==le&&n[o]===l[0]){for(var c=Math.min(i-o,l.length),u=1;u<c&&n[o+u]===l[u];)++u;var p=e.get(l);if(u===l.length)e=p;else{var d=new Map;d.set(l.slice(u),p),e.set(n.slice(o,o+u),d),e.delete(l),e=d}o+=u;continue e}}}catch(g){t={error:g}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}var h=new Map;return e.set(n.slice(o),h),h}return e},nl=function(e,n){var t=$(en(e,n),2),r=t[0],i=t[1];if(r!==void 0){if(r.delete(le),r.size===0)no(i);else if(r.size===1){var o=$(r.entries().next().value,2),a=o[0],s=o[1];ro(i,a,s)}}},no=function(e){if(e.length!==0){var n=$(Er(e),2),t=n[0],r=n[1];if(t.delete(r),t.size===0)no(e.slice(0,-1));else if(t.size===1){var i=$(t.entries().next().value,2),o=i[0],a=i[1];o!==le&&ro(e.slice(0,-1),o,a)}}},ro=function(e,n,t){if(e.length!==0){var r=$(Er(e),2),i=r[0],o=r[1];i.set(o+n,t),i.delete(o)}},Er=function(e){return e[e.length-1]},kt,Cr="or",io="and",rl="and_not",oo=function(){function e(n){if(n?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');var t=n.autoVacuum==null||n.autoVacuum===!0?wr:n.autoVacuum;this._options=J(J(J({},br),n),{autoVacuum:t,searchOptions:J(J({},ji),n.searchOptions||{}),autoSuggestOptions:J(J({},ll),n.autoSuggestOptions||{})}),this._index=new gr,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Sr,this.addFields(this._options.fields)}return e.prototype.add=function(n){var t,r,i,o,a,s,l=this._options,c=l.extractField,u=l.tokenize,p=l.processTerm,d=l.fields,h=l.idField,g=c(n,h);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(h,'"'));if(this._idToShortId.has(g))throw new Error("MiniSearch: duplicate ID ".concat(g));var w=this.addDocumentId(g);this.saveStoredFields(w,n);try{for(var k=X(d),y=k.next();!y.done;y=k.next()){var I=y.value,v=c(n,I);if(v!=null){var z=u(v.toString(),I),P=this._fieldIds[I],x=new Set(z).size;this.addFieldLength(w,P,this._documentCount-1,x);try{for(var A=(i=void 0,X(z)),F=A.next();!F.done;F=A.next()){var R=F.value,Z=p(R,I);if(Array.isArray(Z))try{for(var D=(a=void 0,X(Z)),M=D.next();!M.done;M=D.next()){var C=M.value;this.addTerm(P,w,C)}}catch(L){a={error:L}}finally{try{M&&!M.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else Z&&this.addTerm(P,w,Z)}}catch(L){i={error:L}}finally{try{F&&!F.done&&(o=A.return)&&o.call(A)}finally{if(i)throw i.error}}}}}catch(L){t={error:L}}finally{try{y&&!y.done&&(r=k.return)&&r.call(k)}finally{if(t)throw t.error}}},e.prototype.addAll=function(n){var t,r;try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;this.add(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},e.prototype.addAllAsync=function(n,t){var r=this;t===void 0&&(t={});var i=t.chunkSize,o=i===void 0?10:i,a={chunk:[],promise:Promise.resolve()},s=n.reduce(function(u,p,d){var h=u.chunk,g=u.promise;return h.push(p),(d+1)%o===0?{chunk:[],promise:g.then(function(){return new Promise(function(w){return setTimeout(w,0)})}).then(function(){return r.addAll(h)})}:{chunk:h,promise:g}},a),l=s.chunk,c=s.promise;return c.then(function(){return r.addAll(l)})},e.prototype.remove=function(n){var t,r,i,o,a,s,l=this._options,c=l.tokenize,u=l.processTerm,p=l.extractField,d=l.fields,h=l.idField,g=p(n,h);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(h,'"'));var w=this._idToShortId.get(g);if(w==null)throw new Error("MiniSearch: cannot remove document with ID ".concat(g,": it is not in the index"));try{for(var k=X(d),y=k.next();!y.done;y=k.next()){var I=y.value,v=p(n,I);if(v!=null){var z=c(v.toString(),I),P=this._fieldIds[I],x=new Set(z).size;this.removeFieldLength(w,P,this._documentCount,x);try{for(var A=(i=void 0,X(z)),F=A.next();!F.done;F=A.next()){var R=F.value,Z=u(R,I);if(Array.isArray(Z))try{for(var D=(a=void 0,X(Z)),M=D.next();!M.done;M=D.next()){var C=M.value;this.removeTerm(P,w,C)}}catch(L){a={error:L}}finally{try{M&&!M.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else Z&&this.removeTerm(P,w,Z)}}catch(L){i={error:L}}finally{try{F&&!F.done&&(o=A.return)&&o.call(A)}finally{if(i)throw i.error}}}}}catch(L){t={error:L}}finally{try{y&&!y.done&&(r=k.return)&&r.call(k)}finally{if(t)throw t.error}}this._storedFields.delete(w),this._documentIds.delete(w),this._idToShortId.delete(g),this._fieldLength.delete(w),this._documentCount-=1},e.prototype.removeAll=function(n){var t,r;if(n)try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;this.remove(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new gr,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},e.prototype.discard=function(n){var t=this,r=this._idToShortId.get(n);if(r==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(n,": it is not in the index"));this._idToShortId.delete(n),this._documentIds.delete(r),this._storedFields.delete(r),(this._fieldLength.get(r)||[]).forEach(function(i,o){t.removeFieldLength(r,o,t._documentCount,i)}),this._fieldLength.delete(r),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},e.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var n=this._options.autoVacuum,t=n.minDirtFactor,r=n.minDirtCount,i=n.batchSize,o=n.batchWait;this.conditionalVacuum({batchSize:i,batchWait:o},{minDirtCount:r,minDirtFactor:t})}},e.prototype.discardAll=function(n){var t,r,i=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var o=X(n),a=o.next();!a.done;a=o.next()){var s=a.value;this.discard(s)}}catch(l){t={error:l}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}}finally{this._options.autoVacuum=i}this.maybeAutoVacuum()},e.prototype.replace=function(n){var t=this._options,r=t.idField,i=t.extractField,o=i(n,r);this.discard(o),this.add(n)},e.prototype.vacuum=function(n){return n===void 0&&(n={}),this.conditionalVacuum(n)},e.prototype.conditionalVacuum=function(n,t){var r=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&t,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var i=r._enqueuedVacuumConditions;return r._enqueuedVacuumConditions=Sr,r.performVacuuming(n,i)}),this._enqueuedVacuum)):this.vacuumConditionsMet(t)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(n),this._currentVacuum)},e.prototype.performVacuuming=function(n,t){return qs(this,void 0,void 0,function(){var r,i,o,a,s,l,c,u,p,d,h,g,w,k,y,I,v,z,P,x,A,F,R,Z,D;return $s(this,function(M){switch(M.label){case 0:if(r=this._dirtCount,!this.vacuumConditionsMet(t))return[3,10];i=n.batchSize||kr.batchSize,o=n.batchWait||kr.batchWait,a=1,M.label=1;case 1:M.trys.push([1,7,8,9]),s=X(this._index),l=s.next(),M.label=2;case 2:if(l.done)return[3,6];c=$(l.value,2),u=c[0],p=c[1];try{for(d=(F=void 0,X(p)),h=d.next();!h.done;h=d.next()){g=$(h.value,2),w=g[0],k=g[1];try{for(y=(Z=void 0,X(k)),I=y.next();!I.done;I=y.next())v=$(I.value,1),z=v[0],!this._documentIds.has(z)&&(k.size<=1?p.delete(w):k.delete(z))}catch(C){Z={error:C}}finally{try{I&&!I.done&&(D=y.return)&&D.call(y)}finally{if(Z)throw Z.error}}}}catch(C){F={error:C}}finally{try{h&&!h.done&&(R=d.return)&&R.call(d)}finally{if(F)throw F.error}}return this._index.get(u).size===0&&this._index.delete(u),a%i!==0?[3,4]:[4,new Promise(function(C){return setTimeout(C,o)})];case 3:M.sent(),M.label=4;case 4:a+=1,M.label=5;case 5:return l=s.next(),[3,2];case 6:return[3,9];case 7:return P=M.sent(),x={error:P},[3,9];case 8:try{l&&!l.done&&(A=s.return)&&A.call(s)}finally{if(x)throw x.error}return[7];case 9:this._dirtCount-=r,M.label=10;case 10:return[4,null];case 11:return M.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},e.prototype.vacuumConditionsMet=function(n){if(n==null)return!0;var t=n.minDirtCount,r=n.minDirtFactor;return t=t||wr.minDirtCount,r=r||wr.minDirtFactor,this.dirtCount>=t&&this.dirtFactor>=r},Object.defineProperty(e.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),e.prototype.has=function(n){return this._idToShortId.has(n)},e.prototype.getStoredFields=function(n){var t=this._idToShortId.get(n);if(t!=null)return this._storedFields.get(t)},e.prototype.search=function(n,t){var r,i;t===void 0&&(t={});var o=this.executeQuery(n,t),a=[];try{for(var s=X(o),l=s.next();!l.done;l=s.next()){var c=$(l.value,2),u=c[0],p=c[1],d=p.score,h=p.terms,g=p.match,w=h.length||1,k={id:this._documentIds.get(u),score:d*w,terms:Object.keys(g),queryTerms:h,match:g};Object.assign(k,this._storedFields.get(u)),(t.filter==null||t.filter(k))&&a.push(k)}}catch(y){r={error:y}}finally{try{l&&!l.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return n===e.wildcard&&t.boostDocument==null&&this._options.searchOptions.boostDocument==null||a.sort(Qi),a},e.prototype.autoSuggest=function(n,t){var r,i,o,a;t===void 0&&(t={}),t=J(J({},this._options.autoSuggestOptions),t);var s=new Map;try{for(var l=X(this.search(n,t)),c=l.next();!c.done;c=l.next()){var u=c.value,p=u.score,d=u.terms,h=d.join(" "),g=s.get(h);g!=null?(g.score+=p,g.count+=1):s.set(h,{score:p,terms:d,count:1})}}catch(P){r={error:P}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(r)throw r.error}}var w=[];try{for(var k=X(s),y=k.next();!y.done;y=k.next()){var I=$(y.value,2),g=I[0],v=I[1],p=v.score,d=v.terms,z=v.count;w.push({suggestion:g,terms:d,score:p/z})}}catch(P){o={error:P}}finally{try{y&&!y.done&&(a=k.return)&&a.call(k)}finally{if(o)throw o.error}}return w.sort(Qi),w},Object.defineProperty(e.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),e.loadJSON=function(n,t){if(t==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(n),t)},e.getDefault=function(n){if(br.hasOwnProperty(n))return xr(br,n);throw new Error('MiniSearch: unknown option "'.concat(n,'"'))},e.loadJS=function(n,t){var r,i,o,a,s,l,c=n.index,u=n.documentCount,p=n.nextId,d=n.documentIds,h=n.fieldIds,g=n.fieldLength,w=n.averageFieldLength,k=n.storedFields,y=n.dirtCount,I=n.serializationVersion;if(I!==1&&I!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var v=new e(t);v._documentCount=u,v._nextId=p,v._documentIds=$t(d),v._idToShortId=new Map,v._fieldIds=h,v._fieldLength=$t(g),v._avgFieldLength=w,v._storedFields=$t(k),v._dirtCount=y||0,v._index=new gr;try{for(var z=X(v._documentIds),P=z.next();!P.done;P=z.next()){var x=$(P.value,2),A=x[0],F=x[1];v._idToShortId.set(F,A)}}catch(ne){r={error:ne}}finally{try{P&&!P.done&&(i=z.return)&&i.call(z)}finally{if(r)throw r.error}}try{for(var R=X(c),Z=R.next();!Z.done;Z=R.next()){var D=$(Z.value,2),M=D[0],C=D[1],L=new Map;try{for(var N=(s=void 0,X(Object.keys(C))),H=N.next();!H.done;H=N.next()){var Y=H.value,re=C[Y];I===1&&(re=re.ds),L.set(parseInt(Y,10),$t(re))}}catch(ne){s={error:ne}}finally{try{H&&!H.done&&(l=N.return)&&l.call(N)}finally{if(s)throw s.error}}v._index.set(M,L)}}catch(ne){o={error:ne}}finally{try{Z&&!Z.done&&(a=R.return)&&a.call(R)}finally{if(o)throw o.error}}return v},e.prototype.executeQuery=function(n,t){var r=this;if(t===void 0&&(t={}),n===e.wildcard)return this.executeWildcardQuery(t);if(typeof n!="string"){var i=J(J(J({},t),n),{queries:void 0}),o=n.queries.map(function(k){return r.executeQuery(k,i)});return this.combineResults(o,i.combineWith)}var a=this._options,s=a.tokenize,l=a.processTerm,c=a.searchOptions,u=J(J({tokenize:s,processTerm:l},c),t),p=u.tokenize,d=u.processTerm,h=p(n).flatMap(function(k){return d(k)}).filter(function(k){return!!k}),g=h.map(sl(u)),w=g.map(function(k){return r.executeQuerySpec(k,u)});return this.combineResults(w,u.combineWith)},e.prototype.executeQuerySpec=function(n,t){var r,i,o,a,s=J(J({},this._options.searchOptions),t),l=(s.fields||this._options.fields).reduce(function(Y,re){var ne;return J(J({},Y),(ne={},ne[re]=xr(s.boost,re)||1,ne))},{}),c=s.boostDocument,u=s.weights,p=s.maxFuzzy,d=s.bm25,h=J(J({},ji.weights),u),g=h.fuzzy,w=h.prefix,k=this._index.get(n.term),y=this.termResults(n.term,n.term,1,k,l,c,d),I,v;if(n.prefix&&(I=this._index.atPrefix(n.term)),n.fuzzy){var z=n.fuzzy===!0?.2:n.fuzzy,P=z<1?Math.min(p,Math.round(n.term.length*z)):z;P&&(v=this._index.fuzzyGet(n.term,P))}if(I)try{for(var x=X(I),A=x.next();!A.done;A=x.next()){var F=$(A.value,2),R=F[0],Z=F[1],D=R.length-n.term.length;if(D){v?.delete(R);var M=w*R.length/(R.length+.3*D);this.termResults(n.term,R,M,Z,l,c,d,y)}}}catch(Y){r={error:Y}}finally{try{A&&!A.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}if(v)try{for(var C=X(v.keys()),L=C.next();!L.done;L=C.next()){var R=L.value,N=$(v.get(R),2),H=N[0],D=N[1];if(D){var M=g*R.length/(R.length+D);this.termResults(n.term,R,M,H,l,c,d,y)}}}catch(Y){o={error:Y}}finally{try{L&&!L.done&&(a=C.return)&&a.call(C)}finally{if(o)throw o.error}}return y},e.prototype.executeWildcardQuery=function(n){var t,r,i=new Map,o=J(J({},this._options.searchOptions),n);try{for(var a=X(this._documentIds),s=a.next();!s.done;s=a.next()){var l=$(s.value,2),c=l[0],u=l[1],p=o.boostDocument?o.boostDocument(u,"",this._storedFields.get(c)):1;i.set(c,{score:p,terms:[],match:{}})}}catch(d){t={error:d}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return i},e.prototype.combineResults=function(n,t){if(t===void 0&&(t=Cr),n.length===0)return new Map;var r=t.toLowerCase();return n.reduce(il[r])||new Map},e.prototype.toJSON=function(){var n,t,r,i,o=[];try{for(var a=X(this._index),s=a.next();!s.done;s=a.next()){var l=$(s.value,2),c=l[0],u=l[1],p={};try{for(var d=(r=void 0,X(u)),h=d.next();!h.done;h=d.next()){var g=$(h.value,2),w=g[0],k=g[1];p[w]=Object.fromEntries(k)}}catch(y){r={error:y}}finally{try{h&&!h.done&&(i=d.return)&&i.call(d)}finally{if(r)throw r.error}}o.push([c,p])}}catch(y){n={error:y}}finally{try{s&&!s.done&&(t=a.return)&&t.call(a)}finally{if(n)throw n.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:o,serializationVersion:2}},e.prototype.termResults=function(n,t,r,i,o,a,s,l){var c,u,p,d,h;if(l===void 0&&(l=new Map),i==null)return l;try{for(var g=X(Object.keys(o)),w=g.next();!w.done;w=g.next()){var k=w.value,y=o[k],I=this._fieldIds[k],v=i.get(I);if(v!=null){var z=v.size,P=this._avgFieldLength[I];try{for(var x=(p=void 0,X(v.keys())),A=x.next();!A.done;A=x.next()){var F=A.value;if(!this._documentIds.has(F)){this.removeTerm(I,F,t),z-=1;continue}var R=a?a(this._documentIds.get(F),t,this._storedFields.get(F)):1;if(R){var Z=v.get(F),D=this._fieldLength.get(F)[I],M=al(Z,z,this._documentCount,D,P,s),C=r*y*R*M,L=l.get(F);if(L){L.score+=C,ul(L.terms,n);var N=xr(L.match,t);N?N.push(k):L.match[t]=[k]}else l.set(F,{score:C,terms:[n],match:(h={},h[t]=[k],h)})}}}catch(H){p={error:H}}finally{try{A&&!A.done&&(d=x.return)&&d.call(x)}finally{if(p)throw p.error}}}}}catch(H){c={error:H}}finally{try{w&&!w.done&&(u=g.return)&&u.call(g)}finally{if(c)throw c.error}}return l},e.prototype.addTerm=function(n,t,r){var i=this._index.fetch(r,qi),o=i.get(n);if(o==null)o=new Map,o.set(t,1),i.set(n,o);else{var a=o.get(t);o.set(t,(a||0)+1)}},e.prototype.removeTerm=function(n,t,r){if(!this._index.has(r)){this.warnDocumentChanged(t,n,r);return}var i=this._index.fetch(r,qi),o=i.get(n);o==null||o.get(t)==null?this.warnDocumentChanged(t,n,r):o.get(t)<=1?o.size<=1?i.delete(n):o.delete(t):o.set(t,o.get(t)-1),this._index.get(r).size===0&&this._index.delete(r)},e.prototype.warnDocumentChanged=function(n,t,r){var i,o;try{for(var a=X(Object.keys(this._fieldIds)),s=a.next();!s.done;s=a.next()){var l=s.value;if(this._fieldIds[l]===t){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(n),' has changed before removal: term "').concat(r,'" was not present in field "').concat(l,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(c){i={error:c}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(i)throw i.error}}},e.prototype.addDocumentId=function(n){var t=this._nextId;return this._idToShortId.set(n,t),this._documentIds.set(t,n),this._documentCount+=1,this._nextId+=1,t},e.prototype.addFields=function(n){for(var t=0;t<n.length;t++)this._fieldIds[n[t]]=t},e.prototype.addFieldLength=function(n,t,r,i){var o=this._fieldLength.get(n);o==null&&this._fieldLength.set(n,o=[]),o[t]=i;var a=this._avgFieldLength[t]||0,s=a*r+i;this._avgFieldLength[t]=s/(r+1)},e.prototype.removeFieldLength=function(n,t,r,i){if(r===1){this._avgFieldLength[t]=0;return}var o=this._avgFieldLength[t]*r-i;this._avgFieldLength[t]=o/(r-1)},e.prototype.saveStoredFields=function(n,t){var r,i,o=this._options,a=o.storeFields,s=o.extractField;if(!(a==null||a.length===0)){var l=this._storedFields.get(n);l==null&&this._storedFields.set(n,l={});try{for(var c=X(a),u=c.next();!u.done;u=c.next()){var p=u.value,d=s(t,p);d!==void 0&&(l[p]=d)}}catch(h){r={error:h}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(r)throw r.error}}}},e.wildcard=Symbol("*"),e}(),xr=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0},il=(kt={},kt[Cr]=function(e,n){var t,r;try{for(var i=X(n.keys()),o=i.next();!o.done;o=i.next()){var a=o.value,s=e.get(a);if(s==null)e.set(a,n.get(a));else{var l=n.get(a),c=l.score,u=l.terms,p=l.match;s.score=s.score+c,s.match=Object.assign(s.match,p),Ji(s.terms,u)}}}catch(d){t={error:d}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return e},kt[io]=function(e,n){var t,r,i=new Map;try{for(var o=X(n.keys()),a=o.next();!a.done;a=o.next()){var s=a.value,l=e.get(s);if(l!=null){var c=n.get(s),u=c.score,p=c.terms,d=c.match;Ji(l.terms,p),i.set(s,{score:l.score+u,terms:l.terms,match:Object.assign(l.match,d)})}}}catch(h){t={error:h}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return i},kt[rl]=function(e,n){var t,r;try{for(var i=X(n.keys()),o=i.next();!o.done;o=i.next()){var a=o.value;e.delete(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return e},kt),ol={k:1.2,b:.7,d:.5},al=function(e,n,t,r,i,o){var a=o.k,s=o.b,l=o.d,c=Math.log(1+(t-n+.5)/(n+.5));return c*(l+e*(a+1)/(e+a*(1-s+s*r/i)))},sl=function(e){return function(n,t,r){var i=typeof e.fuzzy=="function"?e.fuzzy(n,t,r):e.fuzzy||!1,o=typeof e.prefix=="function"?e.prefix(n,t,r):e.prefix===!0;return{term:n,fuzzy:i,prefix:o}}},br={idField:"id",extractField:function(e,n){return e[n]},tokenize:function(e){return e.split(cl)},processTerm:function(e){return e.toLowerCase()},fields:void 0,searchOptions:void 0,storeFields:[],logger:function(e,n){typeof console?.[e]=="function"&&console[e](n)},autoVacuum:!0},ji={combineWith:Cr,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:ol},ll={combineWith:io,prefix:function(e,n,t){return n===t.length-1}},kr={batchSize:1e3,batchWait:10},Sr={minDirtFactor:.1,minDirtCount:20},wr=J(J({},kr),Sr),ul=function(e,n){e.includes(n)||e.push(n)},Ji=function(e,n){var t,r;try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;e.includes(a)||e.push(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},Qi=function(e,n){var t=e.score,r=n.score;return r-t},qi=function(){return new Map},$t=function(e){var n,t,r=new Map;try{for(var i=X(Object.keys(e)),o=i.next();!o.done;o=i.next()){var a=o.value;r.set(parseInt(a,10),e[a])}}catch(s){n={error:s}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(n)throw n.error}}return r},cl=/[\n\r -#%-*,-/:;?@[-\]_{}\u00A0\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]+/u;var ao=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,n)=>{let t=await n.knowledgeBase.search(e.query),r=n;r._lastKBsearch=e.query,r._nextRequestUseKBitems=t,n.submitAnalyticsEvent({type:"kb-search",query:e.query,results:t});let i=t.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=t.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${o}.`}}];var Ke=new U("KnowledgeBase"),so=1,tn=class e{constructor(n){this._sources=[{id:"core.internal",query:async()=>ao}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=n}registerSource(n,t){let r=n;return typeof n=="function"&&(t=n,r=`source.${so++}`),this._sources.push({id:r,query:t}),r}removeSource(n){this._sources=this.sources.filter(t=>t.id!==n&&t.query!==n)}addEntry(n){this.manualEntries.push(n)}removeEntry(n){this.manualEntries=this.manualEntries.filter(t=>t.id!==n)}get sources(){let n=this._sources;return typeof window<"u"&&Q().knowledgeBaseSources&&(n=n.concat(Q().knowledgeBaseSources.map(t=>({id:t.name,query:t})))),n=n.concat(this._windowSources),n=n.filter(t=>!t.disabled),n}async search(n){Ke.debug(`Searching knowledge base for: ${n}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=n,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let i=(await Promise.all(this.sources.map(async l=>{try{let c=Date.now(),u=await l.query(n);return Ke.debug(`Source '${l.id}' took ${Date.now()-c}ms`),u||[]}catch(c){return Ke.warn(`Knowledge source '${l.id}' failed:`,c),[]}}))).flat();i=i.concat(t.entries),i=i.concat(this.manualEntries),Q().knowledgeBase&&(i=i.concat(Q().knowledgeBase)),i=i.filter(l=>l&&!l.disabled);for(let l=0;l<i.length;l++){let c=i[l];if(c.id=c.id||`temp.${l}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!c.action&&c.type=="tour"&&(c.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!c.action&&c.type=="info"&&(c.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),c.parameters&&!Array.isArray(c.parameters)){let u=c.parameters,p=[];for(let d in u)p.push({name:d,type:"string",description:c.parameters[d]});c.parameters=p}}let o=new oo({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let s=o.search(n).map(l=>i.find(c=>c.id==l.id));for(let l of i)l.isContext&&(s.find(c=>c.id===l.id)||s.push(l));return this.lastResults=s,Ke.debug("Found results:",s),s}getCachedEntry(n){return this.lastResults.find(t=>t.id==n||t._functionID==n)}registerSourceFromURL(n,t){t||(t=`external.${so++}`),Ke.debug(`Registering remote knowledge base source: ${n}`);let r=[],i=[],o=!0,a=async(l,c)=>{Ke.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:c},p=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw new Error(`HTTP Error ${p.status} ${p.statusText}`);let d=await p.json();return s(d.updateItems||[]),d.response},s=l=>{for(let c of l){if(!c.id){Ke.warn("KB item skipped since it has no ID.",c);continue}let u=r.find(p=>p.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}r.push({...c,action:p=>a(c,p)})}};this.registerSource(t,async l=>{if(o&&i.includes(l))return r;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:l},u=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return o=!p.noCache,i.includes(l)||i.push(l),s(p.items),r})}clone(){let n=new e(this.ai);return n._sources=this._sources,n._windowSources=this._windowSources,n.manualEntries=this.manualEntries,n}};var lo={name:"@intelliweave/embedded",version:"1.6.54",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var nn=class{constructor(n){this.ai=n}async boolean(n,t){let r=this.ai.clone();r.resetConversation(),r.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let i=await r.sendMessage(n+`
10
10
 
11
11
  `+JSON.stringify(t))||"";if(i.toLowerCase().includes("true"))return!0;if(i.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+i)}async choose(n,t,r){r=r.map(a=>a.trim());let i=this.ai.clone();i.resetConversation(),i.getContextPrefix=async()=>"You will receive a question and some data and options. Answer the question by replying with the option you want to choose. Only say the option you want, no additional text.";let o=await i.sendMessage("question:"+n+`
12
12
 
@@ -282,25 +282,27 @@ You have access to a database of knowledge base items. These include "info" type
282
282
 
283
283
  #root {
284
284
  position: fixed;
285
- display: flex;
286
- flex-direction: column;
287
285
  width: 64px;
288
286
  height: 64px;
289
287
  z-index: 200000;
290
288
  background-color: #20262C;
291
- border-radius: 32px;
289
+ border-radius: 50%;
292
290
  box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
293
291
  transition: width 0.25s, height 0.25s, border-radius 0.25s;
294
292
  overflow: hidden;
295
293
  color: white;
296
294
  font-family: "Karla", sans-serif;
295
+ overlow: hidden;
297
296
  }
298
297
  #root.open {
299
298
  border-radius: 32px 32px 16px 16px;
299
+ display: flex;
300
+ flex-direction: column;
300
301
  width: 400px;
301
302
  height: 600px;
302
303
  max-width: calc(100vw - 40px);
303
304
  max-height: calc(max(50vh, 100vh - 320px));
305
+ overflow: visible;
304
306
  }
305
307
 
306
308
  #root #web-weaver-logo {
@@ -310,6 +312,7 @@ You have access to a database of knowledge base items. These include "info" type
310
312
  top: 0px;
311
313
  left: 0px;
312
314
  background-color: #21262c;
315
+ border-radius:50%;
313
316
  z-index:999;
314
317
  }
315
318
 
@@ -328,6 +331,8 @@ You have access to a database of knowledge base items. These include "info" type
328
331
  overflow: hidden;
329
332
  font-size: 9px;
330
333
  color: #abacad;
334
+ border-bottom-right-radius: 16px;
335
+ border-bottom-left-radius: 16px;
331
336
  }
332
337
 
333
338
  #root .green-accent {
@@ -6,7 +6,7 @@ import{v4 as ce}from"uuid";function ie(c){let i=(c||"").split(`
6
6
  `);for(let d of a){n=d.indexOf(": ");let r=d.slice(0,n),h=d.slice(n+2);n==-1&&(r=d,h=""),r&&(l[r]!==void 0?l[r]+=`
7
7
  `+h:l[r]=h)}yield l}},t=new TextDecoder,s=c.getReader();for(;;){let{done:n,value:o}=await s.read();if(n)break;i+=t.decode(o,{stream:!0}),yield*e()}i+=t.decode()+`
8
8
 
9
- `,yield*e()}function he(){if(u().userID)return u().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=ce(),localStorage.setItem("intelliweave.uid",c),c)}else return ce()}var k=class k{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return k.debug?!0:typeof window<"u"&&u().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...s)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...s)}};k.debug=!1;var p=k;var X=new p("ONNXModel"),y=class c{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,X.debug(`Model input parameters: ${i.inputNames.join(", ")}`),X.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!c.lib}static async load(i){if(!c.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(X.debug("Loading ONNX runtime"),this.onnx=await c.lib()),X.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new c(e)}makeTensor(i,e,t=0){let s=1;for(let o of e)s*=o;let n;if(i=="float32")n=new c.onnx.Tensor(new Float32Array(s),e);else if(i=="int8")n=new c.onnx.Tensor(new Int8Array(s),e);else if(i=="int16")n=new c.onnx.Tensor(new Int16Array(s),e);else if(i=="int32")n=new c.onnx.Tensor(new Int32Array(s),e);else if(i=="int64")n=new c.onnx.Tensor(new BigInt64Array(s),e);else if(i=="uint8")n=new c.onnx.Tensor(new Uint8Array(s),e);else if(i=="uint16")n=new c.onnx.Tensor(new Uint16Array(s),e);else if(i=="uint32")n=new c.onnx.Tensor(new Uint32Array(s),e);else if(i=="uint64")n=new c.onnx.Tensor(new BigUint64Array(s),e);else throw new Error(`Invalid type: ${i}`);return t!==0&&(i=="int64"||i=="uint64")?n.data.fill(BigInt(t)):t!==0&&n.data.fill(t),n}registerConstant(i,e){if(!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);return this.constantTensors[i]=e,e}makeConstant(i,e,t,s=0){return this.registerConstant(i,this.makeTensor(e,t,s))}registerState(i,e,t){if(e||(e=i),!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[i]={outputName:e,tensor:t},t}makeState(i,e,t,s,n=0){return this.registerState(i,e,this.makeTensor(t,s,n))}async run(i={}){if(this._runActive&&this.ignoreIfBusy)return X.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)i[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)i[e]=this.constantTensors[e];try{let e=await this.session.run(i);for(let t in this.stateTensors){let s=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=s}return e}finally{this._runActive=!1}}resetState(){X.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var ue="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lm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FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Ee=new p("PCMPlayerNode"),B=class extends AudioWorkletNode{constructor(e,t,s){super(e,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!s||s!="int16"&&s!="float32")throw new Error(`Invalid format: ${s}`);this.sampleRate=t,this.format=s,this.port.onmessage=n=>this.onWorkletMessage(n),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:s})}feed(e){this.port.postMessage({action:"data",buffer:e.buffer},[e.buffer])}async play(e){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(t=>this._playPromiseResolve=t),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:e}}));try{let t=e.getReader();for(;!this.isCancelled;){let{done:s,value:n}=await t.read();if(s||!n)break;this.feed(n)}}catch(t){Ee.warn("Stream error:",t),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:e,error:t}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(e){e.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var P=new p("SpeechOutput"),me=.5,Te=.8,K=class extends EventTarget{constructor(i){super(),this.ai=i,this.ai.addEventListener("output",e=>this.onTextOutputFromAI(e)),this.ai.audio?.speechRecognition.addEventListener("speechstart",e=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(i){i.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(i.detail.message)}async speak(i){if(!this.ai?.config?.voice?.providerID)return P.warn("No voice provider configured");let e=`speech-${Le++}`;await this.ai.audio.beginAccess(e);try{await this._speakWithLock(i)}finally{this.ai.audio.endAccess(e)}}async _speakWithLock(i){this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Te);let e=this.ai?._voiceTracker||P.timer(`${this.ai.config.voice.providerID} voice`);e(`Speak: ${i}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination);let t=this.currentPlayerVolume,s=new B(this.ai.audio.context,24e3,"int16");this.currentPlayer=s,s.connect(t),s.addEventListener("end",o=>{let l=o;e(`PCM stream ${l.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==s&&!l.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let n;if(this.ai.config.voice.providerID=="openai")n=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:i,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")n=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:i})});else{P.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(e(`Received response ${n.status} ${n.statusText}`),!n.ok){P.warn(`Failed to generate voice sample: ${n.status} ${n.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:i}})),e("Playing PCM stream"),await s.play(n.body),e("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let i=this.currentPlayerVolume,e=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=me);let t=400;i.gain.linearRampToValueAtTime(0,t/1e3),await new Promise(s=>setTimeout(s,t+250)),i.disconnect(),e?.stop(),e?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=me)}},Le=1;function N(c,i){let e=i.reduce((a,d)=>a+d.byteLength,0),t=new DataView(new ArrayBuffer(44));t.setUint8(0,82),t.setUint8(1,73),t.setUint8(2,70),t.setUint8(3,70),t.setUint32(4,44+e,!0),t.setUint8(8,87),t.setUint8(9,65),t.setUint8(10,86),t.setUint8(11,69);let s=1,n=32,o=s*n/8,l=c*o;return t.setUint8(12,102),t.setUint8(13,109),t.setUint8(14,116),t.setUint8(15,32),t.setUint32(16,16,!0),t.setUint16(20,3,!0),t.setUint16(22,s,!0),t.setUint32(24,c,!0),t.setUint32(28,l,!0),t.setUint16(32,o,!0),t.setUint16(34,n,!0),t.setUint8(36,100),t.setUint8(37,97),t.setUint8(38,116),t.setUint8(39,97),t.setUint32(40,e,!0),new File([t,...i],"audio.wav",{type:"audio/wav"})}var z=class extends AudioWorkletNode{constructor(e,t,s,n){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=s;let o=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!o.includes(s))throw new Error(`Invalid format ${s}, must be one of: ${o.join(", ")}`);if(!n||n<=0)throw new Error(`Invalid buffer size: ${n}`);this.port.onmessage=l=>this.onWorkletMessage(l),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:s,bufferSize:n})}onWorkletMessage(e){if(e.data.action=="data"){let t=null;if(this.format=="int16"&&(t=new Int16Array(e.data.buffer)),this.format=="int64"&&(t=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(t=new Float32Array(e.data.buffer)),!t)throw new Error(`Invalid format: ${this.format}`);this.onData(t),this.dispatchEvent(new CustomEvent("data",{detail:{data:t}}))}}onData(e){}};var se=16e3,F=256,W=8,V=new p("VoiceDetectionNode"),R=class R extends z{constructor(e){super(e,se,"float32",F*W);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!R.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return se}get numberOfSamples(){return F}get numberOfSampleChunks(){return W}get outputBufferSize(){return F*W}get isModelLoaded(){return!!this.vad}async loadModel(){V.debug("Loading VAD model"),this.vad=await y.load(R.vadModelURL),this.vad.ignoreIfBusy=!0,V.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],se),this.vad.makeState("h","hn","float32",[2,W,64]),this.vad.makeState("c","cn","float32",[2,W,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new y.onnx.Tensor(e,[W,F])});if(!t)return;this.currentProbability=0;for(let o=0;o<t.output.data.length;o++)t.output.data[o]>this.currentProbability&&(this.currentProbability=t.output.data[o]);let s=this.isVoiceActive?this.sentivityEnd:this.sensitivity,n=this.currentProbability>s;if(!n&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=n,n&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),V.debug("Started speaking")):n?this.lastVoiceActiveDate=Date.now():!n&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!n&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),V.debug("Stopped speaking after timeout")),!n){let o=Date.now();o>this.nextVadReset&&(this.nextVadReset=o+5e3,this.vad.resetState())}}catch(t){V.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};R.vadModelURL="";var S=R;var ge=new p("VoiceChunkOutputNode"),I=class extends S{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((e,t)=>e+t.length,0)/8e3}async onData(e){if(await super.onData(e),this.isVoiceActive&&!this._voiceRecording){ge.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let t of this.buffers)this.recordedBuffers.push(t),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:t,isFinal:!1}})),this.onVoiceChunk(t);this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!0}})),this.onVoiceChunk(e),this._voiceRecording=!1;let t=this.recordedBuffers.reduce((s,n)=>s+n.length,0);ge.debug(`Voice complete, recorded ${(t/8e3).toFixed(2)} seconds of audio, ${t*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(e);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(e){}onVoiceEnd(e){}};var A=new p("OpenAITranscriptionNode"),Y=class extends I{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=A.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=N(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let n="";try{let o=new FormData;o.append("file",s),o.append("model","whisper-1"),o.append("response_format","text");let l=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o,signal:this.lastRequestAbortController.signal});if(!l.ok)throw new Error(`Failed to generate voice sample: ${l.status} ${l.statusText}`);t("Response received"),n=await l.text(),t("Content received: "+n),this.lastRequestAbortController=void 0}catch(o){A.error(`Failed to transcribe speech: ${o.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return A.debug("Transcription complete, but no text was found");A.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var H=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var f=new p("IntelliWeaveTranscriptionNode"),ke="wss://speech.intelliweave.ai/api/v1/transcribe",J=class J extends I{constructor(e,t){super(e);this.apiAddress=ke;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(f.debug("Opening WebSocket connection"),this.ws=new H(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(e.buffer),this.ws.onopen=()=>{f.debug("WebSocket connection opened")},this.ws.addEventListener("message",s=>{let n=JSON.parse(s.data);if(n.error)return f.warn("Error: "+n.error);if(n.type!="transcription")return f.warn("Invalid response type",n);if(n.streaming&&!n.final)return f.debug("Partial transcription: "+n.partialText);if(this.isTranscribing=!1,!n.text.trim())return f.warn(`Empty transcription (${n.processingTime}ms)`);f.debug(`Transcription: ${n.text} (${n.processingTime}ms)`),this.onVoiceTranscription(n.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",s=>f.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{f.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),J.debugExportWav){let t=N(this.sampleRate,e),s=document.createElement("a");s.href=URL.createObjectURL(t),s.download="recording.wav",s.click()}}onVoiceTranscription(e){}onSocketClose(){f.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};J.debugExportWav=!1;var D=J;var ne=new p("SpeechRecognition"),U=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e,this.ai.knowledgeBase.registerSource(()=>[{id:"system.microphone.enable",type:"action",name:"Enable or disable microphone",isContext:!0,content:`Starts or stops listening to input from the user through the microphone. ${this.isRunning?"Microphone access is currently enabled and you can hear the user.":"Microphone access is currently disabled."}.`,parameters:[{name:"enable",type:"boolean",description:"If true, enables the microphone. If false, disables it."}],action:async t=>{t.enable?await this.start():this.stop()}}])}get isSupported(){if(!y.lib||!this.ai?.vadModel||!v().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let e=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,e.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),S.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new Y(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new D(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",t=>{this.ai._voiceTracker=ne.timer("voice interaction","Speech started"),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("speechend",t=>{this.ai._voiceTracker?.("Speech ended"),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),this.onTranscription(t)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){ne.error("Failed to start speech recognition:",e),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(e=>e.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let s of this.analyserBuffer)e+=s*s;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(e){let t=e.detail.text;ne.debug("Heard:",t),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:t,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(e){throw this._skipEvents=!1,e}}}};var O=new p("AudioSystem"),w=class{constructor(i){this.locks=[];if(!i)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=i,this.ai.audio=this,this.speechRecognition=new U(this.ai),this.speechOutput=new K(this.ai)}static get isSupported(){return!(!y.lib||!v().AudioWorkletNode)}async beginAccess(i){O.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(O.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await Promise.all([this.context.audioWorklet.addModule(ue),this.context.audioWorklet.addModule(pe)]))}endAccess(i){O.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(O.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var fe=class{constructor(i,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!i)throw new Error(`Invalid array class: ${i}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=i,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((i,e)=>i+e.length,0)}feed(i){this.partialBuffers.push(i)}get canDrain(){return this.partialBuffers.reduce((e,t)=>e+t.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let i=this.ArrayClass,e=new i(this.outputBufferSize),t=0;for(;t!=e.length;){if(t>e.length)throw new Error(`Buffer overflow: ${t} > ${e.length}`);let s=e.length-t,n=this.partialBuffers[0],o=n.length-this.partialBufferOffset;o<s?(e.set(n.subarray(this.partialBufferOffset),t),t+=o,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(n.subarray(this.partialBufferOffset,this.partialBufferOffset+s),t),t+=s,this.partialBufferOffset+=s)}return e}pad(){let i=this.queuedSize%this.outputBufferSize;if(i==0)return;let e=this.ArrayClass,t=new e(i);this.feed(t)}};var ye=class{constructor(i,e,t,s){if(!i||!e||!t)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=i,this.toSampleRate=e,this.channels=t||0,this.inputBufferSize=s,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=i=>i,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(i){try{return this.outputBuffer.subarray(0,i)}catch{try{return this.outputBuffer.length=i,this.outputBuffer}catch{return this.outputBuffer.slice(0,i)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=i=>{let e=i.length,t=this.channels,s,n,o,l,a,d,r,h,m;if(e%t!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,n=this.ratioWeight,o=this.lastWeight,l=0,a=0,d=0,r=0,h=this.outputBuffer;o<1;o+=n)for(a=o%1,l=1-a,this.lastWeight=o%1,m=0;m<this.channels;++m)h[r++]=this.lastOutput[m]*l+i[m]*a;for(o-=1,e-=t,d=Math.floor(o)*t;r<s&&d<e;){for(a=o%1,l=1-a,m=0;m<this.channels;++m)h[r++]=i[d+(m>0?m:0)]*l+i[d+(t+m)]*a;o+=n,d=Math.floor(o)*t}for(m=0;m<t;++m)this.lastOutput[m]=i[d++];return this.bufferSlice(r)}}multiTap(){this.resampler=i=>{let e=i.length,t,s,n=this.channels,o,l,a,d,r,h,m,T,L;if(e%n!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(t=this.outputBufferSize,s=[],o=this.ratioWeight,l=0,d=0,r=0,h=!this.tailExists,this.tailExists=!1,m=this.outputBuffer,T=0,L=0,a=0;a<n;++a)s[a]=0;do{if(h)for(l=o,a=0;a<n;++a)s[a]=0;else{for(l=this.lastWeight,a=0;a<n;++a)s[a]=this.lastOutput[a];h=!0}for(;l>0&&d<e;)if(r=1+d-L,l>=r){for(a=0;a<n;++a)s[a]+=i[d++]*r;L=d,l-=r}else{for(a=0;a<n;++a)s[a]+=i[d+(a>0?a:0)]*l;L+=l,l=0;break}if(l===0)for(a=0;a<n;++a)m[T++]=s[a]/o;else{for(this.lastWeight=l,a=0;a<n;++a)this.lastOutput[a]=s[a];this.tailExists=!0;break}}while(d<e&&T<t);return this.bufferSlice(T)}}resample(i){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(i)}};function Dt(c){let i=c.length,e=new Int16Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,c[i]));e[i]=t<0?t*32768:t*32767}return e}function Jt(c){let i=c.length,e=new BigInt64Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,c[i]));e[i]=BigInt(Math.floor(t<0?t*32768:t*32767))*0x100000000000n}return e}function Ut(c){let i=c.length,e=new Float32Array(i);for(;i--;){let t=c[i];e[i]=t>=32768?-(65536-t)/32768:t/32767}return e}var b=new p("ChatGPT"),j=class{constructor(i){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...i}}async sendMessage(i){this.messages.push({role:"user",content:i}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let e=this.messages[this.messages.length-1];return e?.role=="assistant"&&e.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),b.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let i=this.messages[this.messages.length-1];if(i?.role=="user"||i?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(i?.role=="assistant"&&i?.tool_calls?.length){for(let e of i.tool_calls)await this.processToolCall(e);await this.processMessages()}}async trimMessages(){for(;;){let i=await this.sendToAPI(!0);if(JSON.stringify(i).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){b.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(i){let e=0;for(let a=this.messages.length-1;a>=0;a--)if(this.messages[a].role=="assistant"&&this.messages[a].tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[a].role=="user")break;b.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let a of this.tools){a.description&&a.description.length>1024&&b.warn(`Tool description for "${a.name}" is too long, it will be truncated.`);let d={type:"function",function:{name:a.name,description:(a.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(a.params))for(let r of a.params)d.function.parameters.properties[r.name]={type:r.type,description:r.description};else if(a.params){let r=a.params;for(let h in r)d.function.parameters.properties[h]={type:"string",description:r[h]}}t.tools.push(d)}t.user||delete t.user,t.tools.length||delete t.tools;let s={};if(s["Content-Type"]="application/json",this.config.apiKey&&(s.Authorization=`Bearer ${this.config.apiKey}`),i)return t;let n=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:s,body:JSON.stringify(t)});if(!n.ok){let a=`${n.status} ${n.statusText}`;try{let r=await n.json();a=r.errorText||r.error?.message||r.error||a}catch{}let d=new Error(a);throw d.code=n.status,d}let o=null,l=null;if(this.config.stream)for await(let a of de(n.body)){if(a.data=="[DONE]")break;if(!a.data)continue;let d=JSON.parse(a.data);if(l){for(let r in d.choices[0].delta)if(typeof d.choices[0].delta[r]=="string"){if(r=="role"&&l[r]==d.choices[0].delta[r])continue;l[r]=(l[r]||"")+d.choices[0].delta[r]}for(let r of d.choices[0].delta.tool_calls||[]){if(l.tool_calls||(l.tool_calls=[]),!l.tool_calls[r.index]){l.tool_calls[r.index]=r;continue}let h=l.tool_calls[r.index];h.function=h.function||{},h.function.name=(h.function.name||"")+(r.function?.name||""),h.function.arguments=(h.function.arguments||"")+(r.function?.arguments||"")}}else l={chunkID:d.id,...d.choices[0].delta};l?.content&&!l.content.startsWith("{")&&this.config.onAIMessage?.(l.content,!0)}else o=await n.json(),this.stats.tokensUsed+=o.usage?.total_tokens||0,b.debug(`Used ${o.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),l=o.choices?.[0]?.message;if(l||(b.warn("No response block in API response."),l={role:"assistant",content:""}),l.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(l),this.messages.push(l),l.content&&this.config.onAIMessage?.(l.content,!1)}processIncomingMessage(i){}registerTool(i){this.tools.push(i)}async processToolCall(i){try{let e=this.tools.find(n=>n.name==i.function.name);if(!e)throw new Error(`Tool "${i.function.name}" not found.`);let t=JSON.parse(i.function.arguments);this.config.onAIToolStart?.(i.function.name,t);let s=await e.callback(t);if(typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){b.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(n=>n.role!="assistant"||!n.tool_calls?.find(o=>o.id==i.id));return}else e.removeFromMessageHistory&&b.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${e.name}"`);this.messages.push({role:"tool",content:s,tool_call_id:i.id})}catch(e){b.warn(`Unable to process tool call for "${i?.function?.name}"`,e),this.messages.push({role:"tool",content:`Error: ${e.message}`,tool_call_id:i.id})}}resetConversation(){this.messages=[]}};import Be from"minisearch";var be=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(c,i)=>{let e=await i.knowledgeBase.search(c.query),t=i;t._lastKBsearch=c.query,t._nextRequestUseKBitems=e,i.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${n}.`}}];var Z=new p("KnowledgeBase"),ve=1,Q=class c{constructor(i){this._sources=[{id:"core.internal",query:async()=>be}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${ve++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return typeof window<"u"&&u().knowledgeBaseSources&&(i=i.concat(u().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){Z.debug(`Searching knowledge base for: ${i}`);let e=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});e.query=i,e.entries=[],e.sources=[],typeof document<"u"&&document.dispatchEvent(e),this._windowSources=e.sources;let s=(await Promise.all(this.sources.map(async a=>{try{let d=Date.now(),r=await a.query(i);return Z.debug(`Source '${a.id}' took ${Date.now()-d}ms`),r||[]}catch(d){return Z.warn(`Knowledge source '${a.id}' failed:`,d),[]}}))).flat();s=s.concat(e.entries),s=s.concat(this.manualEntries),u().knowledgeBase&&(s=s.concat(u().knowledgeBase)),s=s.filter(a=>a&&!a.disabled);for(let a=0;a<s.length;a++){let d=s[a];if(d.id=d.id||`temp.${a}`,d._functionID=d.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!d.action&&d.type=="tour"&&(d.action=r=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!d.action&&d.type=="info"&&(d.action=r=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),d.parameters&&!Array.isArray(d.parameters)){let r=d.parameters,h=[];for(let m in r)h.push({name:m,type:"string",description:d.parameters[m]});d.parameters=h}}let n=new Be({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});n.addAll(s);let l=n.search(i).map(a=>s.find(d=>d.id==a.id));for(let a of s)a.isContext&&(l.find(d=>d.id===a.id)||l.push(a));return this.lastResults=l,Z.debug("Found results:",l),l}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${ve++}`),Z.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(a,d)=>{Z.debug(`Calling remote knowledge base action: ${a.id}`);let r={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:a.id,parameters:d},h=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!h.ok)throw new Error(`HTTP Error ${h.status} ${h.statusText}`);let m=await h.json();return l(m.updateItems||[]),m.response},l=a=>{for(let d of a){if(!d.id){Z.warn("KB item skipped since it has no ID.",d);continue}let r=t.find(h=>h.id==d.id);if(r){r.name=d.name||r.name||"",r.content=d.content||r.content||"",r.disabled=d.disabled??r.disabled,r.isContext=d.isContext??r.isContext,r.parameters=d.parameters||r.parameters||[],r.tags=d.tags||r.tags,r.type=d.type||r.type;continue}t.push({...d,action:h=>o(d,h)})}};this.registerSource(e,async a=>{if(n&&s.includes(a))return t;let d={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:a},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let h=await r.json();return n=!h.noCache,s.includes(a)||s.push(a),l(h.items),t})}clone(){let i=new c(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}};import{v4 as xe}from"uuid";var we={name:"@intelliweave/embedded",version:"1.6.53",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var _=class{constructor(i){this.ai=i}async boolean(i,e){let t=this.ai.clone();t.resetConversation(),t.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let s=await t.sendMessage(i+`
9
+ `,yield*e()}function he(){if(u().userID)return u().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=ce(),localStorage.setItem("intelliweave.uid",c),c)}else return ce()}var k=class k{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return k.debug?!0:typeof window<"u"&&u().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...s)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...s)}};k.debug=!1;var p=k;var X=new p("ONNXModel"),y=class c{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,X.debug(`Model input parameters: ${i.inputNames.join(", ")}`),X.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!c.lib}static async load(i){if(!c.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(X.debug("Loading ONNX runtime"),this.onnx=await c.lib()),X.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new c(e)}makeTensor(i,e,t=0){let s=1;for(let o of e)s*=o;let n;if(i=="float32")n=new c.onnx.Tensor(new Float32Array(s),e);else if(i=="int8")n=new c.onnx.Tensor(new Int8Array(s),e);else if(i=="int16")n=new c.onnx.Tensor(new Int16Array(s),e);else if(i=="int32")n=new c.onnx.Tensor(new Int32Array(s),e);else if(i=="int64")n=new c.onnx.Tensor(new BigInt64Array(s),e);else if(i=="uint8")n=new c.onnx.Tensor(new Uint8Array(s),e);else if(i=="uint16")n=new c.onnx.Tensor(new Uint16Array(s),e);else if(i=="uint32")n=new c.onnx.Tensor(new Uint32Array(s),e);else if(i=="uint64")n=new c.onnx.Tensor(new BigUint64Array(s),e);else throw new Error(`Invalid type: ${i}`);return t!==0&&(i=="int64"||i=="uint64")?n.data.fill(BigInt(t)):t!==0&&n.data.fill(t),n}registerConstant(i,e){if(!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);return this.constantTensors[i]=e,e}makeConstant(i,e,t,s=0){return this.registerConstant(i,this.makeTensor(e,t,s))}registerState(i,e,t){if(e||(e=i),!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[i]={outputName:e,tensor:t},t}makeState(i,e,t,s,n=0){return this.registerState(i,e,this.makeTensor(t,s,n))}async run(i={}){if(this._runActive&&this.ignoreIfBusy)return X.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)i[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)i[e]=this.constantTensors[e];try{let e=await this.session.run(i);for(let t in this.stateTensors){let s=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=s}return e}finally{this._runActive=!1}}resetState(){X.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var ue="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9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sZXQgcj0wO3I8cztyKyspaVthXVtyXS5zZXQodFswXVtyXSl9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Ee=new p("PCMPlayerNode"),B=class extends AudioWorkletNode{constructor(e,t,s){super(e,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!s||s!="int16"&&s!="float32")throw new Error(`Invalid format: ${s}`);this.sampleRate=t,this.format=s,this.port.onmessage=n=>this.onWorkletMessage(n),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:s})}feed(e){this.port.postMessage({action:"data",buffer:e.buffer},[e.buffer])}async play(e){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(t=>this._playPromiseResolve=t),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:e}}));try{let t=e.getReader();for(;!this.isCancelled;){let{done:s,value:n}=await t.read();if(s||!n)break;this.feed(n)}}catch(t){Ee.warn("Stream error:",t),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:e,error:t}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(e){e.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var P=new p("SpeechOutput"),me=.5,Te=.8,K=class extends EventTarget{constructor(i){super(),this.ai=i,this.ai.addEventListener("output",e=>this.onTextOutputFromAI(e)),this.ai.audio?.speechRecognition.addEventListener("speechstart",e=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(i){i.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(i.detail.message)}async speak(i){if(!this.ai?.config?.voice?.providerID)return P.warn("No voice provider configured");let e=`speech-${Le++}`;await this.ai.audio.beginAccess(e);try{await this._speakWithLock(i)}finally{this.ai.audio.endAccess(e)}}async _speakWithLock(i){this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Te);let e=this.ai?._voiceTracker||P.timer(`${this.ai.config.voice.providerID} voice`);e(`Speak: ${i}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination);let t=this.currentPlayerVolume,s=new B(this.ai.audio.context,24e3,"int16");this.currentPlayer=s,s.connect(t),s.addEventListener("end",o=>{let l=o;e(`PCM stream ${l.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==s&&!l.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let n;if(this.ai.config.voice.providerID=="openai")n=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:i,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")n=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:i})});else{P.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(e(`Received response ${n.status} ${n.statusText}`),!n.ok){P.warn(`Failed to generate voice sample: ${n.status} ${n.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:i}})),e("Playing PCM stream"),await s.play(n.body),e("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let i=this.currentPlayerVolume,e=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=me);let t=400;i.gain.linearRampToValueAtTime(0,t/1e3),await new Promise(s=>setTimeout(s,t+250)),i.disconnect(),e?.stop(),e?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=me)}},Le=1;function N(c,i){let e=i.reduce((a,d)=>a+d.byteLength,0),t=new DataView(new ArrayBuffer(44));t.setUint8(0,82),t.setUint8(1,73),t.setUint8(2,70),t.setUint8(3,70),t.setUint32(4,44+e,!0),t.setUint8(8,87),t.setUint8(9,65),t.setUint8(10,86),t.setUint8(11,69);let s=1,n=32,o=s*n/8,l=c*o;return t.setUint8(12,102),t.setUint8(13,109),t.setUint8(14,116),t.setUint8(15,32),t.setUint32(16,16,!0),t.setUint16(20,3,!0),t.setUint16(22,s,!0),t.setUint32(24,c,!0),t.setUint32(28,l,!0),t.setUint16(32,o,!0),t.setUint16(34,n,!0),t.setUint8(36,100),t.setUint8(37,97),t.setUint8(38,116),t.setUint8(39,97),t.setUint32(40,e,!0),new File([t,...i],"audio.wav",{type:"audio/wav"})}var z=class extends AudioWorkletNode{constructor(e,t,s,n){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=s;let o=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!o.includes(s))throw new Error(`Invalid format ${s}, must be one of: ${o.join(", ")}`);if(!n||n<=0)throw new Error(`Invalid buffer size: ${n}`);this.port.onmessage=l=>this.onWorkletMessage(l),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:s,bufferSize:n})}onWorkletMessage(e){if(e.data.action=="data"){let t=null;if(this.format=="int16"&&(t=new Int16Array(e.data.buffer)),this.format=="int64"&&(t=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(t=new Float32Array(e.data.buffer)),!t)throw new Error(`Invalid format: ${this.format}`);this.onData(t),this.dispatchEvent(new CustomEvent("data",{detail:{data:t}}))}}onData(e){}};var se=16e3,F=256,W=8,V=new p("VoiceDetectionNode"),R=class R extends z{constructor(e){super(e,se,"float32",F*W);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!R.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return se}get numberOfSamples(){return F}get numberOfSampleChunks(){return W}get outputBufferSize(){return F*W}get isModelLoaded(){return!!this.vad}async loadModel(){V.debug("Loading VAD model"),this.vad=await y.load(R.vadModelURL),this.vad.ignoreIfBusy=!0,V.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],se),this.vad.makeState("h","hn","float32",[2,W,64]),this.vad.makeState("c","cn","float32",[2,W,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new y.onnx.Tensor(e,[W,F])});if(!t)return;this.currentProbability=0;for(let o=0;o<t.output.data.length;o++)t.output.data[o]>this.currentProbability&&(this.currentProbability=t.output.data[o]);let s=this.isVoiceActive?this.sentivityEnd:this.sensitivity,n=this.currentProbability>s;if(!n&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=n,n&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),V.debug("Started speaking")):n?this.lastVoiceActiveDate=Date.now():!n&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!n&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),V.debug("Stopped speaking after timeout")),!n){let o=Date.now();o>this.nextVadReset&&(this.nextVadReset=o+5e3,this.vad.resetState())}}catch(t){V.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};R.vadModelURL="";var S=R;var ge=new p("VoiceChunkOutputNode"),I=class extends S{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((e,t)=>e+t.length,0)/8e3}async onData(e){if(await super.onData(e),this.isVoiceActive&&!this._voiceRecording){ge.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let t of this.buffers)this.recordedBuffers.push(t),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:t,isFinal:!1}})),this.onVoiceChunk(t);this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!0}})),this.onVoiceChunk(e),this._voiceRecording=!1;let t=this.recordedBuffers.reduce((s,n)=>s+n.length,0);ge.debug(`Voice complete, recorded ${(t/8e3).toFixed(2)} seconds of audio, ${t*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(e);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(e){}onVoiceEnd(e){}};var A=new p("OpenAITranscriptionNode"),Y=class extends I{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=A.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=N(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let n="";try{let o=new FormData;o.append("file",s),o.append("model","whisper-1"),o.append("response_format","text");let l=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o,signal:this.lastRequestAbortController.signal});if(!l.ok)throw new Error(`Failed to generate voice sample: ${l.status} ${l.statusText}`);t("Response received"),n=await l.text(),t("Content received: "+n),this.lastRequestAbortController=void 0}catch(o){A.error(`Failed to transcribe speech: ${o.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return A.debug("Transcription complete, but no text was found");A.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var H=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var f=new p("IntelliWeaveTranscriptionNode"),ke="wss://speech.intelliweave.ai/api/v1/transcribe",J=class J extends I{constructor(e,t){super(e);this.apiAddress=ke;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(f.debug("Opening WebSocket connection"),this.ws=new H(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(e.buffer),this.ws.onopen=()=>{f.debug("WebSocket connection opened")},this.ws.addEventListener("message",s=>{let n=JSON.parse(s.data);if(n.error)return f.warn("Error: "+n.error);if(n.type!="transcription")return f.warn("Invalid response type",n);if(n.streaming&&!n.final)return f.debug("Partial transcription: "+n.partialText);if(this.isTranscribing=!1,!n.text.trim())return f.warn(`Empty transcription (${n.processingTime}ms)`);f.debug(`Transcription: ${n.text} (${n.processingTime}ms)`),this.onVoiceTranscription(n.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",s=>f.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{f.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),J.debugExportWav){let t=N(this.sampleRate,e),s=document.createElement("a");s.href=URL.createObjectURL(t),s.download="recording.wav",s.click()}}onVoiceTranscription(e){}onSocketClose(){f.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};J.debugExportWav=!1;var D=J;var ne=new p("SpeechRecognition"),U=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e,this.ai.knowledgeBase.registerSource(()=>[{id:"system.microphone.enable",type:"action",name:"Enable or disable microphone",isContext:!0,content:`Starts or stops listening to input from the user through the microphone. ${this.isRunning?"Microphone access is currently enabled and you can hear the user.":"Microphone access is currently disabled."}.`,parameters:[{name:"enable",type:"boolean",description:"If true, enables the microphone. If false, disables it."}],action:async t=>{t.enable?await this.start():this.stop()}}])}get isSupported(){if(!y.lib||!this.ai?.vadModel||!v().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let e=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,e.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),S.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new Y(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new D(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",t=>{this.ai._voiceTracker=ne.timer("voice interaction","Speech started"),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("speechend",t=>{this.ai._voiceTracker?.("Speech ended"),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),this.onTranscription(t)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){ne.error("Failed to start speech recognition:",e),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(e=>e.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let s of this.analyserBuffer)e+=s*s;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(e){let t=e.detail.text;ne.debug("Heard:",t),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:t,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(e){throw this._skipEvents=!1,e}}}};var O=new p("AudioSystem"),w=class{constructor(i){this.locks=[];if(!i)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=i,this.ai.audio=this,this.speechRecognition=new U(this.ai),this.speechOutput=new K(this.ai)}static get isSupported(){return!(!y.lib||!v().AudioWorkletNode)}async beginAccess(i){O.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(O.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await Promise.all([this.context.audioWorklet.addModule(ue),this.context.audioWorklet.addModule(pe)]))}endAccess(i){O.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(O.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var fe=class{constructor(i,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!i)throw new Error(`Invalid array class: ${i}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=i,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((i,e)=>i+e.length,0)}feed(i){this.partialBuffers.push(i)}get canDrain(){return this.partialBuffers.reduce((e,t)=>e+t.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let i=this.ArrayClass,e=new i(this.outputBufferSize),t=0;for(;t!=e.length;){if(t>e.length)throw new Error(`Buffer overflow: ${t} > ${e.length}`);let s=e.length-t,n=this.partialBuffers[0],o=n.length-this.partialBufferOffset;o<s?(e.set(n.subarray(this.partialBufferOffset),t),t+=o,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(n.subarray(this.partialBufferOffset,this.partialBufferOffset+s),t),t+=s,this.partialBufferOffset+=s)}return e}pad(){let i=this.queuedSize%this.outputBufferSize;if(i==0)return;let e=this.ArrayClass,t=new e(i);this.feed(t)}};var ye=class{constructor(i,e,t,s){if(!i||!e||!t)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=i,this.toSampleRate=e,this.channels=t||0,this.inputBufferSize=s,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=i=>i,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(i){try{return this.outputBuffer.subarray(0,i)}catch{try{return this.outputBuffer.length=i,this.outputBuffer}catch{return this.outputBuffer.slice(0,i)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=i=>{let e=i.length,t=this.channels,s,n,o,l,a,d,r,h,m;if(e%t!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,n=this.ratioWeight,o=this.lastWeight,l=0,a=0,d=0,r=0,h=this.outputBuffer;o<1;o+=n)for(a=o%1,l=1-a,this.lastWeight=o%1,m=0;m<this.channels;++m)h[r++]=this.lastOutput[m]*l+i[m]*a;for(o-=1,e-=t,d=Math.floor(o)*t;r<s&&d<e;){for(a=o%1,l=1-a,m=0;m<this.channels;++m)h[r++]=i[d+(m>0?m:0)]*l+i[d+(t+m)]*a;o+=n,d=Math.floor(o)*t}for(m=0;m<t;++m)this.lastOutput[m]=i[d++];return this.bufferSlice(r)}}multiTap(){this.resampler=i=>{let e=i.length,t,s,n=this.channels,o,l,a,d,r,h,m,T,L;if(e%n!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(t=this.outputBufferSize,s=[],o=this.ratioWeight,l=0,d=0,r=0,h=!this.tailExists,this.tailExists=!1,m=this.outputBuffer,T=0,L=0,a=0;a<n;++a)s[a]=0;do{if(h)for(l=o,a=0;a<n;++a)s[a]=0;else{for(l=this.lastWeight,a=0;a<n;++a)s[a]=this.lastOutput[a];h=!0}for(;l>0&&d<e;)if(r=1+d-L,l>=r){for(a=0;a<n;++a)s[a]+=i[d++]*r;L=d,l-=r}else{for(a=0;a<n;++a)s[a]+=i[d+(a>0?a:0)]*l;L+=l,l=0;break}if(l===0)for(a=0;a<n;++a)m[T++]=s[a]/o;else{for(this.lastWeight=l,a=0;a<n;++a)this.lastOutput[a]=s[a];this.tailExists=!0;break}}while(d<e&&T<t);return this.bufferSlice(T)}}resample(i){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(i)}};function Dt(c){let i=c.length,e=new Int16Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,c[i]));e[i]=t<0?t*32768:t*32767}return e}function Jt(c){let i=c.length,e=new BigInt64Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,c[i]));e[i]=BigInt(Math.floor(t<0?t*32768:t*32767))*0x100000000000n}return e}function Ut(c){let i=c.length,e=new Float32Array(i);for(;i--;){let t=c[i];e[i]=t>=32768?-(65536-t)/32768:t/32767}return e}var b=new p("ChatGPT"),j=class{constructor(i){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...i}}async sendMessage(i){this.messages.push({role:"user",content:i}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let e=this.messages[this.messages.length-1];return e?.role=="assistant"&&e.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),b.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let i=this.messages[this.messages.length-1];if(i?.role=="user"||i?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(i?.role=="assistant"&&i?.tool_calls?.length){for(let e of i.tool_calls)await this.processToolCall(e);await this.processMessages()}}async trimMessages(){for(;;){let i=await this.sendToAPI(!0);if(JSON.stringify(i).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){b.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(i){let e=0;for(let a=this.messages.length-1;a>=0;a--)if(this.messages[a].role=="assistant"&&this.messages[a].tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[a].role=="user")break;b.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let a of this.tools){a.description&&a.description.length>1024&&b.warn(`Tool description for "${a.name}" is too long, it will be truncated.`);let d={type:"function",function:{name:a.name,description:(a.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(a.params))for(let r of a.params)d.function.parameters.properties[r.name]={type:r.type,description:r.description};else if(a.params){let r=a.params;for(let h in r)d.function.parameters.properties[h]={type:"string",description:r[h]}}t.tools.push(d)}t.user||delete t.user,t.tools.length||delete t.tools;let s={};if(s["Content-Type"]="application/json",this.config.apiKey&&(s.Authorization=`Bearer ${this.config.apiKey}`),i)return t;let n=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:s,body:JSON.stringify(t)});if(!n.ok){let a=`${n.status} ${n.statusText}`;try{let r=await n.json();a=r.errorText||r.error?.message||r.error||a}catch{}let d=new Error(a);throw d.code=n.status,d}let o=null,l=null;if(this.config.stream)for await(let a of de(n.body)){if(a.data=="[DONE]")break;if(!a.data)continue;let d=JSON.parse(a.data);if(l){for(let r in d.choices[0].delta)if(typeof d.choices[0].delta[r]=="string"){if(r=="role"&&l[r]==d.choices[0].delta[r])continue;l[r]=(l[r]||"")+d.choices[0].delta[r]}for(let r of d.choices[0].delta.tool_calls||[]){if(l.tool_calls||(l.tool_calls=[]),!l.tool_calls[r.index]){l.tool_calls[r.index]=r;continue}let h=l.tool_calls[r.index];h.function=h.function||{},h.function.name=(h.function.name||"")+(r.function?.name||""),h.function.arguments=(h.function.arguments||"")+(r.function?.arguments||"")}}else l={chunkID:d.id,...d.choices[0].delta};l?.content&&!l.content.startsWith("{")&&this.config.onAIMessage?.(l.content,!0)}else o=await n.json(),this.stats.tokensUsed+=o.usage?.total_tokens||0,b.debug(`Used ${o.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),l=o.choices?.[0]?.message;if(l||(b.warn("No response block in API response."),l={role:"assistant",content:""}),l.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(l),this.messages.push(l),l.content&&this.config.onAIMessage?.(l.content,!1)}processIncomingMessage(i){}registerTool(i){this.tools.push(i)}async processToolCall(i){try{let e=this.tools.find(n=>n.name==i.function.name);if(!e)throw new Error(`Tool "${i.function.name}" not found.`);let t=JSON.parse(i.function.arguments);this.config.onAIToolStart?.(i.function.name,t);let s=await e.callback(t);if(typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){b.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(n=>n.role!="assistant"||!n.tool_calls?.find(o=>o.id==i.id));return}else e.removeFromMessageHistory&&b.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${e.name}"`);this.messages.push({role:"tool",content:s,tool_call_id:i.id})}catch(e){b.warn(`Unable to process tool call for "${i?.function?.name}"`,e),this.messages.push({role:"tool",content:`Error: ${e.message}`,tool_call_id:i.id})}}resetConversation(){this.messages=[]}};import Be from"minisearch";var be=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(c,i)=>{let e=await i.knowledgeBase.search(c.query),t=i;t._lastKBsearch=c.query,t._nextRequestUseKBitems=e,i.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${n}.`}}];var Z=new p("KnowledgeBase"),ve=1,Q=class c{constructor(i){this._sources=[{id:"core.internal",query:async()=>be}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${ve++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return typeof window<"u"&&u().knowledgeBaseSources&&(i=i.concat(u().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){Z.debug(`Searching knowledge base for: ${i}`);let e=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});e.query=i,e.entries=[],e.sources=[],typeof document<"u"&&document.dispatchEvent(e),this._windowSources=e.sources;let s=(await Promise.all(this.sources.map(async a=>{try{let d=Date.now(),r=await a.query(i);return Z.debug(`Source '${a.id}' took ${Date.now()-d}ms`),r||[]}catch(d){return Z.warn(`Knowledge source '${a.id}' failed:`,d),[]}}))).flat();s=s.concat(e.entries),s=s.concat(this.manualEntries),u().knowledgeBase&&(s=s.concat(u().knowledgeBase)),s=s.filter(a=>a&&!a.disabled);for(let a=0;a<s.length;a++){let d=s[a];if(d.id=d.id||`temp.${a}`,d._functionID=d.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!d.action&&d.type=="tour"&&(d.action=r=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!d.action&&d.type=="info"&&(d.action=r=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),d.parameters&&!Array.isArray(d.parameters)){let r=d.parameters,h=[];for(let m in r)h.push({name:m,type:"string",description:d.parameters[m]});d.parameters=h}}let n=new Be({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});n.addAll(s);let l=n.search(i).map(a=>s.find(d=>d.id==a.id));for(let a of s)a.isContext&&(l.find(d=>d.id===a.id)||l.push(a));return this.lastResults=l,Z.debug("Found results:",l),l}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${ve++}`),Z.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(a,d)=>{Z.debug(`Calling remote knowledge base action: ${a.id}`);let r={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:a.id,parameters:d},h=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!h.ok)throw new Error(`HTTP Error ${h.status} ${h.statusText}`);let m=await h.json();return l(m.updateItems||[]),m.response},l=a=>{for(let d of a){if(!d.id){Z.warn("KB item skipped since it has no ID.",d);continue}let r=t.find(h=>h.id==d.id);if(r){r.name=d.name||r.name||"",r.content=d.content||r.content||"",r.disabled=d.disabled??r.disabled,r.isContext=d.isContext??r.isContext,r.parameters=d.parameters||r.parameters||[],r.tags=d.tags||r.tags,r.type=d.type||r.type;continue}t.push({...d,action:h=>o(d,h)})}};this.registerSource(e,async a=>{if(n&&s.includes(a))return t;let d={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:a},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let h=await r.json();return n=!h.noCache,s.includes(a)||s.push(a),l(h.items),t})}clone(){let i=new c(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}};import{v4 as xe}from"uuid";var we={name:"@intelliweave/embedded",version:"1.6.54",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var _=class{constructor(i){this.ai=i}async boolean(i,e){let t=this.ai.clone();t.resetConversation(),t.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let s=await t.sendMessage(i+`
10
10
 
11
11
  `+JSON.stringify(e))||"";if(s.toLowerCase().includes("true"))return!0;if(s.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+s)}async choose(i,e,t){t=t.map(o=>o.trim());let s=this.ai.clone();s.resetConversation(),s.getContextPrefix=async()=>"You will receive a question and some data and options. Answer the question by replying with the option you want to choose. Only say the option you want, no additional text.";let n=await s.sendMessage("question:"+i+`
12
12
 
@@ -259,25 +259,27 @@ You have access to a database of knowledge base items. These include "info" type
259
259
 
260
260
  #root {
261
261
  position: fixed;
262
- display: flex;
263
- flex-direction: column;
264
262
  width: 64px;
265
263
  height: 64px;
266
264
  z-index: 200000;
267
265
  background-color: #20262C;
268
- border-radius: 32px;
266
+ border-radius: 50%;
269
267
  box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
270
268
  transition: width 0.25s, height 0.25s, border-radius 0.25s;
271
269
  overflow: hidden;
272
270
  color: white;
273
271
  font-family: "Karla", sans-serif;
272
+ overlow: hidden;
274
273
  }
275
274
  #root.open {
276
275
  border-radius: 32px 32px 16px 16px;
276
+ display: flex;
277
+ flex-direction: column;
277
278
  width: 400px;
278
279
  height: 600px;
279
280
  max-width: calc(100vw - 40px);
280
281
  max-height: calc(max(50vh, 100vh - 320px));
282
+ overflow: visible;
281
283
  }
282
284
 
283
285
  #root #web-weaver-logo {
@@ -287,6 +289,7 @@ You have access to a database of knowledge base items. These include "info" type
287
289
  top: 0px;
288
290
  left: 0px;
289
291
  background-color: #21262c;
292
+ border-radius:50%;
290
293
  z-index:999;
291
294
  }
292
295
 
@@ -305,6 +308,8 @@ You have access to a database of knowledge base items. These include "info" type
305
308
  overflow: hidden;
306
309
  font-size: 9px;
307
310
  color: #abacad;
311
+ border-bottom-right-radius: 16px;
312
+ border-bottom-left-radius: 16px;
308
313
  }
309
314
 
310
315
  #root .green-accent {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intelliweave/embedded",
3
- "version": "1.6.53",
3
+ "version": "1.6.54",
4
4
  "description": "Integrate IntelliWeave into your app or website.",
5
5
  "main": "./dist/webpack/index.js",
6
6
  "types": "./dist/webpack/index.d.ts",