@intelliweave/embedded 1.6.45 → 1.6.46
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 se}from"uuid";function ne(c){let s=(c||"").split(`
|
|
|
6
6
|
`);for(let o of l){n=o.indexOf(": ");let d=o.slice(0,n),p=o.slice(n+2);n==-1&&(d=o,p=""),d&&(r[d]!==void 0?r[d]+=`
|
|
7
7
|
`+p:r[d]=p)}yield r}},t=new TextDecoder,i=c.getReader();for(;;){let{done:n,value:a}=await i.read();if(n)break;s+=t.decode(a,{stream:!0}),yield*e()}s+=t.decode()+`
|
|
8
8
|
|
|
9
|
-
`,yield*e()}function ae(){if(u().userID)return u().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=se(),localStorage.setItem("intelliweave.uid",c),c)}else return se()}var V=class V{constructor(s){this.module="IntelliWeave";this.module=s}get debugEnabled(){return V.debug?!0:typeof window<"u"&&u().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)}};V.debug=!1;var h=V;var y=new h("ChatGPT"),T=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 l=this.messages.length-1;l>=0;l--)if(this.messages[l].role=="assistant"&&this.messages[l].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[l].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 l of this.tools){l.description&&l.description.length>1024&&y.warn(`Tool description for "${l.name}" is too long, it will be truncated.`);let o={type:"function",function:{name:l.name,description:(l.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(l.params))for(let d of l.params)o.function.parameters.properties[d.name]={type:d.type,description:d.description};else if(l.params){let d=l.params;for(let p in d)o.function.parameters.properties[p]={type:"string",description:d[p]}}t.tools.push(o)}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 l=`${n.status} ${n.statusText}`;try{let d=await n.json();l=d.errorText||d.error?.message||d.error||l}catch{}let o=new Error(l);throw o.code=n.status,o}let a=null,r=null;if(this.config.stream)for await(let l of oe(n.body)){if(l.data=="[DONE]")break;if(!l.data)continue;let o=JSON.parse(l.data);if(r){for(let d in o.choices[0].delta)if(typeof o.choices[0].delta[d]=="string"){if(d=="role"&&r[d]==o.choices[0].delta[d])continue;r[d]=(r[d]||"")+o.choices[0].delta[d]}for(let d of o.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[d.index]){r.tool_calls[d.index]=d;continue}let p=r.tool_calls[d.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(d.function?.name||""),p.function.arguments=(p.function.arguments||"")+(d.function?.arguments||"")}}else r={chunkID:o.id,...o.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}else a=await n.json(),this.stats.tokensUsed+=a.usage?.total_tokens||0,y.debug(`Used ${a.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),r=a.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(a=>a.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(c,s)=>{let e=await s.knowledgeBase.search(c.query);s.updateKnowledgeBase(e),s.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let t=e.filter(n=>n.type!="action").map(n=>"id="+n.id).join(", ")||"(none)",i=e.filter(n=>n.type=="action").map(n=>"name="+n.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${t}. New tools available: ${i}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(c,s)=>{if(!window.open(c.url,"_blank"))throw new Error("Window blocked by popup blocker.");return s.submitAnalyticsEvent({type:"open-url",url:c.url}),"URL opened"}}];var x=new h("KnowledgeBase"),le=1,k=class c{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"&&u().knowledgeBaseSources&&(s=s.concat(u().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 l=>{try{return await l.query(s)}catch(o){return x.warn(`Knowledge source '${l.id}' failed:`,o),[]}}))).flat();i=i.concat(e.entries),i=i.concat(this.manualEntries),u().knowledgeBase&&(i=i.concat(u().knowledgeBase)),i=i.filter(l=>l&&!l.disabled);for(let l=0;l<i.length;l++){let o=i[l];if(o.id=o.id||`temp.${l}`,!o.action&&o.type=="tour"&&(o.action=d=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!o.action&&o.type=="info"&&(o.action=d=>{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 d=o.parameters,p=[];for(let ie in d)p.push({name:ie,type:"string",description:o.parameters[ie]});o.parameters=p}o.content=ne(typeof o.content=="function"?o.content():o.content)}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(l=>i.find(o=>o.id==l.id));for(let l of i)l.isContext&&(r.find(o=>o.id===l.id)||r.push(l));return this.lastResults=r,x.debug("Found results:",r),r}getCachedEntry(s){return this.lastResults.find(e=>e.id==s)}registerSourceFromURL(s,e){e||(e=`external.${le++}`),x.debug(`Registering remote knowledge base source: ${s}`);let t=[],i=async(a,r)=>{x.debug(`Calling remote knowledge base action: ${a.id}`);let l={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:a.id,parameters:r},o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!o.ok)throw new Error(`HTTP Error ${o.status} ${o.statusText}`);let d=await o.json();return n(d.updateItems||[]),d.response},n=a=>{for(let r of a){if(!r.id){x.warn("KB item skipped since it has no ID.",r);continue}let l=t.find(o=>o.id==r.id);if(l){l.name=r.name||l.name||"",l.content=r.content||l.content||"",l.disabled=r.disabled??l.disabled,l.isContext=r.isContext??l.isContext,l.parameters=r.parameters||l.parameters||[],l.tags=r.tags||l.tags,l.type=r.type||l.type;continue}t.push({...r,action:o=>i(r,o)})}};this.registerSource(e,async a=>{let r={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:a},l=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let o=await l.json();return n(o.items),t})}clone(){let s=new c(this.ai);return s._sources=this._sources,s._windowSources=this._windowSources,s.manualEntries=this.manualEntries,s}};var ce={name:"@intelliweave/embedded",version:"1.6.45",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 L=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(u().userID)return u().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=se(),localStorage.setItem("intelliweave.uid",c),c)}else return se()}var V=class V{constructor(s){this.module="IntelliWeave";this.module=s}get debugEnabled(){return V.debug?!0:typeof window<"u"&&u().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)}};V.debug=!1;var h=V;var y=new h("ChatGPT"),T=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 l=this.messages.length-1;l>=0;l--)if(this.messages[l].role=="assistant"&&this.messages[l].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[l].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 l of this.tools){l.description&&l.description.length>1024&&y.warn(`Tool description for "${l.name}" is too long, it will be truncated.`);let o={type:"function",function:{name:l.name,description:(l.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(l.params))for(let d of l.params)o.function.parameters.properties[d.name]={type:d.type,description:d.description};else if(l.params){let d=l.params;for(let p in d)o.function.parameters.properties[p]={type:"string",description:d[p]}}t.tools.push(o)}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 l=`${n.status} ${n.statusText}`;try{let d=await n.json();l=d.errorText||d.error?.message||d.error||l}catch{}let o=new Error(l);throw o.code=n.status,o}let a=null,r=null;if(this.config.stream)for await(let l of oe(n.body)){if(l.data=="[DONE]")break;if(!l.data)continue;let o=JSON.parse(l.data);if(r){for(let d in o.choices[0].delta)if(typeof o.choices[0].delta[d]=="string"){if(d=="role"&&r[d]==o.choices[0].delta[d])continue;r[d]=(r[d]||"")+o.choices[0].delta[d]}for(let d of o.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[d.index]){r.tool_calls[d.index]=d;continue}let p=r.tool_calls[d.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(d.function?.name||""),p.function.arguments=(p.function.arguments||"")+(d.function?.arguments||"")}}else r={chunkID:o.id,...o.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}else a=await n.json(),this.stats.tokensUsed+=a.usage?.total_tokens||0,y.debug(`Used ${a.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),r=a.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(a=>a.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(c,s)=>{let e=await s.knowledgeBase.search(c.query);s.updateKnowledgeBase(e),s.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let t=e.filter(n=>n.type!="action").map(n=>"id="+n.id).join(", ")||"(none)",i=e.filter(n=>n.type=="action").map(n=>"name="+n.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${t}. New tools available: ${i}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(c,s)=>{if(!window.open(c.url,"_blank"))throw new Error("Window blocked by popup blocker.");return s.submitAnalyticsEvent({type:"open-url",url:c.url}),"URL opened"}}];var x=new h("KnowledgeBase"),le=1,k=class c{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"&&u().knowledgeBaseSources&&(s=s.concat(u().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 l=>{try{return await l.query(s)}catch(o){return x.warn(`Knowledge source '${l.id}' failed:`,o),[]}}))).flat();i=i.concat(e.entries),i=i.concat(this.manualEntries),u().knowledgeBase&&(i=i.concat(u().knowledgeBase)),i=i.filter(l=>l&&!l.disabled);for(let l=0;l<i.length;l++){let o=i[l];if(o.id=o.id||`temp.${l}`,!o.action&&o.type=="tour"&&(o.action=d=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!o.action&&o.type=="info"&&(o.action=d=>{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 d=o.parameters,p=[];for(let ie in d)p.push({name:ie,type:"string",description:o.parameters[ie]});o.parameters=p}o.content=ne(typeof o.content=="function"?o.content():o.content)}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(l=>i.find(o=>o.id==l.id));for(let l of i)l.isContext&&(r.find(o=>o.id===l.id)||r.push(l));return this.lastResults=r,x.debug("Found results:",r),r}getCachedEntry(s){return this.lastResults.find(e=>e.id==s)}registerSourceFromURL(s,e){e||(e=`external.${le++}`),x.debug(`Registering remote knowledge base source: ${s}`);let t=[],i=async(a,r)=>{x.debug(`Calling remote knowledge base action: ${a.id}`);let l={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:a.id,parameters:r},o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!o.ok)throw new Error(`HTTP Error ${o.status} ${o.statusText}`);let d=await o.json();return n(d.updateItems||[]),d.response},n=a=>{for(let r of a){if(!r.id){x.warn("KB item skipped since it has no ID.",r);continue}let l=t.find(o=>o.id==r.id);if(l){l.name=r.name||l.name||"",l.content=r.content||l.content||"",l.disabled=r.disabled??l.disabled,l.isContext=r.isContext??l.isContext,l.parameters=r.parameters||l.parameters||[],l.tags=r.tags||l.tags,l.type=r.type||l.type;continue}t.push({...r,action:o=>i(r,o)})}};this.registerSource(e,async a=>{let r={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:a},l=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let o=await l.json();return n(o.items),t})}clone(){let s=new c(this.ai);return s._sources=this._sources,s._windowSources=this._windowSources,s.manualEntries=this.manualEntries,s}};var ce={name:"@intelliweave/embedded",version:"1.6.46",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 L=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(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 n=await i.sendMessage("question:"+s+`
|
|
12
12
|
|
|
@@ -372,4 +372,4 @@ You have access to a database of knowledge base items. These include "info" type
|
|
|
372
372
|
|
|
373
373
|
</div>
|
|
374
374
|
|
|
375
|
-
`;this._isProcessing=!1;this.ai=new Z,S.isSupported&&(this.ai.audio=new S(this.ai))}onCreate(){u().embed&&te.warn("Only one <web-weaver-embed> element should be on the page."),u().embed=this,this.child("root").addEventListener("click",i=>this.onContainerClick(i)),this.child("web-weaver-logo").addEventListener("click",i=>this.onLogoClick(i)),this.child("interaction-bar").addEventListener("input-message",i=>this.processInput(i.detail)),this.child("interaction-bar").addEventListener("llm-button-click",i=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",i=>this.onLLMModelSelect(i)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.onAIToolStart=this.onAIToolStart.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.focusElement",type:"action",name:"Focus on an element",content:"Focuses and draws the user's attention to an HTML element on the page.",isContext:!0,parameters:[{name:"elementID",type:"string",description:"The HTML ID of the element to focus."}],action:i=>{let n=i.elementID||"";if(n.startsWith("#")&&(n=n.substring(1)),!n)throw new Error("No element ID specified.");let a=document.getElementById(n);if(!a)throw new Error(`Could not find the element with ID "${n}".`);a.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),this.attr.focusID=n,this.ai.submitAnalyticsEvent({type:"focus-element",elementID:n})}}),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:i=>(this.suggestions.push(i.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:i.text}),"Suggestion button added")});let t=this.attr.apiKey||u().apiKey;if(!t)return te.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.ai.load(t).then(i=>{this.config=i,u().introductionMessage=this.config.introductionMessage,u().analytics=this.config.analytics!==void 0?!!this.config.analytics:u().analytics,this.state.loading=!1,this.resetConversation()})}onUpdate(){this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("root").className=this.attr.open?"open":"",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("root").style.right=this.attr.offsetX?this.attr.offsetX+"px":"20px",this.child("root").style.bottom=this.attr.offsetY?this.attr.offsetY+"px":"20px",this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1;let e=this.child("web-weaver-logo");e.attr.focusID=this.attr.focusID,e.refreshLayout(),this.child("llm-selector-panel").state.items=this.ai.models.sort((t,i)=>(i.priority||0)-(t.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){u().embed==this&&(u().embed=null)}onContainerClick(e){this.attr.open||(e.preventDefault(),this.attr.open=!0)}onLogoClick(e){e.preventDefault(),e.stopPropagation(),this.attr.focusID?this.attr.focusID="":this.attr.open=!this.attr.open}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=u().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let i of u().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=i,n.addEventListener("click",a=>this.onSuggestionClick(a,i)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let t=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let n of Array.from(t.querySelectorAll(".suggestion-button")))n.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=e,t.appendChild(i),t.scrollBy({top:1e5,behavior:"smooth"}),await this.ai.sendMessage(e);for(let n of this.suggestions){let a=document.createElement("div");a.className="suggestion-button",a.innerText=n,a.addEventListener("click",r=>this.onSuggestionClick(r,n)),t.appendChild(a)}t.scrollBy({top:1e5,behavior:"smooth"})}catch(i){te.error("Failed to process input:",i);let n=document.createElement("div");n.className="output",n.innerText="Sorry, there was a problem getting a response. "+i.message,t.appendChild(n);let a=document.createElement("div");a.className="suggestion-button",a.innerText="Reset conversation",a.addEventListener("click",r=>this.resetConversation()),t.appendChild(a)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e){let t=await Pe().use(Le).use(Be).use(Ve,{target:"_blank",rel:["noopener","noreferrer"]}).use(Te).use(ke).processSync(e),i=this.child("web-weaver-embed-inner"),n=i.lastElementChild;if(n&&n.classList.contains("output"))n.innerHTML=t.toString("utf-8");else{let a=document.createElement("div");a.className="output",a.innerHTML=t.toString("utf-8"),i.appendChild(a)}for(let a of Array.from(i.querySelectorAll(".tool")))a.remove();i.scrollBy({top:1e6,behavior:"smooth"})}onAIToolStart(e,t){let i=`Running: ${e}`;e=="search"&&(i=`Searching: ${t?.query}`),e=="ui.focusElement"&&(i=`Focusing: #${t?.elementID}`),e=="ui.suggestResponse"&&(i=`Suggested response: ${t?.text}`);let n=this.child("web-weaver-embed-inner"),a=document.createElement("div");a.className="tool",a.innerText=i,n.appendChild(a),n.scrollBy({top:1e5,behavior:"smooth"})}onSuggestionClick(e,t){this.processInput(t)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}};w.tagName="intelliweave-embed",w.observedAttributes=["logo"];var vs=w;g.lib=()=>import("onnxruntime-web");w.register();export{vs as default};
|
|
375
|
+
`;this._isProcessing=!1;this.ai=new Z,S.isSupported&&(this.ai.audio=new S(this.ai))}onCreate(){u().embed&&te.warn("Only one <web-weaver-embed> element should be on the page."),u().embed=this,this.child("root").addEventListener("click",i=>this.onContainerClick(i)),this.child("web-weaver-logo").addEventListener("click",i=>this.onLogoClick(i)),this.child("interaction-bar").addEventListener("input-message",i=>this.processInput(i.detail)),this.child("interaction-bar").addEventListener("llm-button-click",i=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",i=>this.onLLMModelSelect(i)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.onAIToolStart=this.onAIToolStart.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.focusElement",type:"action",name:"Focus on an element",content:"Focuses and draws the user's attention to an HTML element on the page.",isContext:!0,parameters:[{name:"elementID",type:"string",description:"The HTML ID of the element to focus."}],action:i=>{let n=i.elementID||"";if(n.startsWith("#")&&(n=n.substring(1)),!n)throw new Error("No element ID specified.");let a=document.getElementById(n);if(!a)throw new Error(`Could not find the element with ID "${n}".`);a.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),this.attr.focusID=n,this.ai.submitAnalyticsEvent({type:"focus-element",elementID:n})}}),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:i=>(this.suggestions.push(i.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:i.text}),"Suggestion button added")});let t=this.attr.apiKey||u().apiKey;if(!t)return te.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.ai.load(t).then(i=>{this.config=i,u().introductionMessage=this.config.introductionMessage,u().analytics=this.config.analytics!==void 0?!!this.config.analytics:u().analytics,this.state.loading=!1,this.resetConversation()})}onUpdate(){this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("root").className=this.attr.open?"open":"",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("root").style.right=this.attr.offsetX?this.attr.offsetX+"px":"20px",this.child("root").style.bottom=this.attr.offsetY?this.attr.offsetY+"px":"20px",this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1;let e=this.child("web-weaver-logo");e.attr.focusID=this.attr.focusID,e.refreshLayout(),this.child("llm-selector-panel").state.items=this.ai.models.sort((t,i)=>(i.priority||0)-(t.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){u().embed==this&&(u().embed=null)}onContainerClick(e){this.attr.open||(e.preventDefault(),this.attr.open=!0)}onLogoClick(e){e.preventDefault(),e.stopPropagation(),this.attr.focusID?this.attr.focusID="":this.attr.open=!this.attr.open}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=u().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let i of u().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=i,n.addEventListener("click",a=>this.onSuggestionClick(a,i)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let t=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let n of Array.from(t.querySelectorAll(".suggestion-button")))n.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=e,t.appendChild(i),t.scrollBy({top:1e5,behavior:"smooth"}),await this.ai.sendMessage(e);for(let n of this.suggestions){let a=document.createElement("div");a.className="suggestion-button",a.innerText=n,a.addEventListener("click",r=>this.onSuggestionClick(r,n)),t.appendChild(a)}t.scrollBy({top:1e5,behavior:"smooth"})}catch(i){te.error("Failed to process input:",i);let n=document.createElement("div");n.className="output",n.innerText="Sorry, there was a problem getting a response. "+i.message,t.appendChild(n);let a=document.createElement("div");a.className="suggestion-button",a.innerText="Reset conversation",a.addEventListener("click",r=>this.resetConversation()),t.appendChild(a)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e){let t=await Pe().use(Le).use(Be).use(Ve,{target:"_blank",rel:["noopener","noreferrer"]}).use(Te).use(ke).processSync(e),i=this.child("web-weaver-embed-inner"),n=i.lastElementChild;if(n&&n.classList.contains("output"))n.innerHTML=t.toString("utf-8");else{let a=document.createElement("div");a.className="output",a.innerHTML=t.toString("utf-8"),i.appendChild(a)}for(let a of Array.from(i.querySelectorAll(".tool")))a.remove();i.scrollBy({top:1e6,behavior:"smooth"})}onAIToolStart(e,t){let i=`Running: ${e}`;e=="search"&&(i=`Searching: ${t?.query}`),e=="ui.focusElement"&&(i=`Focusing: #${t?.elementID}`),e=="ui.suggestResponse"&&(i=`Suggested response: ${t?.text}`);let n=this.child("web-weaver-embed-inner"),a=document.createElement("div");a.className="tool",a.innerText=i,n.appendChild(a),n.scrollBy({top:1e5,behavior:"smooth"})}onSuggestionClick(e,t){this.processInput(t)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}};w.tagName="intelliweave-embed",w.observedAttributes=["logo","focusID","open"];var vs=w;g.lib=()=>import("onnxruntime-web");w.register();export{vs as default};
|
|
Binary file
|
package/dist/node/node.js
CHANGED
|
@@ -6,7 +6,7 @@ import{v4 as C}from"uuid";function A(c){let t=(c||"").split(`
|
|
|
6
6
|
`);for(let r of n){o=r.indexOf(": ");let u=r.slice(0,o),d=r.slice(o+2);o==-1&&(u=r,d=""),u&&(a[u]!==void 0?a[u]+=`
|
|
7
7
|
`+d:a[u]=d)}yield a}},s=new TextDecoder,i=c.getReader();for(;;){let{done:o,value:l}=await i.read();if(o)break;t+=s.decode(l,{stream:!0}),yield*e()}t+=s.decode()+`
|
|
8
8
|
|
|
9
|
-
`,yield*e()}function O(){if(f().userID)return f().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=C(),localStorage.setItem("intelliweave.uid",c),c)}else return C()}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),(...i)=>this.debug(`[${t} ${Math.floor(Date.now()-s)}ms]`,...i)}};I.debug=!1;var g=I;var w=new g("ONNXModel"),D=class c{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,w.debug(`Model input parameters: ${t.inputNames.join(", ")}`),w.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||(w.debug("Loading ONNX runtime"),this.onnx=await c.lib()),w.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new c(e)}makeTensor(t,e,s=0){let i=1;for(let l of e)i*=l;let o;if(t=="float32")o=new c.onnx.Tensor(new Float32Array(i),e);else if(t=="int8")o=new c.onnx.Tensor(new Int8Array(i),e);else if(t=="int16")o=new c.onnx.Tensor(new Int16Array(i),e);else if(t=="int32")o=new c.onnx.Tensor(new Int32Array(i),e);else if(t=="int64")o=new c.onnx.Tensor(new BigInt64Array(i),e);else if(t=="uint8")o=new c.onnx.Tensor(new Uint8Array(i),e);else if(t=="uint16")o=new c.onnx.Tensor(new Uint16Array(i),e);else if(t=="uint32")o=new c.onnx.Tensor(new Uint32Array(i),e);else if(t=="uint64")o=new c.onnx.Tensor(new BigUint64Array(i),e);else throw new Error(`Invalid type: ${t}`);return s!==0&&(t=="int64"||t=="uint64")?o.data.fill(BigInt(s)):s!==0&&o.data.fill(s),o}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,i=0){return this.registerConstant(t,this.makeTensor(e,s,i))}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,i,o=0){return this.registerState(t,e,this.makeTensor(s,i,o))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return w.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 i=e[this.stateTensors[s].outputName];this.stateTensors[s].tensor=i}return e}finally{this._runActive=!1}}resetState(){w.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((n,r)=>n+r.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 i=1,o=32,l=i*o/8,a=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,i,!0),s.setUint32(24,c,!0),s.setUint32(28,a,!0),s.setUint16(32,l,!0),s.setUint16(34,o,!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 W=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 _=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 i=e.length-s,o=this.partialBuffers[0],l=o.length-this.partialBufferOffset;l<i?(e.set(o.subarray(this.partialBufferOffset),s),s+=l,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+i),s),s+=i,this.partialBufferOffset+=i)}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 K=class{constructor(t,e,s,i){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=i,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,i,o,l,a,n,r,u,d,h;if(e%s!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(i=this.outputBufferSize,o=this.ratioWeight,l=this.lastWeight,a=0,n=0,r=0,u=0,d=this.outputBuffer;l<1;l+=o)for(n=l%1,a=1-n,this.lastWeight=l%1,h=0;h<this.channels;++h)d[u++]=this.lastOutput[h]*a+t[h]*n;for(l-=1,e-=s,r=Math.floor(l)*s;u<i&&r<e;){for(n=l%1,a=1-n,h=0;h<this.channels;++h)d[u++]=t[r+(h>0?h:0)]*a+t[r+(s+h)]*n;l+=o,r=Math.floor(l)*s}for(h=0;h<s;++h)this.lastOutput[h]=t[r++];return this.bufferSlice(u)}}multiTap(){this.resampler=t=>{let e=t.length,s,i,o=this.channels,l,a,n,r,u,d,h,v,x;if(e%o!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,i=[],l=this.ratioWeight,a=0,r=0,u=0,d=!this.tailExists,this.tailExists=!1,h=this.outputBuffer,v=0,x=0,n=0;n<o;++n)i[n]=0;do{if(d)for(a=l,n=0;n<o;++n)i[n]=0;else{for(a=this.lastWeight,n=0;n<o;++n)i[n]=this.lastOutput[n];d=!0}for(;a>0&&r<e;)if(u=1+r-x,a>=u){for(n=0;n<o;++n)i[n]+=t[r++]*u;x=r,a-=u}else{for(n=0;n<o;++n)i[n]+=t[r+(n>0?n:0)]*a;x+=a,a=0;break}if(a===0)for(n=0;n<o;++n)h[v++]=i[n]/l;else{for(this.lastWeight=a,n=0;n<o;++n)this.lastOutput[n]=i[n];this.tailExists=!0;break}}while(r<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 n=this.messages.length-1;n>=0;n--)if(this.messages[n].role=="assistant"&&this.messages[n].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[n].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 n of this.tools){n.description&&n.description.length>1024&&p.warn(`Tool description for "${n.name}" is too long, it will be truncated.`);let r={type:"function",function:{name:n.name,description:(n.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(n.params))for(let u of n.params)r.function.parameters.properties[u.name]={type:u.type,description:u.description};else if(n.params){let u=n.params;for(let d in u)r.function.parameters.properties[d]={type:"string",description:u[d]}}s.tools.push(r)}s.user||delete s.user,s.tools.length||delete s.tools;let i={};if(i["Content-Type"]="application/json",this.config.apiKey&&(i.Authorization=`Bearer ${this.config.apiKey}`),t)return s;let o=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(s)});if(!o.ok){let n=`${o.status} ${o.statusText}`;try{let u=await o.json();n=u.errorText||u.error?.message||u.error||n}catch{}let r=new Error(n);throw r.code=o.status,r}let l=null,a=null;if(this.config.stream)for await(let n of P(o.body)){if(n.data=="[DONE]")break;if(!n.data)continue;let r=JSON.parse(n.data);if(a){for(let u in r.choices[0].delta)if(typeof r.choices[0].delta[u]=="string"){if(u=="role"&&a[u]==r.choices[0].delta[u])continue;a[u]=(a[u]||"")+r.choices[0].delta[u]}for(let u of r.choices[0].delta.tool_calls||[]){if(a.tool_calls||(a.tool_calls=[]),!a.tool_calls[u.index]){a.tool_calls[u.index]=u;continue}let d=a.tool_calls[u.index];d.function=d.function||{},d.function.name=(d.function.name||"")+(u.function?.name||""),d.function.arguments=(d.function.arguments||"")+(u.function?.arguments||"")}}else a={chunkID:r.id,...r.choices[0].delta};a?.content&&!a.content.startsWith("{")&&this.config.onAIMessage?.(a.content,!0)}else l=await o.json(),this.stats.tokensUsed+=l.usage?.total_tokens||0,p.debug(`Used ${l.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),a=l.choices?.[0]?.message;if(a||(p.warn("No response block in API response."),a={role:"assistant",content:""}),a.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(a),this.messages.push(a),a.content&&this.config.onAIMessage?.(a.content,!1)}processIncomingMessage(t){}registerTool(t){this.tools.push(t)}async processToolCall(t){try{let e=this.tools.find(o=>o.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 i=await e.callback(s);if(typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){p.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(o=>o.role!="assistant"||!o.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:i,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 F from"minisearch";var N=[{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);t.updateKnowledgeBase(e),t.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",i=e.filter(o=>o.type=="action").map(o=>"name="+o.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${i}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(c,t)=>{if(!window.open(c.url,"_blank"))throw new Error("Window blocked by popup blocker.");return t.submitAnalyticsEvent({type:"open-url",url:c.url}),"URL opened"}}];var y=new g("KnowledgeBase"),$=1,E=class c{constructor(t){this._sources=[{id:"core.internal",query:async()=>N}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${$++}`),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){y.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 i=(await Promise.all(this.sources.map(async n=>{try{return await n.query(t)}catch(r){return y.warn(`Knowledge source '${n.id}' failed:`,r),[]}}))).flat();i=i.concat(e.entries),i=i.concat(this.manualEntries),f().knowledgeBase&&(i=i.concat(f().knowledgeBase)),i=i.filter(n=>n&&!n.disabled);for(let n=0;n<i.length;n++){let r=i[n];if(r.id=r.id||`temp.${n}`,!r.action&&r.type=="tour"&&(r.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!r.action&&r.type=="info"&&(r.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),r.parameters&&!Array.isArray(r.parameters)){let u=r.parameters,d=[];for(let h in u)d.push({name:h,type:"string",description:r.parameters[h]});r.parameters=d}r.content=A(typeof r.content=="function"?r.content():r.content)}let o=new F({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let a=o.search(t).map(n=>i.find(r=>r.id==n.id));for(let n of i)n.isContext&&(a.find(r=>r.id===n.id)||a.push(n));return this.lastResults=a,y.debug("Found results:",a),a}getCachedEntry(t){return this.lastResults.find(e=>e.id==t)}registerSourceFromURL(t,e){e||(e=`external.${$++}`),y.debug(`Registering remote knowledge base source: ${t}`);let s=[],i=async(l,a)=>{y.debug(`Calling remote knowledge base action: ${l.id}`);let n={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:a},r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let u=await r.json();return o(u.updateItems||[]),u.response},o=l=>{for(let a of l){if(!a.id){y.warn("KB item skipped since it has no ID.",a);continue}let n=s.find(r=>r.id==a.id);if(n){n.name=a.name||n.name||"",n.content=a.content||n.content||"",n.disabled=a.disabled??n.disabled,n.isContext=a.isContext??n.isContext,n.parameters=a.parameters||n.parameters||[],n.tags=a.tags||n.tags,n.type=a.type||n.type;continue}s.push({...a,action:r=>i(a,r)})}};this.registerSource(e,async l=>{let a={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:l},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!n.ok)throw new Error(`HTTP Error ${n.status} ${n.statusText}`);let r=await n.json();return o(r.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.45",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 i=await s.sendMessage(t+`
|
|
9
|
+
`,yield*e()}function O(){if(f().userID)return f().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=C(),localStorage.setItem("intelliweave.uid",c),c)}else return C()}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),(...i)=>this.debug(`[${t} ${Math.floor(Date.now()-s)}ms]`,...i)}};I.debug=!1;var g=I;var w=new g("ONNXModel"),D=class c{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,w.debug(`Model input parameters: ${t.inputNames.join(", ")}`),w.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||(w.debug("Loading ONNX runtime"),this.onnx=await c.lib()),w.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new c(e)}makeTensor(t,e,s=0){let i=1;for(let l of e)i*=l;let o;if(t=="float32")o=new c.onnx.Tensor(new Float32Array(i),e);else if(t=="int8")o=new c.onnx.Tensor(new Int8Array(i),e);else if(t=="int16")o=new c.onnx.Tensor(new Int16Array(i),e);else if(t=="int32")o=new c.onnx.Tensor(new Int32Array(i),e);else if(t=="int64")o=new c.onnx.Tensor(new BigInt64Array(i),e);else if(t=="uint8")o=new c.onnx.Tensor(new Uint8Array(i),e);else if(t=="uint16")o=new c.onnx.Tensor(new Uint16Array(i),e);else if(t=="uint32")o=new c.onnx.Tensor(new Uint32Array(i),e);else if(t=="uint64")o=new c.onnx.Tensor(new BigUint64Array(i),e);else throw new Error(`Invalid type: ${t}`);return s!==0&&(t=="int64"||t=="uint64")?o.data.fill(BigInt(s)):s!==0&&o.data.fill(s),o}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,i=0){return this.registerConstant(t,this.makeTensor(e,s,i))}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,i,o=0){return this.registerState(t,e,this.makeTensor(s,i,o))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return w.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 i=e[this.stateTensors[s].outputName];this.stateTensors[s].tensor=i}return e}finally{this._runActive=!1}}resetState(){w.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((n,r)=>n+r.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 i=1,o=32,l=i*o/8,a=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,i,!0),s.setUint32(24,c,!0),s.setUint32(28,a,!0),s.setUint16(32,l,!0),s.setUint16(34,o,!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 W=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 _=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 i=e.length-s,o=this.partialBuffers[0],l=o.length-this.partialBufferOffset;l<i?(e.set(o.subarray(this.partialBufferOffset),s),s+=l,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+i),s),s+=i,this.partialBufferOffset+=i)}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 K=class{constructor(t,e,s,i){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=i,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,i,o,l,a,n,r,u,d,h;if(e%s!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(i=this.outputBufferSize,o=this.ratioWeight,l=this.lastWeight,a=0,n=0,r=0,u=0,d=this.outputBuffer;l<1;l+=o)for(n=l%1,a=1-n,this.lastWeight=l%1,h=0;h<this.channels;++h)d[u++]=this.lastOutput[h]*a+t[h]*n;for(l-=1,e-=s,r=Math.floor(l)*s;u<i&&r<e;){for(n=l%1,a=1-n,h=0;h<this.channels;++h)d[u++]=t[r+(h>0?h:0)]*a+t[r+(s+h)]*n;l+=o,r=Math.floor(l)*s}for(h=0;h<s;++h)this.lastOutput[h]=t[r++];return this.bufferSlice(u)}}multiTap(){this.resampler=t=>{let e=t.length,s,i,o=this.channels,l,a,n,r,u,d,h,v,x;if(e%o!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,i=[],l=this.ratioWeight,a=0,r=0,u=0,d=!this.tailExists,this.tailExists=!1,h=this.outputBuffer,v=0,x=0,n=0;n<o;++n)i[n]=0;do{if(d)for(a=l,n=0;n<o;++n)i[n]=0;else{for(a=this.lastWeight,n=0;n<o;++n)i[n]=this.lastOutput[n];d=!0}for(;a>0&&r<e;)if(u=1+r-x,a>=u){for(n=0;n<o;++n)i[n]+=t[r++]*u;x=r,a-=u}else{for(n=0;n<o;++n)i[n]+=t[r+(n>0?n:0)]*a;x+=a,a=0;break}if(a===0)for(n=0;n<o;++n)h[v++]=i[n]/l;else{for(this.lastWeight=a,n=0;n<o;++n)this.lastOutput[n]=i[n];this.tailExists=!0;break}}while(r<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 n=this.messages.length-1;n>=0;n--)if(this.messages[n].role=="assistant"&&this.messages[n].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[n].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 n of this.tools){n.description&&n.description.length>1024&&p.warn(`Tool description for "${n.name}" is too long, it will be truncated.`);let r={type:"function",function:{name:n.name,description:(n.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(n.params))for(let u of n.params)r.function.parameters.properties[u.name]={type:u.type,description:u.description};else if(n.params){let u=n.params;for(let d in u)r.function.parameters.properties[d]={type:"string",description:u[d]}}s.tools.push(r)}s.user||delete s.user,s.tools.length||delete s.tools;let i={};if(i["Content-Type"]="application/json",this.config.apiKey&&(i.Authorization=`Bearer ${this.config.apiKey}`),t)return s;let o=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(s)});if(!o.ok){let n=`${o.status} ${o.statusText}`;try{let u=await o.json();n=u.errorText||u.error?.message||u.error||n}catch{}let r=new Error(n);throw r.code=o.status,r}let l=null,a=null;if(this.config.stream)for await(let n of P(o.body)){if(n.data=="[DONE]")break;if(!n.data)continue;let r=JSON.parse(n.data);if(a){for(let u in r.choices[0].delta)if(typeof r.choices[0].delta[u]=="string"){if(u=="role"&&a[u]==r.choices[0].delta[u])continue;a[u]=(a[u]||"")+r.choices[0].delta[u]}for(let u of r.choices[0].delta.tool_calls||[]){if(a.tool_calls||(a.tool_calls=[]),!a.tool_calls[u.index]){a.tool_calls[u.index]=u;continue}let d=a.tool_calls[u.index];d.function=d.function||{},d.function.name=(d.function.name||"")+(u.function?.name||""),d.function.arguments=(d.function.arguments||"")+(u.function?.arguments||"")}}else a={chunkID:r.id,...r.choices[0].delta};a?.content&&!a.content.startsWith("{")&&this.config.onAIMessage?.(a.content,!0)}else l=await o.json(),this.stats.tokensUsed+=l.usage?.total_tokens||0,p.debug(`Used ${l.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),a=l.choices?.[0]?.message;if(a||(p.warn("No response block in API response."),a={role:"assistant",content:""}),a.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(a),this.messages.push(a),a.content&&this.config.onAIMessage?.(a.content,!1)}processIncomingMessage(t){}registerTool(t){this.tools.push(t)}async processToolCall(t){try{let e=this.tools.find(o=>o.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 i=await e.callback(s);if(typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){p.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(o=>o.role!="assistant"||!o.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:i,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 F from"minisearch";var N=[{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);t.updateKnowledgeBase(e),t.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",i=e.filter(o=>o.type=="action").map(o=>"name="+o.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${i}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(c,t)=>{if(!window.open(c.url,"_blank"))throw new Error("Window blocked by popup blocker.");return t.submitAnalyticsEvent({type:"open-url",url:c.url}),"URL opened"}}];var y=new g("KnowledgeBase"),$=1,E=class c{constructor(t){this._sources=[{id:"core.internal",query:async()=>N}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${$++}`),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){y.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 i=(await Promise.all(this.sources.map(async n=>{try{return await n.query(t)}catch(r){return y.warn(`Knowledge source '${n.id}' failed:`,r),[]}}))).flat();i=i.concat(e.entries),i=i.concat(this.manualEntries),f().knowledgeBase&&(i=i.concat(f().knowledgeBase)),i=i.filter(n=>n&&!n.disabled);for(let n=0;n<i.length;n++){let r=i[n];if(r.id=r.id||`temp.${n}`,!r.action&&r.type=="tour"&&(r.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!r.action&&r.type=="info"&&(r.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),r.parameters&&!Array.isArray(r.parameters)){let u=r.parameters,d=[];for(let h in u)d.push({name:h,type:"string",description:r.parameters[h]});r.parameters=d}r.content=A(typeof r.content=="function"?r.content():r.content)}let o=new F({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let a=o.search(t).map(n=>i.find(r=>r.id==n.id));for(let n of i)n.isContext&&(a.find(r=>r.id===n.id)||a.push(n));return this.lastResults=a,y.debug("Found results:",a),a}getCachedEntry(t){return this.lastResults.find(e=>e.id==t)}registerSourceFromURL(t,e){e||(e=`external.${$++}`),y.debug(`Registering remote knowledge base source: ${t}`);let s=[],i=async(l,a)=>{y.debug(`Calling remote knowledge base action: ${l.id}`);let n={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:a},r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let u=await r.json();return o(u.updateItems||[]),u.response},o=l=>{for(let a of l){if(!a.id){y.warn("KB item skipped since it has no ID.",a);continue}let n=s.find(r=>r.id==a.id);if(n){n.name=a.name||n.name||"",n.content=a.content||n.content||"",n.disabled=a.disabled??n.disabled,n.isContext=a.isContext??n.isContext,n.parameters=a.parameters||n.parameters||[],n.tags=a.tags||n.tags,n.type=a.type||n.type;continue}s.push({...a,action:r=>i(a,r)})}};this.registerSource(e,async l=>{let a={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:l},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!n.ok)throw new Error(`HTTP Error ${n.status} ${n.statusText}`);let r=await n.json();return o(r.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.46",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 i=await s.sendMessage(t+`
|
|
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(t,e,s){s=s.map(l=>l.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:"+t+`
|
|
12
12
|
|
package/dist/react/react.js
CHANGED
|
@@ -6,7 +6,7 @@ import we,{createContext as Ne,useContext as He,useEffect as $,useMemo as De,use
|
|
|
6
6
|
`);for(let a of c){n=a.indexOf(": ");let d=a.slice(0,n),p=a.slice(n+2);n==-1&&(d=a,p=""),d&&(r[d]!==void 0?r[d]+=`
|
|
7
7
|
`+p:r[d]=p)}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=oe(),localStorage.setItem("intelliweave.uid",l),l)}else return oe()}var V=class V{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return V.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)}};V.debug=!1;var u=V;var f=new u("ChatGPT"),T=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 a={type:"function",function:{name:c.name,description:(c.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(c.params))for(let d of c.params)a.function.parameters.properties[d.name]={type:d.type,description:d.description};else if(c.params){let d=c.params;for(let p in d)a.function.parameters.properties[p]={type:"string",description:d[p]}}t.tools.push(a)}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 d=await n.json();c=d.errorText||d.error?.message||d.error||c}catch{}let a=new Error(c);throw a.code=n.status,a}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 a=JSON.parse(c.data);if(r){for(let d in a.choices[0].delta)if(typeof a.choices[0].delta[d]=="string"){if(d=="role"&&r[d]==a.choices[0].delta[d])continue;r[d]=(r[d]||"")+a.choices[0].delta[d]}for(let d of a.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[d.index]){r.tool_calls[d.index]=d;continue}let p=r.tool_calls[d.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(d.function?.name||""),p.function.arguments=(p.function.arguments||"")+(d.function?.arguments||"")}}else r={chunkID:a.id,...a.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);i.updateKnowledgeBase(e),i.submitAnalyticsEvent({type:"kb-search",query:l.query,results:e});let t=e.filter(n=>n.type!="action").map(n=>"id="+n.id).join(", ")||"(none)",s=e.filter(n=>n.type=="action").map(n=>"name="+n.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${t}. New tools available: ${s}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(l,i)=>{if(!window.open(l.url,"_blank"))throw new Error("Window blocked by popup blocker.");return i.submitAnalyticsEvent({type:"open-url",url:l.url}),"URL opened"}}];var Z=new u("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){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 c=>{try{return await c.query(i)}catch(a){return Z.warn(`Knowledge source '${c.id}' failed:`,a),[]}}))).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 a=s[c];if(a.id=a.id||`temp.${c}`,!a.action&&a.type=="tour"&&(a.action=d=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!a.action&&a.type=="info"&&(a.action=d=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),a.parameters&&!Array.isArray(a.parameters)){let d=a.parameters,p=[];for(let ne in d)p.push({name:ne,type:"string",description:a.parameters[ne]});a.parameters=p}a.content=ae(typeof a.content=="function"?a.content():a.content)}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(a=>a.id==c.id));for(let c of s)c.isContext&&(r.find(a=>a.id===c.id)||r.push(c));return this.lastResults=r,Z.debug("Found results:",r),r}getCachedEntry(i){return this.lastResults.find(e=>e.id==i)}registerSourceFromURL(i,e){e||(e=`external.${de++}`),Z.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=async(o,r)=>{Z.debug(`Calling remote knowledge base action: ${o.id}`);let c={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:o.id,parameters:r},a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let d=await a.json();return n(d.updateItems||[]),d.response},n=o=>{for(let r of o){if(!r.id){Z.warn("KB item skipped since it has no ID.",r);continue}let c=t.find(a=>a.id==r.id);if(c){c.name=r.name||c.name||"",c.content=r.content||c.content||"",c.disabled=r.disabled??c.disabled,c.isContext=r.isContext??c.isContext,c.parameters=r.parameters||c.parameters||[],c.tags=r.tags||c.tags,c.type=r.type||c.type;continue}t.push({...r,action:a=>s(r,a)})}};this.registerSource(e,async o=>{let r={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:o},c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let a=await c.json();return n(a.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.45",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 L=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=oe(),localStorage.setItem("intelliweave.uid",l),l)}else return oe()}var V=class V{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return V.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)}};V.debug=!1;var u=V;var f=new u("ChatGPT"),T=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 a={type:"function",function:{name:c.name,description:(c.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(c.params))for(let d of c.params)a.function.parameters.properties[d.name]={type:d.type,description:d.description};else if(c.params){let d=c.params;for(let p in d)a.function.parameters.properties[p]={type:"string",description:d[p]}}t.tools.push(a)}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 d=await n.json();c=d.errorText||d.error?.message||d.error||c}catch{}let a=new Error(c);throw a.code=n.status,a}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 a=JSON.parse(c.data);if(r){for(let d in a.choices[0].delta)if(typeof a.choices[0].delta[d]=="string"){if(d=="role"&&r[d]==a.choices[0].delta[d])continue;r[d]=(r[d]||"")+a.choices[0].delta[d]}for(let d of a.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[d.index]){r.tool_calls[d.index]=d;continue}let p=r.tool_calls[d.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(d.function?.name||""),p.function.arguments=(p.function.arguments||"")+(d.function?.arguments||"")}}else r={chunkID:a.id,...a.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);i.updateKnowledgeBase(e),i.submitAnalyticsEvent({type:"kb-search",query:l.query,results:e});let t=e.filter(n=>n.type!="action").map(n=>"id="+n.id).join(", ")||"(none)",s=e.filter(n=>n.type=="action").map(n=>"name="+n.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${t}. New tools available: ${s}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(l,i)=>{if(!window.open(l.url,"_blank"))throw new Error("Window blocked by popup blocker.");return i.submitAnalyticsEvent({type:"open-url",url:l.url}),"URL opened"}}];var Z=new u("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){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 c=>{try{return await c.query(i)}catch(a){return Z.warn(`Knowledge source '${c.id}' failed:`,a),[]}}))).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 a=s[c];if(a.id=a.id||`temp.${c}`,!a.action&&a.type=="tour"&&(a.action=d=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!a.action&&a.type=="info"&&(a.action=d=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),a.parameters&&!Array.isArray(a.parameters)){let d=a.parameters,p=[];for(let ne in d)p.push({name:ne,type:"string",description:a.parameters[ne]});a.parameters=p}a.content=ae(typeof a.content=="function"?a.content():a.content)}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(a=>a.id==c.id));for(let c of s)c.isContext&&(r.find(a=>a.id===c.id)||r.push(c));return this.lastResults=r,Z.debug("Found results:",r),r}getCachedEntry(i){return this.lastResults.find(e=>e.id==i)}registerSourceFromURL(i,e){e||(e=`external.${de++}`),Z.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=async(o,r)=>{Z.debug(`Calling remote knowledge base action: ${o.id}`);let c={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:o.id,parameters:r},a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let d=await a.json();return n(d.updateItems||[]),d.response},n=o=>{for(let r of o){if(!r.id){Z.warn("KB item skipped since it has no ID.",r);continue}let c=t.find(a=>a.id==r.id);if(c){c.name=r.name||c.name||"",c.content=r.content||c.content||"",c.disabled=r.disabled??c.disabled,c.isContext=r.isContext??c.isContext,c.parameters=r.parameters||c.parameters||[],c.tags=r.tags||c.tags,c.type=r.type||c.type;continue}t.push({...r,action:a=>s(r,a)})}};this.registerSource(e,async o=>{let r={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:o},c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let a=await c.json();return n(a.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.46",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 L=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
|
|
|
@@ -372,4 +372,4 @@ You have access to a database of knowledge base items. These include "info" type
|
|
|
372
372
|
|
|
373
373
|
</div>
|
|
374
374
|
|
|
375
|
-
`;this._isProcessing=!1;this.ai=new x,w.isSupported&&(this.ai.audio=new w(this.ai))}onCreate(){h().embed&&ie.warn("Only one <web-weaver-embed> element should be on the page."),h().embed=this,this.child("root").addEventListener("click",s=>this.onContainerClick(s)),this.child("web-weaver-logo").addEventListener("click",s=>this.onLogoClick(s)),this.child("interaction-bar").addEventListener("input-message",s=>this.processInput(s.detail)),this.child("interaction-bar").addEventListener("llm-button-click",s=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",s=>this.onLLMModelSelect(s)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.onAIToolStart=this.onAIToolStart.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.focusElement",type:"action",name:"Focus on an element",content:"Focuses and draws the user's attention to an HTML element on the page.",isContext:!0,parameters:[{name:"elementID",type:"string",description:"The HTML ID of the element to focus."}],action:s=>{let n=s.elementID||"";if(n.startsWith("#")&&(n=n.substring(1)),!n)throw new Error("No element ID specified.");let o=document.getElementById(n);if(!o)throw new Error(`Could not find the element with ID "${n}".`);o.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),this.attr.focusID=n,this.ai.submitAnalyticsEvent({type:"focus-element",elementID:n})}}),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:s=>(this.suggestions.push(s.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:s.text}),"Suggestion button added")});let t=this.attr.apiKey||h().apiKey;if(!t)return ie.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.ai.load(t).then(s=>{this.config=s,h().introductionMessage=this.config.introductionMessage,h().analytics=this.config.analytics!==void 0?!!this.config.analytics:h().analytics,this.state.loading=!1,this.resetConversation()})}onUpdate(){this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("root").className=this.attr.open?"open":"",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("root").style.right=this.attr.offsetX?this.attr.offsetX+"px":"20px",this.child("root").style.bottom=this.attr.offsetY?this.attr.offsetY+"px":"20px",this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1;let e=this.child("web-weaver-logo");e.attr.focusID=this.attr.focusID,e.refreshLayout(),this.child("llm-selector-panel").state.items=this.ai.models.sort((t,s)=>(s.priority||0)-(t.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){h().embed==this&&(h().embed=null)}onContainerClick(e){this.attr.open||(e.preventDefault(),this.attr.open=!0)}onLogoClick(e){e.preventDefault(),e.stopPropagation(),this.attr.focusID?this.attr.focusID="":this.attr.open=!this.attr.open}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=h().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let s of h().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=s,n.addEventListener("click",o=>this.onSuggestionClick(o,s)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let t=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let n of Array.from(t.querySelectorAll(".suggestion-button")))n.remove();this.attr.focusID="";let s=document.createElement("div");s.className="input",s.innerText=e,t.appendChild(s),t.scrollBy({top:1e5,behavior:"smooth"}),await this.ai.sendMessage(e);for(let n of this.suggestions){let o=document.createElement("div");o.className="suggestion-button",o.innerText=n,o.addEventListener("click",r=>this.onSuggestionClick(r,n)),t.appendChild(o)}t.scrollBy({top:1e5,behavior:"smooth"})}catch(s){ie.error("Failed to process input:",s);let n=document.createElement("div");n.className="output",n.innerText="Sorry, there was a problem getting a response. "+s.message,t.appendChild(n);let o=document.createElement("div");o.className="suggestion-button",o.innerText="Reset conversation",o.addEventListener("click",r=>this.resetConversation()),t.appendChild(o)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e){let t=await Ae().use(Ke).use(ze).use(Be,{target:"_blank",rel:["noopener","noreferrer"]}).use(Pe).use(Fe).processSync(e),s=this.child("web-weaver-embed-inner"),n=s.lastElementChild;if(n&&n.classList.contains("output"))n.innerHTML=t.toString("utf-8");else{let o=document.createElement("div");o.className="output",o.innerHTML=t.toString("utf-8"),s.appendChild(o)}for(let o of Array.from(s.querySelectorAll(".tool")))o.remove();s.scrollBy({top:1e6,behavior:"smooth"})}onAIToolStart(e,t){let s=`Running: ${e}`;e=="search"&&(s=`Searching: ${t?.query}`),e=="ui.focusElement"&&(s=`Focusing: #${t?.elementID}`),e=="ui.suggestResponse"&&(s=`Suggested response: ${t?.text}`);let n=this.child("web-weaver-embed-inner"),o=document.createElement("div");o.className="tool",o.innerText=s,n.appendChild(o),n.scrollBy({top:1e5,behavior:"smooth"})}onSuggestionClick(e,t){this.processInput(t)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}};S.tagName="intelliweave-embed",S.observedAttributes=["logo"];var xe=new u("React"),fs=l=>typeof window>"u"?null:(S.register(),h().apiKey=l.apiKey??h().apiKey,h().analytics=l.analytics??h().analytics,h().debug=l.debug??h().debug,l.context&&(h().pageSummary=l.context),l.introductionMessage&&(h().introductionMessage=l.introductionMessage),l.introductionSuggestions&&(h().introductionSuggestions=l.introductionSuggestions),l.userID&&(h().userID=l.userID),$(()=>{let i=e=>{for(let t of l.knowledgeBase||[])e.entries.push(t);for(let t of l.sources||[])e.sources.push(t)};return document.addEventListener("webweaver_kb_search",i),()=>document.removeEventListener("webweaver_kb_search",i)},[l.knowledgeBase]),we.createElement("intelliweave-embed",{logo:l.logo,apiKey:l.apiKey,offsetX:l.offsetX||20,offsetY:l.offsetY||20})),Ze=Ne(void 0);function ys(l){function i(){xe.debug("Creating new IntelliWeave instance for <IntelliWeaveProvider />");let t=new x;return w.isSupported&&(t.audio=new w(t)),t.load(l.apiKey),t}h().analytics=l.analytics??h().analytics,h().debug=l.debug??h().debug;let e=De(()=>l.ai||i(),[l.ai,l.apiKey]);return $(()=>{let t=s=>{let n=s;n.detail.isFinal&&e.sendMessage(n.detail.transcript)};return e.audio?.speechRecognition.addEventListener("speech",t),()=>{e.audio?.speechRecognition.removeEventListener("speech",t)}}),we.createElement(Ze.Provider,{value:e},l.children)}function bs(){let[l,i]=se(0),e=He(Ze)||h().embed?.ai;e||xe.warn("Couldn't find IntelliWeave instance. Make sure you have <IntelliWeaveProvider /> somewhere in your scene graph, or use the <WebWeaverUI /> component.");let[,t]=se(!!e?.loaded),[,s]=se(e?.error);return $(()=>{let n=c=>t(c.detail.ai.loaded),o=c=>s(c.detail.ai.error),r=()=>i(c=>c+1);return e?.addEventListener("load",n),e?.addEventListener("error",o),e?.addEventListener("input",r),e?.addEventListener("output",r),e?.addEventListener("toolstart",r),e?.addEventListener("tool",r),()=>{e?.removeEventListener("load",n),e?.removeEventListener("error",o),e?.removeEventListener("input",r),e?.removeEventListener("output",r),e?.removeEventListener("toolstart",r),e?.removeEventListener("tool",r)}},[e]),e}function vs(l,i=[]){$(()=>{let e=t=>t.sources.push({query:l});return document.addEventListener("webweaver_kb_search",e),()=>document.removeEventListener("webweaver_kb_search",e)},i)}export{ys as IntelliWeaveProvider,fs as WebWeaverUI,bs as useIntelliWeave,vs as useIntelliWeaveKnowledge};
|
|
375
|
+
`;this._isProcessing=!1;this.ai=new x,w.isSupported&&(this.ai.audio=new w(this.ai))}onCreate(){h().embed&&ie.warn("Only one <web-weaver-embed> element should be on the page."),h().embed=this,this.child("root").addEventListener("click",s=>this.onContainerClick(s)),this.child("web-weaver-logo").addEventListener("click",s=>this.onLogoClick(s)),this.child("interaction-bar").addEventListener("input-message",s=>this.processInput(s.detail)),this.child("interaction-bar").addEventListener("llm-button-click",s=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",s=>this.onLLMModelSelect(s)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.onAIToolStart=this.onAIToolStart.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.focusElement",type:"action",name:"Focus on an element",content:"Focuses and draws the user's attention to an HTML element on the page.",isContext:!0,parameters:[{name:"elementID",type:"string",description:"The HTML ID of the element to focus."}],action:s=>{let n=s.elementID||"";if(n.startsWith("#")&&(n=n.substring(1)),!n)throw new Error("No element ID specified.");let o=document.getElementById(n);if(!o)throw new Error(`Could not find the element with ID "${n}".`);o.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),this.attr.focusID=n,this.ai.submitAnalyticsEvent({type:"focus-element",elementID:n})}}),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:s=>(this.suggestions.push(s.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:s.text}),"Suggestion button added")});let t=this.attr.apiKey||h().apiKey;if(!t)return ie.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.ai.load(t).then(s=>{this.config=s,h().introductionMessage=this.config.introductionMessage,h().analytics=this.config.analytics!==void 0?!!this.config.analytics:h().analytics,this.state.loading=!1,this.resetConversation()})}onUpdate(){this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("root").className=this.attr.open?"open":"",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("root").style.right=this.attr.offsetX?this.attr.offsetX+"px":"20px",this.child("root").style.bottom=this.attr.offsetY?this.attr.offsetY+"px":"20px",this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1;let e=this.child("web-weaver-logo");e.attr.focusID=this.attr.focusID,e.refreshLayout(),this.child("llm-selector-panel").state.items=this.ai.models.sort((t,s)=>(s.priority||0)-(t.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){h().embed==this&&(h().embed=null)}onContainerClick(e){this.attr.open||(e.preventDefault(),this.attr.open=!0)}onLogoClick(e){e.preventDefault(),e.stopPropagation(),this.attr.focusID?this.attr.focusID="":this.attr.open=!this.attr.open}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=h().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let s of h().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=s,n.addEventListener("click",o=>this.onSuggestionClick(o,s)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let t=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let n of Array.from(t.querySelectorAll(".suggestion-button")))n.remove();this.attr.focusID="";let s=document.createElement("div");s.className="input",s.innerText=e,t.appendChild(s),t.scrollBy({top:1e5,behavior:"smooth"}),await this.ai.sendMessage(e);for(let n of this.suggestions){let o=document.createElement("div");o.className="suggestion-button",o.innerText=n,o.addEventListener("click",r=>this.onSuggestionClick(r,n)),t.appendChild(o)}t.scrollBy({top:1e5,behavior:"smooth"})}catch(s){ie.error("Failed to process input:",s);let n=document.createElement("div");n.className="output",n.innerText="Sorry, there was a problem getting a response. "+s.message,t.appendChild(n);let o=document.createElement("div");o.className="suggestion-button",o.innerText="Reset conversation",o.addEventListener("click",r=>this.resetConversation()),t.appendChild(o)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e){let t=await Ae().use(Ke).use(ze).use(Be,{target:"_blank",rel:["noopener","noreferrer"]}).use(Pe).use(Fe).processSync(e),s=this.child("web-weaver-embed-inner"),n=s.lastElementChild;if(n&&n.classList.contains("output"))n.innerHTML=t.toString("utf-8");else{let o=document.createElement("div");o.className="output",o.innerHTML=t.toString("utf-8"),s.appendChild(o)}for(let o of Array.from(s.querySelectorAll(".tool")))o.remove();s.scrollBy({top:1e6,behavior:"smooth"})}onAIToolStart(e,t){let s=`Running: ${e}`;e=="search"&&(s=`Searching: ${t?.query}`),e=="ui.focusElement"&&(s=`Focusing: #${t?.elementID}`),e=="ui.suggestResponse"&&(s=`Suggested response: ${t?.text}`);let n=this.child("web-weaver-embed-inner"),o=document.createElement("div");o.className="tool",o.innerText=s,n.appendChild(o),n.scrollBy({top:1e5,behavior:"smooth"})}onSuggestionClick(e,t){this.processInput(t)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}};S.tagName="intelliweave-embed",S.observedAttributes=["logo","focusID","open"];var xe=new u("React"),fs=l=>typeof window>"u"?null:(S.register(),h().apiKey=l.apiKey??h().apiKey,h().analytics=l.analytics??h().analytics,h().debug=l.debug??h().debug,l.context&&(h().pageSummary=l.context),l.introductionMessage&&(h().introductionMessage=l.introductionMessage),l.introductionSuggestions&&(h().introductionSuggestions=l.introductionSuggestions),l.userID&&(h().userID=l.userID),$(()=>{let i=e=>{for(let t of l.knowledgeBase||[])e.entries.push(t);for(let t of l.sources||[])e.sources.push(t)};return document.addEventListener("webweaver_kb_search",i),()=>document.removeEventListener("webweaver_kb_search",i)},[l.knowledgeBase]),we.createElement("intelliweave-embed",{logo:l.logo,apiKey:l.apiKey,offsetX:l.offsetX||20,offsetY:l.offsetY||20})),Ze=Ne(void 0);function ys(l){function i(){xe.debug("Creating new IntelliWeave instance for <IntelliWeaveProvider />");let t=new x;return w.isSupported&&(t.audio=new w(t)),t.load(l.apiKey),t}h().analytics=l.analytics??h().analytics,h().debug=l.debug??h().debug;let e=De(()=>l.ai||i(),[l.ai,l.apiKey]);return $(()=>{let t=s=>{let n=s;n.detail.isFinal&&e.sendMessage(n.detail.transcript)};return e.audio?.speechRecognition.addEventListener("speech",t),()=>{e.audio?.speechRecognition.removeEventListener("speech",t)}}),we.createElement(Ze.Provider,{value:e},l.children)}function bs(){let[l,i]=se(0),e=He(Ze)||h().embed?.ai;e||xe.warn("Couldn't find IntelliWeave instance. Make sure you have <IntelliWeaveProvider /> somewhere in your scene graph, or use the <WebWeaverUI /> component.");let[,t]=se(!!e?.loaded),[,s]=se(e?.error);return $(()=>{let n=c=>t(c.detail.ai.loaded),o=c=>s(c.detail.ai.error),r=()=>i(c=>c+1);return e?.addEventListener("load",n),e?.addEventListener("error",o),e?.addEventListener("input",r),e?.addEventListener("output",r),e?.addEventListener("toolstart",r),e?.addEventListener("tool",r),()=>{e?.removeEventListener("load",n),e?.removeEventListener("error",o),e?.removeEventListener("input",r),e?.removeEventListener("output",r),e?.removeEventListener("toolstart",r),e?.removeEventListener("tool",r)}},[e]),e}function vs(l,i=[]){$(()=>{let e=t=>t.sources.push({query:l});return document.addEventListener("webweaver_kb_search",e),()=>document.removeEventListener("webweaver_kb_search",e)},i)}export{ys as IntelliWeaveProvider,fs as WebWeaverUI,bs as useIntelliWeave,vs as useIntelliWeaveKnowledge};
|
|
@@ -6,7 +6,7 @@ import{b as pr,c as Oi,d as _i}from"./chunk-FSRPMVAS.js";var gs=pr((v1,ms)=>{"us
|
|
|
6
6
|
`);for(let u of l){o=u.indexOf(": ");let c=u.slice(0,o),h=u.slice(o+2);o==-1&&(c=u,h=""),c&&(s[c]!==void 0?s[c]+=`
|
|
7
7
|
`+h:s[c]=h)}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=Ke(),localStorage.setItem("intelliweave.uid",e),e)}else return Ke()}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 Ze=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?.(),Ze.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){Ze.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;Ze.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&&Ze.warn(`Tool description for "${l.name}" is too long, it will be truncated.`);let u={type:"function",function:{name:l.name,description:(l.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(l.params))for(let c of l.params)u.function.parameters.properties[c.name]={type:c.type,description:c.description};else if(l.params){let c=l.params;for(let h in c)u.function.parameters.properties[h]={type:"string",description:c[h]}}r.tools.push(u)}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 c=await o.json();l=c.errorText||c.error?.message||c.error||l}catch{}let u=new Error(l);throw u.code=o.status,u}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 u=JSON.parse(l.data);if(s){for(let c in u.choices[0].delta)if(typeof u.choices[0].delta[c]=="string"){if(c=="role"&&s[c]==u.choices[0].delta[c])continue;s[c]=(s[c]||"")+u.choices[0].delta[c]}for(let c of u.choices[0].delta.tool_calls||[]){if(s.tool_calls||(s.tool_calls=[]),!s.tool_calls[c.index]){s.tool_calls[c.index]=c;continue}let h=s.tool_calls[c.index];h.function=h.function||{},h.function.name=(h.function.name||"")+(c.function?.name||""),h.function.arguments=(h.function.arguments||"")+(c.function?.arguments||"")}}else s={chunkID:u.id,...u.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,Ze.debug(`Used ${a.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),s=a.choices?.[0]?.message;if(s||(Ze.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){Ze.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&&Ze.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){Ze.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(c){try{u(r.next(c))}catch(h){a(h)}}function l(c){try{u(r.throw(c))}catch(h){a(h)}}function u(c){c.done?o(c.value):i(c.value).then(s,l)}u((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(u){return function(c){return l([u,c])}}function l(u){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(t=0)),t;)try{if(r=1,i&&(o=u[0]&2?i.return:u[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,u[1])).done)return o;switch(i=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,i=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){t.label=u[1];break}if(u[0]===6&&t.label<o[1]){t.label=o[1],o=u;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(u);break}o[2]&&t.ops.pop(),t.trys.pop();continue}u=n.call(e,t)}catch(c){u=[6,c],i=0}finally{r=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[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="",fr=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=ot(this._path),t=n.node,r=n.keys;if(ot(r)===le)return{done:!1,value:this.result()};var i=t.get(ot(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=ot(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 ot(t)}).filter(function(n){return n!==le}).join("")},e.prototype.value=function(){return ot(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}(),ot=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,u,c=o*a;try{e:for(var h=X(e.keys()),d=h.next();!d.done;d=h.next()){var p=d.value;if(p===le){var g=i[c-1];g<=t&&r.set(s,[e.get(p),g])}else{for(var w=o,k=0;k<p.length;++k,++w){for(var y=p[k],I=a*w,v=I-a,z=i[I],Z=Math.max(0,w-t-1),x=Math.min(a-1,w+t),L=Z;L<x;++L){var R=y!==n[L],M=i[v+L]+ +R,P=i[v+L+1]+1,D=i[I+L]+1,F=i[I+L+1]=Math.min(M,P,D);F<z&&(z=F)}if(z>t)continue e}to(e.get(p),n,t,r,i,w,a,s+p)}}}catch(E){l={error:E}}finally{try{d&&!d.done&&(u=h.return)&&u.call(h)}finally{if(l)throw l.error}}},mr=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=$(Sr(a),2),l=s[0],u=s[1];try{for(var c=X(l.keys()),h=c.next();!h.done;h=c.next()){var d=h.value;if(d!==le&&d.startsWith(u)){var p=new Map;return p.set(d.slice(u.length),l.get(d)),new e(p,n)}}}catch(g){t={error:g}}finally{try{h&&!h.done&&(r=c.return)&&r.call(c)}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 fr(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(u){t={error:u}}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=wr(this._tree,n);return t!==void 0?t.get(le):void 0},e.prototype.has=function(n){var t=wr(this._tree,n);return t!==void 0&&t.has(le)},e.prototype.keys=function(){return new fr(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=gr(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=gr(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=gr(this._tree,n),i=r.get(le);return i===void 0&&r.set(le,i=t()),i},e.prototype.values=function(){return new fr(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],u=s[1];i.set(l,u)}}catch(c){t={error:c}}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)},wr=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 wr(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}}},gr=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 u=Math.min(i-o,l.length),c=1;c<u&&n[o+c]===l[c];)++c;var h=e.get(l);if(c===l.length)e=h;else{var d=new Map;d.set(l.slice(c),h),e.set(n.slice(o,o+c),d),e.delete(l),e=d}o+=c;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 p=new Map;return e.set(n.slice(o),p),p}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=$(Sr(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=$(Sr(e),2),i=r[0],o=r[1];i.set(o+n,t),i.delete(o)}},Sr=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?br:n.autoVacuum;this._options=J(J(J({},xr),n),{autoVacuum:t,searchOptions:J(J({},ji),n.searchOptions||{}),autoSuggestOptions:J(J({},ll),n.autoSuggestOptions||{})}),this._index=new mr,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=kr,this.addFields(this._options.fields)}return e.prototype.add=function(n){var t,r,i,o,a,s,l=this._options,u=l.extractField,c=l.tokenize,h=l.processTerm,d=l.fields,p=l.idField,g=u(n,p);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(p,'"'));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=u(n,I);if(v!=null){var z=c(v.toString(),I),Z=this._fieldIds[I],x=new Set(z).size;this.addFieldLength(w,Z,this._documentCount-1,x);try{for(var L=(i=void 0,X(z)),R=L.next();!R.done;R=L.next()){var M=R.value,P=h(M,I);if(Array.isArray(P))try{for(var D=(a=void 0,X(P)),F=D.next();!F.done;F=D.next()){var E=F.value;this.addTerm(Z,w,E)}}catch(A){a={error:A}}finally{try{F&&!F.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else P&&this.addTerm(Z,w,P)}}catch(A){i={error:A}}finally{try{R&&!R.done&&(o=L.return)&&o.call(L)}finally{if(i)throw i.error}}}}}catch(A){t={error:A}}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(c,h,d){var p=c.chunk,g=c.promise;return p.push(h),(d+1)%o===0?{chunk:[],promise:g.then(function(){return new Promise(function(w){return setTimeout(w,0)})}).then(function(){return r.addAll(p)})}:{chunk:p,promise:g}},a),l=s.chunk,u=s.promise;return u.then(function(){return r.addAll(l)})},e.prototype.remove=function(n){var t,r,i,o,a,s,l=this._options,u=l.tokenize,c=l.processTerm,h=l.extractField,d=l.fields,p=l.idField,g=h(n,p);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(p,'"'));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=h(n,I);if(v!=null){var z=u(v.toString(),I),Z=this._fieldIds[I],x=new Set(z).size;this.removeFieldLength(w,Z,this._documentCount,x);try{for(var L=(i=void 0,X(z)),R=L.next();!R.done;R=L.next()){var M=R.value,P=c(M,I);if(Array.isArray(P))try{for(var D=(a=void 0,X(P)),F=D.next();!F.done;F=D.next()){var E=F.value;this.removeTerm(Z,w,E)}}catch(A){a={error:A}}finally{try{F&&!F.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else P&&this.removeTerm(Z,w,P)}}catch(A){i={error:A}}finally{try{R&&!R.done&&(o=L.return)&&o.call(L)}finally{if(i)throw i.error}}}}}catch(A){t={error:A}}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 mr,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=kr,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,u,c,h,d,p,g,w,k,y,I,v,z,Z,x,L,R,M,P,D;return $s(this,function(F){switch(F.label){case 0:if(r=this._dirtCount,!this.vacuumConditionsMet(t))return[3,10];i=n.batchSize||vr.batchSize,o=n.batchWait||vr.batchWait,a=1,F.label=1;case 1:F.trys.push([1,7,8,9]),s=X(this._index),l=s.next(),F.label=2;case 2:if(l.done)return[3,6];u=$(l.value,2),c=u[0],h=u[1];try{for(d=(R=void 0,X(h)),p=d.next();!p.done;p=d.next()){g=$(p.value,2),w=g[0],k=g[1];try{for(y=(P=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?h.delete(w):k.delete(z))}catch(E){P={error:E}}finally{try{I&&!I.done&&(D=y.return)&&D.call(y)}finally{if(P)throw P.error}}}}catch(E){R={error:E}}finally{try{p&&!p.done&&(M=d.return)&&M.call(d)}finally{if(R)throw R.error}}return this._index.get(c).size===0&&this._index.delete(c),a%i!==0?[3,4]:[4,new Promise(function(E){return setTimeout(E,o)})];case 3:F.sent(),F.label=4;case 4:a+=1,F.label=5;case 5:return l=s.next(),[3,2];case 6:return[3,9];case 7:return Z=F.sent(),x={error:Z},[3,9];case 8:try{l&&!l.done&&(L=s.return)&&L.call(s)}finally{if(x)throw x.error}return[7];case 9:this._dirtCount-=r,F.label=10;case 10:return[4,null];case 11:return F.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||br.minDirtCount,r=r||br.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 u=$(l.value,2),c=u[0],h=u[1],d=h.score,p=h.terms,g=h.match,w=p.length||1,k={id:this._documentIds.get(c),score:d*w,terms:Object.keys(g),queryTerms:p,match:g};Object.assign(k,this._storedFields.get(c)),(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)),u=l.next();!u.done;u=l.next()){var c=u.value,h=c.score,d=c.terms,p=d.join(" "),g=s.get(p);g!=null?(g.score+=h,g.count+=1):s.set(p,{score:h,terms:d,count:1})}}catch(Z){r={error:Z}}finally{try{u&&!u.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],h=v.score,d=v.terms,z=v.count;w.push({suggestion:g,terms:d,score:h/z})}}catch(Z){o={error:Z}}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(xr.hasOwnProperty(n))return yr(xr,n);throw new Error('MiniSearch: unknown option "'.concat(n,'"'))},e.loadJS=function(n,t){var r,i,o,a,s,l,u=n.index,c=n.documentCount,h=n.nextId,d=n.documentIds,p=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=c,v._nextId=h,v._documentIds=$t(d),v._idToShortId=new Map,v._fieldIds=p,v._fieldLength=$t(g),v._avgFieldLength=w,v._storedFields=$t(k),v._dirtCount=y||0,v._index=new mr;try{for(var z=X(v._documentIds),Z=z.next();!Z.done;Z=z.next()){var x=$(Z.value,2),L=x[0],R=x[1];v._idToShortId.set(R,L)}}catch(ne){r={error:ne}}finally{try{Z&&!Z.done&&(i=z.return)&&i.call(z)}finally{if(r)throw r.error}}try{for(var M=X(u),P=M.next();!P.done;P=M.next()){var D=$(P.value,2),F=D[0],E=D[1],A=new Map;try{for(var N=(s=void 0,X(Object.keys(E))),H=N.next();!H.done;H=N.next()){var Y=H.value,re=E[Y];I===1&&(re=re.ds),A.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(F,A)}}catch(ne){o={error:ne}}finally{try{P&&!P.done&&(a=M.return)&&a.call(M)}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,u=a.searchOptions,c=J(J({tokenize:s,processTerm:l},u),t),h=c.tokenize,d=c.processTerm,p=h(n).flatMap(function(k){return d(k)}).filter(function(k){return!!k}),g=p.map(sl(c)),w=g.map(function(k){return r.executeQuerySpec(k,c)});return this.combineResults(w,c.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]=yr(s.boost,re)||1,ne))},{}),u=s.boostDocument,c=s.weights,h=s.maxFuzzy,d=s.bm25,p=J(J({},ji.weights),c),g=p.fuzzy,w=p.prefix,k=this._index.get(n.term),y=this.termResults(n.term,n.term,1,k,l,u,d),I,v;if(n.prefix&&(I=this._index.atPrefix(n.term)),n.fuzzy){var z=n.fuzzy===!0?.2:n.fuzzy,Z=z<1?Math.min(h,Math.round(n.term.length*z)):z;Z&&(v=this._index.fuzzyGet(n.term,Z))}if(I)try{for(var x=X(I),L=x.next();!L.done;L=x.next()){var R=$(L.value,2),M=R[0],P=R[1],D=M.length-n.term.length;if(D){v?.delete(M);var F=w*M.length/(M.length+.3*D);this.termResults(n.term,M,F,P,l,u,d,y)}}}catch(Y){r={error:Y}}finally{try{L&&!L.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}if(v)try{for(var E=X(v.keys()),A=E.next();!A.done;A=E.next()){var M=A.value,N=$(v.get(M),2),H=N[0],D=N[1];if(D){var F=g*M.length/(M.length+D);this.termResults(n.term,M,F,H,l,u,d,y)}}}catch(Y){o={error:Y}}finally{try{A&&!A.done&&(a=E.return)&&a.call(E)}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),u=l[0],c=l[1],h=o.boostDocument?o.boostDocument(c,"",this._storedFields.get(u)):1;i.set(u,{score:h,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),u=l[0],c=l[1],h={};try{for(var d=(r=void 0,X(c)),p=d.next();!p.done;p=d.next()){var g=$(p.value,2),w=g[0],k=g[1];h[w]=Object.fromEntries(k)}}catch(y){r={error:y}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(r)throw r.error}}o.push([u,h])}}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 u,c,h,d,p;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,Z=this._avgFieldLength[I];try{for(var x=(h=void 0,X(v.keys())),L=x.next();!L.done;L=x.next()){var R=L.value;if(!this._documentIds.has(R)){this.removeTerm(I,R,t),z-=1;continue}var M=a?a(this._documentIds.get(R),t,this._storedFields.get(R)):1;if(M){var P=v.get(R),D=this._fieldLength.get(R)[I],F=al(P,z,this._documentCount,D,Z,s),E=r*y*M*F,A=l.get(R);if(A){A.score+=E,ul(A.terms,n);var N=yr(A.match,t);N?N.push(k):A.match[t]=[k]}else l.set(R,{score:E,terms:[n],match:(p={},p[t]=[k],p)})}}}catch(H){h={error:H}}finally{try{L&&!L.done&&(d=x.return)&&d.call(x)}finally{if(h)throw h.error}}}}}catch(H){u={error:H}}finally{try{w&&!w.done&&(c=g.return)&&c.call(g)}finally{if(u)throw u.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(u){i={error:u}}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 u=X(a),c=u.next();!c.done;c=u.next()){var h=c.value,d=s(t,h);d!==void 0&&(l[h]=d)}}catch(p){r={error:p}}finally{try{c&&!c.done&&(i=u.return)&&i.call(u)}finally{if(r)throw r.error}}}},e.wildcard=Symbol("*"),e}(),yr=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),u=l.score,c=l.terms,h=l.match;s.score=s.score+u,s.match=Object.assign(s.match,h),Ji(s.terms,c)}}}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 u=n.get(s),c=u.score,h=u.terms,d=u.match;Ji(l.terms,h),i.set(s,{score:l.score+c,terms:l.terms,match:Object.assign(l.match,d)})}}}catch(p){t={error:p}}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,u=Math.log(1+(t-n+.5)/(n+.5));return u*(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}}},xr={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}},vr={batchSize:1e3,batchWait:10},kr={minDirtFactor:.1,minDirtCount:20},br=J(J({},vr),kr),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);n.updateKnowledgeBase(t),n.submitAnalyticsEvent({type:"kb-search",query:e.query,results:t});let r=t.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",i=t.filter(o=>o.type=="action").map(o=>"name="+o.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${r}. New tools available: ${i}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(e,n)=>{if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker.");return n.submitAnalyticsEvent({type:"open-url",url:e.url}),"URL opened"}}];var at=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){at.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{return await l.query(n)}catch(u){return at.warn(`Knowledge source '${l.id}' failed:`,u),[]}}))).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 u=i[l];if(u.id=u.id||`temp.${l}`,!u.action&&u.type=="tour"&&(u.action=c=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!u.action&&u.type=="info"&&(u.action=c=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),u.parameters&&!Array.isArray(u.parameters)){let c=u.parameters,h=[];for(let d in c)h.push({name:d,type:"string",description:u.parameters[d]});u.parameters=h}u.content=Ui(typeof u.content=="function"?u.content():u.content)}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(u=>u.id==l.id));for(let l of i)l.isContext&&(s.find(u=>u.id===l.id)||s.push(l));return this.lastResults=s,at.debug("Found results:",s),s}getCachedEntry(n){return this.lastResults.find(t=>t.id==n)}registerSourceFromURL(n,t){t||(t=`external.${so++}`),at.debug(`Registering remote knowledge base source: ${n}`);let r=[],i=async(a,s)=>{at.debug(`Calling remote knowledge base action: ${a.id}`);let l={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:a.id,parameters:s},u=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let c=await u.json();return o(c.updateItems||[]),c.response},o=a=>{for(let s of a){if(!s.id){at.warn("KB item skipped since it has no ID.",s);continue}let l=r.find(u=>u.id==s.id);if(l){l.name=s.name||l.name||"",l.content=s.content||l.content||"",l.disabled=s.disabled??l.disabled,l.isContext=s.isContext??l.isContext,l.parameters=s.parameters||l.parameters||[],l.tags=s.tags||l.tags,l.type=s.type||l.type;continue}r.push({...s,action:u=>i(s,u)})}};this.registerSource(t,async a=>{let s={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:a},l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let u=await l.json();return o(u.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.45",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=Ke(),localStorage.setItem("intelliweave.uid",e),e)}else return Ke()}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 Ze=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?.(),Ze.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){Ze.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;Ze.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&&Ze.warn(`Tool description for "${l.name}" is too long, it will be truncated.`);let u={type:"function",function:{name:l.name,description:(l.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(l.params))for(let c of l.params)u.function.parameters.properties[c.name]={type:c.type,description:c.description};else if(l.params){let c=l.params;for(let h in c)u.function.parameters.properties[h]={type:"string",description:c[h]}}r.tools.push(u)}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 c=await o.json();l=c.errorText||c.error?.message||c.error||l}catch{}let u=new Error(l);throw u.code=o.status,u}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 u=JSON.parse(l.data);if(s){for(let c in u.choices[0].delta)if(typeof u.choices[0].delta[c]=="string"){if(c=="role"&&s[c]==u.choices[0].delta[c])continue;s[c]=(s[c]||"")+u.choices[0].delta[c]}for(let c of u.choices[0].delta.tool_calls||[]){if(s.tool_calls||(s.tool_calls=[]),!s.tool_calls[c.index]){s.tool_calls[c.index]=c;continue}let h=s.tool_calls[c.index];h.function=h.function||{},h.function.name=(h.function.name||"")+(c.function?.name||""),h.function.arguments=(h.function.arguments||"")+(c.function?.arguments||"")}}else s={chunkID:u.id,...u.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,Ze.debug(`Used ${a.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),s=a.choices?.[0]?.message;if(s||(Ze.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){Ze.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&&Ze.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){Ze.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(c){try{u(r.next(c))}catch(h){a(h)}}function l(c){try{u(r.throw(c))}catch(h){a(h)}}function u(c){c.done?o(c.value):i(c.value).then(s,l)}u((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(u){return function(c){return l([u,c])}}function l(u){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(t=0)),t;)try{if(r=1,i&&(o=u[0]&2?i.return:u[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,u[1])).done)return o;switch(i=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,i=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){t.label=u[1];break}if(u[0]===6&&t.label<o[1]){t.label=o[1],o=u;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(u);break}o[2]&&t.ops.pop(),t.trys.pop();continue}u=n.call(e,t)}catch(c){u=[6,c],i=0}finally{r=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[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="",fr=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=ot(this._path),t=n.node,r=n.keys;if(ot(r)===le)return{done:!1,value:this.result()};var i=t.get(ot(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=ot(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 ot(t)}).filter(function(n){return n!==le}).join("")},e.prototype.value=function(){return ot(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}(),ot=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,u,c=o*a;try{e:for(var h=X(e.keys()),d=h.next();!d.done;d=h.next()){var p=d.value;if(p===le){var g=i[c-1];g<=t&&r.set(s,[e.get(p),g])}else{for(var w=o,k=0;k<p.length;++k,++w){for(var y=p[k],I=a*w,v=I-a,z=i[I],Z=Math.max(0,w-t-1),x=Math.min(a-1,w+t),L=Z;L<x;++L){var R=y!==n[L],M=i[v+L]+ +R,P=i[v+L+1]+1,D=i[I+L]+1,F=i[I+L+1]=Math.min(M,P,D);F<z&&(z=F)}if(z>t)continue e}to(e.get(p),n,t,r,i,w,a,s+p)}}}catch(E){l={error:E}}finally{try{d&&!d.done&&(u=h.return)&&u.call(h)}finally{if(l)throw l.error}}},mr=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=$(Sr(a),2),l=s[0],u=s[1];try{for(var c=X(l.keys()),h=c.next();!h.done;h=c.next()){var d=h.value;if(d!==le&&d.startsWith(u)){var p=new Map;return p.set(d.slice(u.length),l.get(d)),new e(p,n)}}}catch(g){t={error:g}}finally{try{h&&!h.done&&(r=c.return)&&r.call(c)}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 fr(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(u){t={error:u}}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=wr(this._tree,n);return t!==void 0?t.get(le):void 0},e.prototype.has=function(n){var t=wr(this._tree,n);return t!==void 0&&t.has(le)},e.prototype.keys=function(){return new fr(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=gr(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=gr(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=gr(this._tree,n),i=r.get(le);return i===void 0&&r.set(le,i=t()),i},e.prototype.values=function(){return new fr(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],u=s[1];i.set(l,u)}}catch(c){t={error:c}}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)},wr=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 wr(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}}},gr=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 u=Math.min(i-o,l.length),c=1;c<u&&n[o+c]===l[c];)++c;var h=e.get(l);if(c===l.length)e=h;else{var d=new Map;d.set(l.slice(c),h),e.set(n.slice(o,o+c),d),e.delete(l),e=d}o+=c;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 p=new Map;return e.set(n.slice(o),p),p}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=$(Sr(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=$(Sr(e),2),i=r[0],o=r[1];i.set(o+n,t),i.delete(o)}},Sr=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?br:n.autoVacuum;this._options=J(J(J({},xr),n),{autoVacuum:t,searchOptions:J(J({},ji),n.searchOptions||{}),autoSuggestOptions:J(J({},ll),n.autoSuggestOptions||{})}),this._index=new mr,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=kr,this.addFields(this._options.fields)}return e.prototype.add=function(n){var t,r,i,o,a,s,l=this._options,u=l.extractField,c=l.tokenize,h=l.processTerm,d=l.fields,p=l.idField,g=u(n,p);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(p,'"'));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=u(n,I);if(v!=null){var z=c(v.toString(),I),Z=this._fieldIds[I],x=new Set(z).size;this.addFieldLength(w,Z,this._documentCount-1,x);try{for(var L=(i=void 0,X(z)),R=L.next();!R.done;R=L.next()){var M=R.value,P=h(M,I);if(Array.isArray(P))try{for(var D=(a=void 0,X(P)),F=D.next();!F.done;F=D.next()){var E=F.value;this.addTerm(Z,w,E)}}catch(A){a={error:A}}finally{try{F&&!F.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else P&&this.addTerm(Z,w,P)}}catch(A){i={error:A}}finally{try{R&&!R.done&&(o=L.return)&&o.call(L)}finally{if(i)throw i.error}}}}}catch(A){t={error:A}}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(c,h,d){var p=c.chunk,g=c.promise;return p.push(h),(d+1)%o===0?{chunk:[],promise:g.then(function(){return new Promise(function(w){return setTimeout(w,0)})}).then(function(){return r.addAll(p)})}:{chunk:p,promise:g}},a),l=s.chunk,u=s.promise;return u.then(function(){return r.addAll(l)})},e.prototype.remove=function(n){var t,r,i,o,a,s,l=this._options,u=l.tokenize,c=l.processTerm,h=l.extractField,d=l.fields,p=l.idField,g=h(n,p);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(p,'"'));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=h(n,I);if(v!=null){var z=u(v.toString(),I),Z=this._fieldIds[I],x=new Set(z).size;this.removeFieldLength(w,Z,this._documentCount,x);try{for(var L=(i=void 0,X(z)),R=L.next();!R.done;R=L.next()){var M=R.value,P=c(M,I);if(Array.isArray(P))try{for(var D=(a=void 0,X(P)),F=D.next();!F.done;F=D.next()){var E=F.value;this.removeTerm(Z,w,E)}}catch(A){a={error:A}}finally{try{F&&!F.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else P&&this.removeTerm(Z,w,P)}}catch(A){i={error:A}}finally{try{R&&!R.done&&(o=L.return)&&o.call(L)}finally{if(i)throw i.error}}}}}catch(A){t={error:A}}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 mr,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=kr,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,u,c,h,d,p,g,w,k,y,I,v,z,Z,x,L,R,M,P,D;return $s(this,function(F){switch(F.label){case 0:if(r=this._dirtCount,!this.vacuumConditionsMet(t))return[3,10];i=n.batchSize||vr.batchSize,o=n.batchWait||vr.batchWait,a=1,F.label=1;case 1:F.trys.push([1,7,8,9]),s=X(this._index),l=s.next(),F.label=2;case 2:if(l.done)return[3,6];u=$(l.value,2),c=u[0],h=u[1];try{for(d=(R=void 0,X(h)),p=d.next();!p.done;p=d.next()){g=$(p.value,2),w=g[0],k=g[1];try{for(y=(P=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?h.delete(w):k.delete(z))}catch(E){P={error:E}}finally{try{I&&!I.done&&(D=y.return)&&D.call(y)}finally{if(P)throw P.error}}}}catch(E){R={error:E}}finally{try{p&&!p.done&&(M=d.return)&&M.call(d)}finally{if(R)throw R.error}}return this._index.get(c).size===0&&this._index.delete(c),a%i!==0?[3,4]:[4,new Promise(function(E){return setTimeout(E,o)})];case 3:F.sent(),F.label=4;case 4:a+=1,F.label=5;case 5:return l=s.next(),[3,2];case 6:return[3,9];case 7:return Z=F.sent(),x={error:Z},[3,9];case 8:try{l&&!l.done&&(L=s.return)&&L.call(s)}finally{if(x)throw x.error}return[7];case 9:this._dirtCount-=r,F.label=10;case 10:return[4,null];case 11:return F.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||br.minDirtCount,r=r||br.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 u=$(l.value,2),c=u[0],h=u[1],d=h.score,p=h.terms,g=h.match,w=p.length||1,k={id:this._documentIds.get(c),score:d*w,terms:Object.keys(g),queryTerms:p,match:g};Object.assign(k,this._storedFields.get(c)),(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)),u=l.next();!u.done;u=l.next()){var c=u.value,h=c.score,d=c.terms,p=d.join(" "),g=s.get(p);g!=null?(g.score+=h,g.count+=1):s.set(p,{score:h,terms:d,count:1})}}catch(Z){r={error:Z}}finally{try{u&&!u.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],h=v.score,d=v.terms,z=v.count;w.push({suggestion:g,terms:d,score:h/z})}}catch(Z){o={error:Z}}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(xr.hasOwnProperty(n))return yr(xr,n);throw new Error('MiniSearch: unknown option "'.concat(n,'"'))},e.loadJS=function(n,t){var r,i,o,a,s,l,u=n.index,c=n.documentCount,h=n.nextId,d=n.documentIds,p=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=c,v._nextId=h,v._documentIds=$t(d),v._idToShortId=new Map,v._fieldIds=p,v._fieldLength=$t(g),v._avgFieldLength=w,v._storedFields=$t(k),v._dirtCount=y||0,v._index=new mr;try{for(var z=X(v._documentIds),Z=z.next();!Z.done;Z=z.next()){var x=$(Z.value,2),L=x[0],R=x[1];v._idToShortId.set(R,L)}}catch(ne){r={error:ne}}finally{try{Z&&!Z.done&&(i=z.return)&&i.call(z)}finally{if(r)throw r.error}}try{for(var M=X(u),P=M.next();!P.done;P=M.next()){var D=$(P.value,2),F=D[0],E=D[1],A=new Map;try{for(var N=(s=void 0,X(Object.keys(E))),H=N.next();!H.done;H=N.next()){var Y=H.value,re=E[Y];I===1&&(re=re.ds),A.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(F,A)}}catch(ne){o={error:ne}}finally{try{P&&!P.done&&(a=M.return)&&a.call(M)}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,u=a.searchOptions,c=J(J({tokenize:s,processTerm:l},u),t),h=c.tokenize,d=c.processTerm,p=h(n).flatMap(function(k){return d(k)}).filter(function(k){return!!k}),g=p.map(sl(c)),w=g.map(function(k){return r.executeQuerySpec(k,c)});return this.combineResults(w,c.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]=yr(s.boost,re)||1,ne))},{}),u=s.boostDocument,c=s.weights,h=s.maxFuzzy,d=s.bm25,p=J(J({},ji.weights),c),g=p.fuzzy,w=p.prefix,k=this._index.get(n.term),y=this.termResults(n.term,n.term,1,k,l,u,d),I,v;if(n.prefix&&(I=this._index.atPrefix(n.term)),n.fuzzy){var z=n.fuzzy===!0?.2:n.fuzzy,Z=z<1?Math.min(h,Math.round(n.term.length*z)):z;Z&&(v=this._index.fuzzyGet(n.term,Z))}if(I)try{for(var x=X(I),L=x.next();!L.done;L=x.next()){var R=$(L.value,2),M=R[0],P=R[1],D=M.length-n.term.length;if(D){v?.delete(M);var F=w*M.length/(M.length+.3*D);this.termResults(n.term,M,F,P,l,u,d,y)}}}catch(Y){r={error:Y}}finally{try{L&&!L.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}if(v)try{for(var E=X(v.keys()),A=E.next();!A.done;A=E.next()){var M=A.value,N=$(v.get(M),2),H=N[0],D=N[1];if(D){var F=g*M.length/(M.length+D);this.termResults(n.term,M,F,H,l,u,d,y)}}}catch(Y){o={error:Y}}finally{try{A&&!A.done&&(a=E.return)&&a.call(E)}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),u=l[0],c=l[1],h=o.boostDocument?o.boostDocument(c,"",this._storedFields.get(u)):1;i.set(u,{score:h,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),u=l[0],c=l[1],h={};try{for(var d=(r=void 0,X(c)),p=d.next();!p.done;p=d.next()){var g=$(p.value,2),w=g[0],k=g[1];h[w]=Object.fromEntries(k)}}catch(y){r={error:y}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(r)throw r.error}}o.push([u,h])}}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 u,c,h,d,p;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,Z=this._avgFieldLength[I];try{for(var x=(h=void 0,X(v.keys())),L=x.next();!L.done;L=x.next()){var R=L.value;if(!this._documentIds.has(R)){this.removeTerm(I,R,t),z-=1;continue}var M=a?a(this._documentIds.get(R),t,this._storedFields.get(R)):1;if(M){var P=v.get(R),D=this._fieldLength.get(R)[I],F=al(P,z,this._documentCount,D,Z,s),E=r*y*M*F,A=l.get(R);if(A){A.score+=E,ul(A.terms,n);var N=yr(A.match,t);N?N.push(k):A.match[t]=[k]}else l.set(R,{score:E,terms:[n],match:(p={},p[t]=[k],p)})}}}catch(H){h={error:H}}finally{try{L&&!L.done&&(d=x.return)&&d.call(x)}finally{if(h)throw h.error}}}}}catch(H){u={error:H}}finally{try{w&&!w.done&&(c=g.return)&&c.call(g)}finally{if(u)throw u.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(u){i={error:u}}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 u=X(a),c=u.next();!c.done;c=u.next()){var h=c.value,d=s(t,h);d!==void 0&&(l[h]=d)}}catch(p){r={error:p}}finally{try{c&&!c.done&&(i=u.return)&&i.call(u)}finally{if(r)throw r.error}}}},e.wildcard=Symbol("*"),e}(),yr=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),u=l.score,c=l.terms,h=l.match;s.score=s.score+u,s.match=Object.assign(s.match,h),Ji(s.terms,c)}}}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 u=n.get(s),c=u.score,h=u.terms,d=u.match;Ji(l.terms,h),i.set(s,{score:l.score+c,terms:l.terms,match:Object.assign(l.match,d)})}}}catch(p){t={error:p}}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,u=Math.log(1+(t-n+.5)/(n+.5));return u*(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}}},xr={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}},vr={batchSize:1e3,batchWait:10},kr={minDirtFactor:.1,minDirtCount:20},br=J(J({},vr),kr),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);n.updateKnowledgeBase(t),n.submitAnalyticsEvent({type:"kb-search",query:e.query,results:t});let r=t.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",i=t.filter(o=>o.type=="action").map(o=>"name="+o.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${r}. New tools available: ${i}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(e,n)=>{if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker.");return n.submitAnalyticsEvent({type:"open-url",url:e.url}),"URL opened"}}];var at=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){at.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{return await l.query(n)}catch(u){return at.warn(`Knowledge source '${l.id}' failed:`,u),[]}}))).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 u=i[l];if(u.id=u.id||`temp.${l}`,!u.action&&u.type=="tour"&&(u.action=c=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!u.action&&u.type=="info"&&(u.action=c=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),u.parameters&&!Array.isArray(u.parameters)){let c=u.parameters,h=[];for(let d in c)h.push({name:d,type:"string",description:u.parameters[d]});u.parameters=h}u.content=Ui(typeof u.content=="function"?u.content():u.content)}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(u=>u.id==l.id));for(let l of i)l.isContext&&(s.find(u=>u.id===l.id)||s.push(l));return this.lastResults=s,at.debug("Found results:",s),s}getCachedEntry(n){return this.lastResults.find(t=>t.id==n)}registerSourceFromURL(n,t){t||(t=`external.${so++}`),at.debug(`Registering remote knowledge base source: ${n}`);let r=[],i=async(a,s)=>{at.debug(`Calling remote knowledge base action: ${a.id}`);let l={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:a.id,parameters:s},u=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let c=await u.json();return o(c.updateItems||[]),c.response},o=a=>{for(let s of a){if(!s.id){at.warn("KB item skipped since it has no ID.",s);continue}let l=r.find(u=>u.id==s.id);if(l){l.name=s.name||l.name||"",l.content=s.content||l.content||"",l.disabled=s.disabled??l.disabled,l.isContext=s.isContext??l.isContext,l.parameters=s.parameters||l.parameters||[],l.tags=s.tags||l.tags,l.type=s.type||l.type;continue}r.push({...s,action:u=>i(s,u)})}};this.registerSource(t,async a=>{let s={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:a},l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let u=await l.json();return o(u.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.46",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
|
|
|
@@ -397,7 +397,7 @@ You have access to a database of knowledge base items. These include "info" type
|
|
|
397
397
|
|
|
398
398
|
</div>
|
|
399
399
|
|
|
400
|
-
`;this._isProcessing=!1;this.ai=new st,yt.isSupported&&(this.ai.audio=new yt(this.ai))}onCreate(){Q().embed&&Vi.warn("Only one <web-weaver-embed> element should be on the page."),Q().embed=this,this.child("root").addEventListener("click",i=>this.onContainerClick(i)),this.child("web-weaver-logo").addEventListener("click",i=>this.onLogoClick(i)),this.child("interaction-bar").addEventListener("input-message",i=>this.processInput(i.detail)),this.child("interaction-bar").addEventListener("llm-button-click",i=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",i=>this.onLLMModelSelect(i)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.onAIToolStart=this.onAIToolStart.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.focusElement",type:"action",name:"Focus on an element",content:"Focuses and draws the user's attention to an HTML element on the page.",isContext:!0,parameters:[{name:"elementID",type:"string",description:"The HTML ID of the element to focus."}],action:i=>{let o=i.elementID||"";if(o.startsWith("#")&&(o=o.substring(1)),!o)throw new Error("No element ID specified.");let a=document.getElementById(o);if(!a)throw new Error(`Could not find the element with ID "${o}".`);a.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),this.attr.focusID=o,this.ai.submitAnalyticsEvent({type:"focus-element",elementID:o})}}),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:i=>(this.suggestions.push(i.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:i.text}),"Suggestion button added")});let r=this.attr.apiKey||Q().apiKey;if(!r)return Vi.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.ai.load(r).then(i=>{this.config=i,Q().introductionMessage=this.config.introductionMessage,Q().analytics=this.config.analytics!==void 0?!!this.config.analytics:Q().analytics,this.state.loading=!1,this.resetConversation()})}onUpdate(){this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("root").className=this.attr.open?"open":"",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("root").style.right=this.attr.offsetX?this.attr.offsetX+"px":"20px",this.child("root").style.bottom=this.attr.offsetY?this.attr.offsetY+"px":"20px",this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1;let t=this.child("web-weaver-logo");t.attr.focusID=this.attr.focusID,t.refreshLayout(),this.child("llm-selector-panel").state.items=this.ai.models.sort((r,i)=>(i.priority||0)-(r.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){Q().embed==this&&(Q().embed=null)}onContainerClick(t){this.attr.open||(t.preventDefault(),this.attr.open=!0)}onLogoClick(t){t.preventDefault(),t.stopPropagation(),this.attr.focusID?this.attr.focusID="":this.attr.open=!this.attr.open}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let t=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;t.children.length>0;)t.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let r=document.createElement("div");r.className="introduction-message",r.innerHTML=Q().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,t.appendChild(r),this.ai.insertAssistantMessage(r.innerText);for(let i of Q().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",a=>this.onSuggestionClick(a,i)),t.appendChild(o)}}async processInput(t){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let r=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let o of Array.from(r.querySelectorAll(".suggestion-button")))o.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=t,r.appendChild(i),r.scrollBy({top:1e5,behavior:"smooth"}),await this.ai.sendMessage(t);for(let o of this.suggestions){let a=document.createElement("div");a.className="suggestion-button",a.innerText=o,a.addEventListener("click",s=>this.onSuggestionClick(s,o)),r.appendChild(a)}r.scrollBy({top:1e5,behavior:"smooth"})}catch(i){Vi.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,r.appendChild(o);let a=document.createElement("div");a.className="suggestion-button",a.innerText="Reset conversation",a.addEventListener("click",s=>this.resetConversation()),r.appendChild(a)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(t){let r=await Li().use(Vn).use(On).use(fn,{target:"_blank",rel:["noopener","noreferrer"]}).use(gn).use(En).processSync(t),i=this.child("web-weaver-embed-inner"),o=i.lastElementChild;if(o&&o.classList.contains("output"))o.innerHTML=r.toString("utf-8");else{let a=document.createElement("div");a.className="output",a.innerHTML=r.toString("utf-8"),i.appendChild(a)}for(let a of Array.from(i.querySelectorAll(".tool")))a.remove();i.scrollBy({top:1e6,behavior:"smooth"})}onAIToolStart(t,r){let i=`Running: ${t}`;t=="search"&&(i=`Searching: ${r?.query}`),t=="ui.focusElement"&&(i=`Focusing: #${r?.elementID}`),t=="ui.suggestResponse"&&(i=`Suggested response: ${r?.text}`);let o=this.child("web-weaver-embed-inner"),a=document.createElement("div");a.className="tool",a.innerText=i,o.appendChild(a),o.scrollBy({top:1e5,behavior:"smooth"})}onSuggestionClick(t,r){this.processInput(r)}onLLMModelSelect(t){t.preventDefault(),this.ai.setModel(t.detail),this.state.llmPanelOpen=!1}};tt.tagName="intelliweave-embed",tt.observedAttributes=["logo"];Ee.lib=()=>import("./ort.bundle.min-5QOPZPPI.js");document.body.appendChild(tt.create());
|
|
400
|
+
`;this._isProcessing=!1;this.ai=new st,yt.isSupported&&(this.ai.audio=new yt(this.ai))}onCreate(){Q().embed&&Vi.warn("Only one <web-weaver-embed> element should be on the page."),Q().embed=this,this.child("root").addEventListener("click",i=>this.onContainerClick(i)),this.child("web-weaver-logo").addEventListener("click",i=>this.onLogoClick(i)),this.child("interaction-bar").addEventListener("input-message",i=>this.processInput(i.detail)),this.child("interaction-bar").addEventListener("llm-button-click",i=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",i=>this.onLLMModelSelect(i)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.onAIToolStart=this.onAIToolStart.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.focusElement",type:"action",name:"Focus on an element",content:"Focuses and draws the user's attention to an HTML element on the page.",isContext:!0,parameters:[{name:"elementID",type:"string",description:"The HTML ID of the element to focus."}],action:i=>{let o=i.elementID||"";if(o.startsWith("#")&&(o=o.substring(1)),!o)throw new Error("No element ID specified.");let a=document.getElementById(o);if(!a)throw new Error(`Could not find the element with ID "${o}".`);a.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),this.attr.focusID=o,this.ai.submitAnalyticsEvent({type:"focus-element",elementID:o})}}),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:i=>(this.suggestions.push(i.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:i.text}),"Suggestion button added")});let r=this.attr.apiKey||Q().apiKey;if(!r)return Vi.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.ai.load(r).then(i=>{this.config=i,Q().introductionMessage=this.config.introductionMessage,Q().analytics=this.config.analytics!==void 0?!!this.config.analytics:Q().analytics,this.state.loading=!1,this.resetConversation()})}onUpdate(){this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("root").className=this.attr.open?"open":"",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("root").style.right=this.attr.offsetX?this.attr.offsetX+"px":"20px",this.child("root").style.bottom=this.attr.offsetY?this.attr.offsetY+"px":"20px",this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1;let t=this.child("web-weaver-logo");t.attr.focusID=this.attr.focusID,t.refreshLayout(),this.child("llm-selector-panel").state.items=this.ai.models.sort((r,i)=>(i.priority||0)-(r.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){Q().embed==this&&(Q().embed=null)}onContainerClick(t){this.attr.open||(t.preventDefault(),this.attr.open=!0)}onLogoClick(t){t.preventDefault(),t.stopPropagation(),this.attr.focusID?this.attr.focusID="":this.attr.open=!this.attr.open}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let t=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;t.children.length>0;)t.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let r=document.createElement("div");r.className="introduction-message",r.innerHTML=Q().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,t.appendChild(r),this.ai.insertAssistantMessage(r.innerText);for(let i of Q().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",a=>this.onSuggestionClick(a,i)),t.appendChild(o)}}async processInput(t){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let r=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let o of Array.from(r.querySelectorAll(".suggestion-button")))o.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=t,r.appendChild(i),r.scrollBy({top:1e5,behavior:"smooth"}),await this.ai.sendMessage(t);for(let o of this.suggestions){let a=document.createElement("div");a.className="suggestion-button",a.innerText=o,a.addEventListener("click",s=>this.onSuggestionClick(s,o)),r.appendChild(a)}r.scrollBy({top:1e5,behavior:"smooth"})}catch(i){Vi.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,r.appendChild(o);let a=document.createElement("div");a.className="suggestion-button",a.innerText="Reset conversation",a.addEventListener("click",s=>this.resetConversation()),r.appendChild(a)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(t){let r=await Li().use(Vn).use(On).use(fn,{target:"_blank",rel:["noopener","noreferrer"]}).use(gn).use(En).processSync(t),i=this.child("web-weaver-embed-inner"),o=i.lastElementChild;if(o&&o.classList.contains("output"))o.innerHTML=r.toString("utf-8");else{let a=document.createElement("div");a.className="output",a.innerHTML=r.toString("utf-8"),i.appendChild(a)}for(let a of Array.from(i.querySelectorAll(".tool")))a.remove();i.scrollBy({top:1e6,behavior:"smooth"})}onAIToolStart(t,r){let i=`Running: ${t}`;t=="search"&&(i=`Searching: ${r?.query}`),t=="ui.focusElement"&&(i=`Focusing: #${r?.elementID}`),t=="ui.suggestResponse"&&(i=`Suggested response: ${r?.text}`);let o=this.child("web-weaver-embed-inner"),a=document.createElement("div");a.className="tool",a.innerText=i,o.appendChild(a),o.scrollBy({top:1e5,behavior:"smooth"})}onSuggestionClick(t,r){this.processInput(r)}onLLMModelSelect(t){t.preventDefault(),this.ai.setModel(t.detail),this.state.llmPanelOpen=!1}};tt.tagName="intelliweave-embed",tt.observedAttributes=["logo","focusID","open"];Ee.lib=()=>import("./ort.bundle.min-5QOPZPPI.js");document.body.appendChild(tt.create());
|
|
401
401
|
/*! Bundled license information:
|
|
402
402
|
|
|
403
403
|
react/cjs/react.production.min.js:
|
package/dist/webpack/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import{v4 as le}from"uuid";function ce(c){let i=(c||"").split(`
|
|
|
6
6
|
`);for(let l of o){n=l.indexOf(": ");let d=l.slice(0,n),p=l.slice(n+2);n==-1&&(d=l,p=""),d&&(r[d]!==void 0?r[d]+=`
|
|
7
7
|
`+p:r[d]=p)}yield r}},t=new TextDecoder,s=c.getReader();for(;;){let{done:n,value:a}=await s.read();if(n)break;i+=t.decode(a,{stream:!0}),yield*e()}i+=t.decode()+`
|
|
8
8
|
|
|
9
|
-
`,yield*e()}function he(){if(h().userID)return h().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=le(),localStorage.setItem("intelliweave.uid",c),c)}else return le()}var L=class L{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return L.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)}};L.debug=!1;var u=L;var G=new u("ONNXModel"),y=class c{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,G.debug(`Model input parameters: ${i.inputNames.join(", ")}`),G.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||(G.debug("Loading ONNX runtime"),this.onnx=await c.lib()),G.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 a of e)s*=a;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 G.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(){G.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var ue="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWx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9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Ve=new u("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){Ve.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 u("SpeechOutput"),me=.5,Te=.8,F=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-${ke++}`;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",a=>{let r=a;e(`PCM stream ${r.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==s&&!r.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)}},ke=1;function K(c,i){let e=i.reduce((o,l)=>o+l.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,a=s*n/8,r=c*a;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,r,!0),t.setUint16(32,a,!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 a=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!a.includes(s))throw new Error(`Invalid format ${s}, must be one of: ${a.join(", ")}`);if(!n||n<=0)throw new Error(`Invalid buffer size: ${n}`);this.port.onmessage=r=>this.onWorkletMessage(r),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 ie=16e3,A=256,X=8,I=new u("VoiceDetectionNode"),R=class R extends z{constructor(e){super(e,ie,"float32",A*X);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 ie}get numberOfSamples(){return A}get numberOfSampleChunks(){return X}get outputBufferSize(){return A*X}get isModelLoaded(){return!!this.vad}async loadModel(){I.debug("Loading VAD model"),this.vad=await y.load(R.vadModelURL),this.vad.ignoreIfBusy=!0,I.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],ie),this.vad.makeState("h","hn","float32",[2,X,64]),this.vad.makeState("c","cn","float32",[2,X,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new y.onnx.Tensor(e,[X,A])});if(!t)return;this.currentProbability=0;for(let a=0;a<t.output.data.length;a++)t.output.data[a]>this.currentProbability&&(this.currentProbability=t.output.data[a]);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(),I.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(),I.debug("Stopped speaking after timeout")),!n){let a=Date.now();a>this.nextVadReset&&(this.nextVadReset=a+5e3,this.vad.resetState())}}catch(t){I.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};R.vadModelURL="";var C=R;var ge=new u("VoiceChunkOutputNode"),W=class extends C{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 N=new u("OpenAITranscriptionNode"),H=class extends W{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=N.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=K(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let n="";try{let a=new FormData;a.append("file",s),a.append("model","whisper-1"),a.append("response_format","text");let r=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:a,signal:this.lastRequestAbortController.signal});if(!r.ok)throw new Error(`Failed to generate voice sample: ${r.status} ${r.statusText}`);t("Response received"),n=await r.text(),t("Content received: "+n),this.lastRequestAbortController=void 0}catch(a){N.error(`Failed to transcribe speech: ${a.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return N.debug("Transcription complete, but no text was found");N.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var D=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 u("IntelliWeaveTranscriptionNode"),Le="wss://speech.intelliweave.ai/api/v1/transcribe",J=class J extends W{constructor(e,t){super(e);this.apiAddress=Le;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 D(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=K(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 Y=J;var se=new u("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),C.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new H(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new Y(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=se.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){se.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;se.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 u("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 F(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],a=n.length-this.partialBufferOffset;a<s?(e.set(n.subarray(this.partialBufferOffset),t),t+=a,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,a,r,o,l,d,p,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,a=this.lastWeight,r=0,o=0,l=0,d=0,p=this.outputBuffer;a<1;a+=n)for(o=a%1,r=1-o,this.lastWeight=a%1,m=0;m<this.channels;++m)p[d++]=this.lastOutput[m]*r+i[m]*o;for(a-=1,e-=t,l=Math.floor(a)*t;d<s&&l<e;){for(o=a%1,r=1-o,m=0;m<this.channels;++m)p[d++]=i[l+(m>0?m:0)]*r+i[l+(t+m)]*o;a+=n,l=Math.floor(a)*t}for(m=0;m<t;++m)this.lastOutput[m]=i[l++];return this.bufferSlice(d)}}multiTap(){this.resampler=i=>{let e=i.length,t,s,n=this.channels,a,r,o,l,d,p,m,T,k;if(e%n!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(t=this.outputBufferSize,s=[],a=this.ratioWeight,r=0,l=0,d=0,p=!this.tailExists,this.tailExists=!1,m=this.outputBuffer,T=0,k=0,o=0;o<n;++o)s[o]=0;do{if(p)for(r=a,o=0;o<n;++o)s[o]=0;else{for(r=this.lastWeight,o=0;o<n;++o)s[o]=this.lastOutput[o];p=!0}for(;r>0&&l<e;)if(d=1+l-k,r>=d){for(o=0;o<n;++o)s[o]+=i[l++]*d;k=l,r-=d}else{for(o=0;o<n;++o)s[o]+=i[l+(o>0?o:0)]*r;k+=r,r=0;break}if(r===0)for(o=0;o<n;++o)m[T++]=s[o]/a;else{for(this.lastWeight=r,o=0;o<n;++o)this.lastOutput[o]=s[o];this.tailExists=!0;break}}while(l<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 Yt(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 u("ChatGPT"),_=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 o=this.messages.length-1;o>=0;o--)if(this.messages[o].role=="assistant"&&this.messages[o].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[o].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 o of this.tools){o.description&&o.description.length>1024&&b.warn(`Tool description for "${o.name}" is too long, it will be truncated.`);let l={type:"function",function:{name:o.name,description:(o.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(o.params))for(let d of o.params)l.function.parameters.properties[d.name]={type:d.type,description:d.description};else if(o.params){let d=o.params;for(let p in d)l.function.parameters.properties[p]={type:"string",description:d[p]}}t.tools.push(l)}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 o=`${n.status} ${n.statusText}`;try{let d=await n.json();o=d.errorText||d.error?.message||d.error||o}catch{}let l=new Error(o);throw l.code=n.status,l}let a=null,r=null;if(this.config.stream)for await(let o of de(n.body)){if(o.data=="[DONE]")break;if(!o.data)continue;let l=JSON.parse(o.data);if(r){for(let d in l.choices[0].delta)if(typeof l.choices[0].delta[d]=="string"){if(d=="role"&&r[d]==l.choices[0].delta[d])continue;r[d]=(r[d]||"")+l.choices[0].delta[d]}for(let d of l.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[d.index]){r.tool_calls[d.index]=d;continue}let p=r.tool_calls[d.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(d.function?.name||""),p.function.arguments=(p.function.arguments||"")+(d.function?.arguments||"")}}else r={chunkID:l.id,...l.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}else a=await n.json(),this.stats.tokensUsed+=a.usage?.total_tokens||0,b.debug(`Used ${a.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),r=a.choices?.[0]?.message;if(r||(b.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){b.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(n=>n.role!="assistant"||!n.tool_calls?.find(a=>a.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);i.updateKnowledgeBase(e),i.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let t=e.filter(n=>n.type!="action").map(n=>"id="+n.id).join(", ")||"(none)",s=e.filter(n=>n.type=="action").map(n=>"name="+n.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${t}. New tools available: ${s}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(c,i)=>{if(!window.open(c.url,"_blank"))throw new Error("Window blocked by popup blocker.");return i.submitAnalyticsEvent({type:"open-url",url:c.url}),"URL opened"}}];var S=new u("KnowledgeBase"),ve=1,j=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"&&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){S.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 o=>{try{return await o.query(i)}catch(l){return S.warn(`Knowledge source '${o.id}' failed:`,l),[]}}))).flat();s=s.concat(e.entries),s=s.concat(this.manualEntries),h().knowledgeBase&&(s=s.concat(h().knowledgeBase)),s=s.filter(o=>o&&!o.disabled);for(let o=0;o<s.length;o++){let l=s[o];if(l.id=l.id||`temp.${o}`,!l.action&&l.type=="tour"&&(l.action=d=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=d=>{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 d=l.parameters,p=[];for(let m in d)p.push({name:m,type:"string",description:l.parameters[m]});l.parameters=p}l.content=ce(typeof l.content=="function"?l.content():l.content)}let n=new Be({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});n.addAll(s);let r=n.search(i).map(o=>s.find(l=>l.id==o.id));for(let o of s)o.isContext&&(r.find(l=>l.id===o.id)||r.push(o));return this.lastResults=r,S.debug("Found results:",r),r}getCachedEntry(i){return this.lastResults.find(e=>e.id==i)}registerSourceFromURL(i,e){e||(e=`external.${ve++}`),S.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=async(a,r)=>{S.debug(`Calling remote knowledge base action: ${a.id}`);let o={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:a.id,parameters:r},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let d=await l.json();return n(d.updateItems||[]),d.response},n=a=>{for(let r of a){if(!r.id){S.warn("KB item skipped since it has no ID.",r);continue}let o=t.find(l=>l.id==r.id);if(o){o.name=r.name||o.name||"",o.content=r.content||o.content||"",o.disabled=r.disabled??o.disabled,o.isContext=r.isContext??o.isContext,o.parameters=r.parameters||o.parameters||[],o.tags=r.tags||o.tags,o.type=r.type||o.type;continue}t.push({...r,action:l=>s(r,l)})}};this.registerSource(e,async a=>{let r={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:a},o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`HTTP Error ${o.status} ${o.statusText}`);let l=await o.json();return n(l.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.45",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 Q=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(h().userID)return h().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=le(),localStorage.setItem("intelliweave.uid",c),c)}else return le()}var L=class L{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return L.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)}};L.debug=!1;var u=L;var G=new u("ONNXModel"),y=class c{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,G.debug(`Model input parameters: ${i.inputNames.join(", ")}`),G.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||(G.debug("Loading ONNX runtime"),this.onnx=await c.lib()),G.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 a of e)s*=a;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 G.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(){G.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var ue="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3IoO3IhPXQubGVuZ3RoOyl7aWYocj50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZm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Qcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Ve=new u("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){Ve.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 u("SpeechOutput"),me=.5,Te=.8,F=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-${ke++}`;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",a=>{let r=a;e(`PCM stream ${r.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==s&&!r.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)}},ke=1;function K(c,i){let e=i.reduce((o,l)=>o+l.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,a=s*n/8,r=c*a;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,r,!0),t.setUint16(32,a,!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 a=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!a.includes(s))throw new Error(`Invalid format ${s}, must be one of: ${a.join(", ")}`);if(!n||n<=0)throw new Error(`Invalid buffer size: ${n}`);this.port.onmessage=r=>this.onWorkletMessage(r),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 ie=16e3,A=256,X=8,I=new u("VoiceDetectionNode"),R=class R extends z{constructor(e){super(e,ie,"float32",A*X);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 ie}get numberOfSamples(){return A}get numberOfSampleChunks(){return X}get outputBufferSize(){return A*X}get isModelLoaded(){return!!this.vad}async loadModel(){I.debug("Loading VAD model"),this.vad=await y.load(R.vadModelURL),this.vad.ignoreIfBusy=!0,I.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],ie),this.vad.makeState("h","hn","float32",[2,X,64]),this.vad.makeState("c","cn","float32",[2,X,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new y.onnx.Tensor(e,[X,A])});if(!t)return;this.currentProbability=0;for(let a=0;a<t.output.data.length;a++)t.output.data[a]>this.currentProbability&&(this.currentProbability=t.output.data[a]);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(),I.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(),I.debug("Stopped speaking after timeout")),!n){let a=Date.now();a>this.nextVadReset&&(this.nextVadReset=a+5e3,this.vad.resetState())}}catch(t){I.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};R.vadModelURL="";var C=R;var ge=new u("VoiceChunkOutputNode"),W=class extends C{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 N=new u("OpenAITranscriptionNode"),H=class extends W{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=N.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=K(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let n="";try{let a=new FormData;a.append("file",s),a.append("model","whisper-1"),a.append("response_format","text");let r=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:a,signal:this.lastRequestAbortController.signal});if(!r.ok)throw new Error(`Failed to generate voice sample: ${r.status} ${r.statusText}`);t("Response received"),n=await r.text(),t("Content received: "+n),this.lastRequestAbortController=void 0}catch(a){N.error(`Failed to transcribe speech: ${a.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return N.debug("Transcription complete, but no text was found");N.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var D=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 u("IntelliWeaveTranscriptionNode"),Le="wss://speech.intelliweave.ai/api/v1/transcribe",J=class J extends W{constructor(e,t){super(e);this.apiAddress=Le;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 D(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=K(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 Y=J;var se=new u("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),C.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new H(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new Y(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=se.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){se.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;se.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 u("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 F(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],a=n.length-this.partialBufferOffset;a<s?(e.set(n.subarray(this.partialBufferOffset),t),t+=a,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,a,r,o,l,d,p,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,a=this.lastWeight,r=0,o=0,l=0,d=0,p=this.outputBuffer;a<1;a+=n)for(o=a%1,r=1-o,this.lastWeight=a%1,m=0;m<this.channels;++m)p[d++]=this.lastOutput[m]*r+i[m]*o;for(a-=1,e-=t,l=Math.floor(a)*t;d<s&&l<e;){for(o=a%1,r=1-o,m=0;m<this.channels;++m)p[d++]=i[l+(m>0?m:0)]*r+i[l+(t+m)]*o;a+=n,l=Math.floor(a)*t}for(m=0;m<t;++m)this.lastOutput[m]=i[l++];return this.bufferSlice(d)}}multiTap(){this.resampler=i=>{let e=i.length,t,s,n=this.channels,a,r,o,l,d,p,m,T,k;if(e%n!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(t=this.outputBufferSize,s=[],a=this.ratioWeight,r=0,l=0,d=0,p=!this.tailExists,this.tailExists=!1,m=this.outputBuffer,T=0,k=0,o=0;o<n;++o)s[o]=0;do{if(p)for(r=a,o=0;o<n;++o)s[o]=0;else{for(r=this.lastWeight,o=0;o<n;++o)s[o]=this.lastOutput[o];p=!0}for(;r>0&&l<e;)if(d=1+l-k,r>=d){for(o=0;o<n;++o)s[o]+=i[l++]*d;k=l,r-=d}else{for(o=0;o<n;++o)s[o]+=i[l+(o>0?o:0)]*r;k+=r,r=0;break}if(r===0)for(o=0;o<n;++o)m[T++]=s[o]/a;else{for(this.lastWeight=r,o=0;o<n;++o)this.lastOutput[o]=s[o];this.tailExists=!0;break}}while(l<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 Yt(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 u("ChatGPT"),_=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 o=this.messages.length-1;o>=0;o--)if(this.messages[o].role=="assistant"&&this.messages[o].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[o].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 o of this.tools){o.description&&o.description.length>1024&&b.warn(`Tool description for "${o.name}" is too long, it will be truncated.`);let l={type:"function",function:{name:o.name,description:(o.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(o.params))for(let d of o.params)l.function.parameters.properties[d.name]={type:d.type,description:d.description};else if(o.params){let d=o.params;for(let p in d)l.function.parameters.properties[p]={type:"string",description:d[p]}}t.tools.push(l)}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 o=`${n.status} ${n.statusText}`;try{let d=await n.json();o=d.errorText||d.error?.message||d.error||o}catch{}let l=new Error(o);throw l.code=n.status,l}let a=null,r=null;if(this.config.stream)for await(let o of de(n.body)){if(o.data=="[DONE]")break;if(!o.data)continue;let l=JSON.parse(o.data);if(r){for(let d in l.choices[0].delta)if(typeof l.choices[0].delta[d]=="string"){if(d=="role"&&r[d]==l.choices[0].delta[d])continue;r[d]=(r[d]||"")+l.choices[0].delta[d]}for(let d of l.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[d.index]){r.tool_calls[d.index]=d;continue}let p=r.tool_calls[d.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(d.function?.name||""),p.function.arguments=(p.function.arguments||"")+(d.function?.arguments||"")}}else r={chunkID:l.id,...l.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}else a=await n.json(),this.stats.tokensUsed+=a.usage?.total_tokens||0,b.debug(`Used ${a.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),r=a.choices?.[0]?.message;if(r||(b.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){b.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(n=>n.role!="assistant"||!n.tool_calls?.find(a=>a.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);i.updateKnowledgeBase(e),i.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let t=e.filter(n=>n.type!="action").map(n=>"id="+n.id).join(", ")||"(none)",s=e.filter(n=>n.type=="action").map(n=>"name="+n.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${t}. New tools available: ${s}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(c,i)=>{if(!window.open(c.url,"_blank"))throw new Error("Window blocked by popup blocker.");return i.submitAnalyticsEvent({type:"open-url",url:c.url}),"URL opened"}}];var S=new u("KnowledgeBase"),ve=1,j=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"&&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){S.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 o=>{try{return await o.query(i)}catch(l){return S.warn(`Knowledge source '${o.id}' failed:`,l),[]}}))).flat();s=s.concat(e.entries),s=s.concat(this.manualEntries),h().knowledgeBase&&(s=s.concat(h().knowledgeBase)),s=s.filter(o=>o&&!o.disabled);for(let o=0;o<s.length;o++){let l=s[o];if(l.id=l.id||`temp.${o}`,!l.action&&l.type=="tour"&&(l.action=d=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=d=>{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 d=l.parameters,p=[];for(let m in d)p.push({name:m,type:"string",description:l.parameters[m]});l.parameters=p}l.content=ce(typeof l.content=="function"?l.content():l.content)}let n=new Be({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});n.addAll(s);let r=n.search(i).map(o=>s.find(l=>l.id==o.id));for(let o of s)o.isContext&&(r.find(l=>l.id===o.id)||r.push(o));return this.lastResults=r,S.debug("Found results:",r),r}getCachedEntry(i){return this.lastResults.find(e=>e.id==i)}registerSourceFromURL(i,e){e||(e=`external.${ve++}`),S.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=async(a,r)=>{S.debug(`Calling remote knowledge base action: ${a.id}`);let o={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:a.id,parameters:r},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let d=await l.json();return n(d.updateItems||[]),d.response},n=a=>{for(let r of a){if(!r.id){S.warn("KB item skipped since it has no ID.",r);continue}let o=t.find(l=>l.id==r.id);if(o){o.name=r.name||o.name||"",o.content=r.content||o.content||"",o.disabled=r.disabled??o.disabled,o.isContext=r.isContext??o.isContext,o.parameters=r.parameters||o.parameters||[],o.tags=r.tags||o.tags,o.type=r.type||o.type;continue}t.push({...r,action:l=>s(r,l)})}};this.registerSource(e,async a=>{let r={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:a},o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`HTTP Error ${o.status} ${o.statusText}`);let l=await o.json();return n(l.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.46",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 Q=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(a=>a.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
|
|
|
@@ -374,4 +374,4 @@ You have access to a database of knowledge base items. These include "info" type
|
|
|
374
374
|
|
|
375
375
|
</div>
|
|
376
376
|
|
|
377
|
-
`;this._isProcessing=!1;this.ai=new Z,w.isSupported&&(this.ai.audio=new w(this.ai))}onCreate(){h().embed&&ae.warn("Only one <web-weaver-embed> element should be on the page."),h().embed=this,this.child("root").addEventListener("click",s=>this.onContainerClick(s)),this.child("web-weaver-logo").addEventListener("click",s=>this.onLogoClick(s)),this.child("interaction-bar").addEventListener("input-message",s=>this.processInput(s.detail)),this.child("interaction-bar").addEventListener("llm-button-click",s=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",s=>this.onLLMModelSelect(s)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.onAIToolStart=this.onAIToolStart.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.focusElement",type:"action",name:"Focus on an element",content:"Focuses and draws the user's attention to an HTML element on the page.",isContext:!0,parameters:[{name:"elementID",type:"string",description:"The HTML ID of the element to focus."}],action:s=>{let n=s.elementID||"";if(n.startsWith("#")&&(n=n.substring(1)),!n)throw new Error("No element ID specified.");let a=document.getElementById(n);if(!a)throw new Error(`Could not find the element with ID "${n}".`);a.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),this.attr.focusID=n,this.ai.submitAnalyticsEvent({type:"focus-element",elementID:n})}}),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:s=>(this.suggestions.push(s.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:s.text}),"Suggestion button added")});let t=this.attr.apiKey||h().apiKey;if(!t)return ae.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.ai.load(t).then(s=>{this.config=s,h().introductionMessage=this.config.introductionMessage,h().analytics=this.config.analytics!==void 0?!!this.config.analytics:h().analytics,this.state.loading=!1,this.resetConversation()})}onUpdate(){this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("root").className=this.attr.open?"open":"",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("root").style.right=this.attr.offsetX?this.attr.offsetX+"px":"20px",this.child("root").style.bottom=this.attr.offsetY?this.attr.offsetY+"px":"20px",this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1;let e=this.child("web-weaver-logo");e.attr.focusID=this.attr.focusID,e.refreshLayout(),this.child("llm-selector-panel").state.items=this.ai.models.sort((t,s)=>(s.priority||0)-(t.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){h().embed==this&&(h().embed=null)}onContainerClick(e){this.attr.open||(e.preventDefault(),this.attr.open=!0)}onLogoClick(e){e.preventDefault(),e.stopPropagation(),this.attr.focusID?this.attr.focusID="":this.attr.open=!this.attr.open}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=h().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let s of h().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=s,n.addEventListener("click",a=>this.onSuggestionClick(a,s)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let t=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let n of Array.from(t.querySelectorAll(".suggestion-button")))n.remove();this.attr.focusID="";let s=document.createElement("div");s.className="input",s.innerText=e,t.appendChild(s),t.scrollBy({top:1e5,behavior:"smooth"}),await this.ai.sendMessage(e);for(let n of this.suggestions){let a=document.createElement("div");a.className="suggestion-button",a.innerText=n,a.addEventListener("click",r=>this.onSuggestionClick(r,n)),t.appendChild(a)}t.scrollBy({top:1e5,behavior:"smooth"})}catch(s){ae.error("Failed to process input:",s);let n=document.createElement("div");n.className="output",n.innerText="Sorry, there was a problem getting a response. "+s.message,t.appendChild(n);let a=document.createElement("div");a.className="suggestion-button",a.innerText="Reset conversation",a.addEventListener("click",r=>this.resetConversation()),t.appendChild(a)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e){let t=await Ue().use(Ye).use(Je).use(Ne,{target:"_blank",rel:["noopener","noreferrer"]}).use(He).use(De).processSync(e),s=this.child("web-weaver-embed-inner"),n=s.lastElementChild;if(n&&n.classList.contains("output"))n.innerHTML=t.toString("utf-8");else{let a=document.createElement("div");a.className="output",a.innerHTML=t.toString("utf-8"),s.appendChild(a)}for(let a of Array.from(s.querySelectorAll(".tool")))a.remove();s.scrollBy({top:1e6,behavior:"smooth"})}onAIToolStart(e,t){let s=`Running: ${e}`;e=="search"&&(s=`Searching: ${t?.query}`),e=="ui.focusElement"&&(s=`Focusing: #${t?.elementID}`),e=="ui.suggestResponse"&&(s=`Suggested response: ${t?.text}`);let n=this.child("web-weaver-embed-inner"),a=document.createElement("div");a.className="tool",a.innerText=s,n.appendChild(a),n.scrollBy({top:1e5,behavior:"smooth"})}onSuggestionClick(e,t){this.processInput(t)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}};M.tagName="intelliweave-embed",M.observedAttributes=["logo"];import We,{createContext as Oe,useContext as _e,useEffect as te,useMemo as je,useState as re}from"react";var Se=new u("React"),ss=c=>typeof window>"u"?null:(M.register(),h().apiKey=c.apiKey??h().apiKey,h().analytics=c.analytics??h().analytics,h().debug=c.debug??h().debug,c.context&&(h().pageSummary=c.context),c.introductionMessage&&(h().introductionMessage=c.introductionMessage),c.introductionSuggestions&&(h().introductionSuggestions=c.introductionSuggestions),c.userID&&(h().userID=c.userID),te(()=>{let i=e=>{for(let t of c.knowledgeBase||[])e.entries.push(t);for(let t of c.sources||[])e.sources.push(t)};return document.addEventListener("webweaver_kb_search",i),()=>document.removeEventListener("webweaver_kb_search",i)},[c.knowledgeBase]),We.createElement("intelliweave-embed",{logo:c.logo,apiKey:c.apiKey,offsetX:c.offsetX||20,offsetY:c.offsetY||20})),Me=Oe(void 0);function ns(c){function i(){Se.debug("Creating new IntelliWeave instance for <IntelliWeaveProvider />");let t=new Z;return w.isSupported&&(t.audio=new w(t)),t.load(c.apiKey),t}h().analytics=c.analytics??h().analytics,h().debug=c.debug??h().debug;let e=je(()=>c.ai||i(),[c.ai,c.apiKey]);return te(()=>{let t=s=>{let n=s;n.detail.isFinal&&e.sendMessage(n.detail.transcript)};return e.audio?.speechRecognition.addEventListener("speech",t),()=>{e.audio?.speechRecognition.removeEventListener("speech",t)}}),We.createElement(Me.Provider,{value:e},c.children)}function os(){let[c,i]=re(0),e=_e(Me)||h().embed?.ai;e||Se.warn("Couldn't find IntelliWeave instance. Make sure you have <IntelliWeaveProvider /> somewhere in your scene graph, or use the <WebWeaverUI /> component.");let[,t]=re(!!e?.loaded),[,s]=re(e?.error);return te(()=>{let n=o=>t(o.detail.ai.loaded),a=o=>s(o.detail.ai.error),r=()=>i(o=>o+1);return e?.addEventListener("load",n),e?.addEventListener("error",a),e?.addEventListener("input",r),e?.addEventListener("output",r),e?.addEventListener("toolstart",r),e?.addEventListener("tool",r),()=>{e?.removeEventListener("load",n),e?.removeEventListener("error",a),e?.removeEventListener("input",r),e?.removeEventListener("output",r),e?.removeEventListener("toolstart",r),e?.removeEventListener("tool",r)}},[e]),e}function as(c,i=[]){te(()=>{let e=t=>t.sources.push({query:c});return document.addEventListener("webweaver_kb_search",e),()=>document.removeEventListener("webweaver_kb_search",e)},i)}export{w as AudioSystem,D as BufferedWebSocket,_ as ChatGPT,fe as FixedBufferStream,Z as IntelliWeave,ns as IntelliWeaveProvider,Ze as IntelliWeaveStream,Y as IntelliWeaveTranscriptionNode,j as KnowledgeBase,u as Logging,y as ONNXModel,H as OpenAITranscriptionNode,B as PCMPlayerNode,z as PCMReceiverNode,ye as Resampler,W as VoiceChunkOutputNode,C as VoiceDetectionNode,M as WebWeaverEmbed,ss as WebWeaverUI,K as audioToWav,Yt as floatTo16BitPCM,Jt as floatTo64BitPCM,he as getDefaultUserID,Ut as int16ToFloat32BitPCM,h as intelliweaveConfig,v as intelliweaveGlobalThis,de as sseEvents,ce as trimWhitespaceInText,os as useIntelliWeave,as as useIntelliWeaveKnowledge};
|
|
377
|
+
`;this._isProcessing=!1;this.ai=new Z,w.isSupported&&(this.ai.audio=new w(this.ai))}onCreate(){h().embed&&ae.warn("Only one <web-weaver-embed> element should be on the page."),h().embed=this,this.child("root").addEventListener("click",s=>this.onContainerClick(s)),this.child("web-weaver-logo").addEventListener("click",s=>this.onLogoClick(s)),this.child("interaction-bar").addEventListener("input-message",s=>this.processInput(s.detail)),this.child("interaction-bar").addEventListener("llm-button-click",s=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",s=>this.onLLMModelSelect(s)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.onAIToolStart=this.onAIToolStart.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.focusElement",type:"action",name:"Focus on an element",content:"Focuses and draws the user's attention to an HTML element on the page.",isContext:!0,parameters:[{name:"elementID",type:"string",description:"The HTML ID of the element to focus."}],action:s=>{let n=s.elementID||"";if(n.startsWith("#")&&(n=n.substring(1)),!n)throw new Error("No element ID specified.");let a=document.getElementById(n);if(!a)throw new Error(`Could not find the element with ID "${n}".`);a.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),this.attr.focusID=n,this.ai.submitAnalyticsEvent({type:"focus-element",elementID:n})}}),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:s=>(this.suggestions.push(s.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:s.text}),"Suggestion button added")});let t=this.attr.apiKey||h().apiKey;if(!t)return ae.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.ai.load(t).then(s=>{this.config=s,h().introductionMessage=this.config.introductionMessage,h().analytics=this.config.analytics!==void 0?!!this.config.analytics:h().analytics,this.state.loading=!1,this.resetConversation()})}onUpdate(){this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("root").className=this.attr.open?"open":"",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("root").style.right=this.attr.offsetX?this.attr.offsetX+"px":"20px",this.child("root").style.bottom=this.attr.offsetY?this.attr.offsetY+"px":"20px",this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1;let e=this.child("web-weaver-logo");e.attr.focusID=this.attr.focusID,e.refreshLayout(),this.child("llm-selector-panel").state.items=this.ai.models.sort((t,s)=>(s.priority||0)-(t.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){h().embed==this&&(h().embed=null)}onContainerClick(e){this.attr.open||(e.preventDefault(),this.attr.open=!0)}onLogoClick(e){e.preventDefault(),e.stopPropagation(),this.attr.focusID?this.attr.focusID="":this.attr.open=!this.attr.open}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=h().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let s of h().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=s,n.addEventListener("click",a=>this.onSuggestionClick(a,s)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let t=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let n of Array.from(t.querySelectorAll(".suggestion-button")))n.remove();this.attr.focusID="";let s=document.createElement("div");s.className="input",s.innerText=e,t.appendChild(s),t.scrollBy({top:1e5,behavior:"smooth"}),await this.ai.sendMessage(e);for(let n of this.suggestions){let a=document.createElement("div");a.className="suggestion-button",a.innerText=n,a.addEventListener("click",r=>this.onSuggestionClick(r,n)),t.appendChild(a)}t.scrollBy({top:1e5,behavior:"smooth"})}catch(s){ae.error("Failed to process input:",s);let n=document.createElement("div");n.className="output",n.innerText="Sorry, there was a problem getting a response. "+s.message,t.appendChild(n);let a=document.createElement("div");a.className="suggestion-button",a.innerText="Reset conversation",a.addEventListener("click",r=>this.resetConversation()),t.appendChild(a)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e){let t=await Ue().use(Ye).use(Je).use(Ne,{target:"_blank",rel:["noopener","noreferrer"]}).use(He).use(De).processSync(e),s=this.child("web-weaver-embed-inner"),n=s.lastElementChild;if(n&&n.classList.contains("output"))n.innerHTML=t.toString("utf-8");else{let a=document.createElement("div");a.className="output",a.innerHTML=t.toString("utf-8"),s.appendChild(a)}for(let a of Array.from(s.querySelectorAll(".tool")))a.remove();s.scrollBy({top:1e6,behavior:"smooth"})}onAIToolStart(e,t){let s=`Running: ${e}`;e=="search"&&(s=`Searching: ${t?.query}`),e=="ui.focusElement"&&(s=`Focusing: #${t?.elementID}`),e=="ui.suggestResponse"&&(s=`Suggested response: ${t?.text}`);let n=this.child("web-weaver-embed-inner"),a=document.createElement("div");a.className="tool",a.innerText=s,n.appendChild(a),n.scrollBy({top:1e5,behavior:"smooth"})}onSuggestionClick(e,t){this.processInput(t)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}};M.tagName="intelliweave-embed",M.observedAttributes=["logo","focusID","open"];import We,{createContext as Oe,useContext as _e,useEffect as te,useMemo as je,useState as re}from"react";var Se=new u("React"),ss=c=>typeof window>"u"?null:(M.register(),h().apiKey=c.apiKey??h().apiKey,h().analytics=c.analytics??h().analytics,h().debug=c.debug??h().debug,c.context&&(h().pageSummary=c.context),c.introductionMessage&&(h().introductionMessage=c.introductionMessage),c.introductionSuggestions&&(h().introductionSuggestions=c.introductionSuggestions),c.userID&&(h().userID=c.userID),te(()=>{let i=e=>{for(let t of c.knowledgeBase||[])e.entries.push(t);for(let t of c.sources||[])e.sources.push(t)};return document.addEventListener("webweaver_kb_search",i),()=>document.removeEventListener("webweaver_kb_search",i)},[c.knowledgeBase]),We.createElement("intelliweave-embed",{logo:c.logo,apiKey:c.apiKey,offsetX:c.offsetX||20,offsetY:c.offsetY||20})),Me=Oe(void 0);function ns(c){function i(){Se.debug("Creating new IntelliWeave instance for <IntelliWeaveProvider />");let t=new Z;return w.isSupported&&(t.audio=new w(t)),t.load(c.apiKey),t}h().analytics=c.analytics??h().analytics,h().debug=c.debug??h().debug;let e=je(()=>c.ai||i(),[c.ai,c.apiKey]);return te(()=>{let t=s=>{let n=s;n.detail.isFinal&&e.sendMessage(n.detail.transcript)};return e.audio?.speechRecognition.addEventListener("speech",t),()=>{e.audio?.speechRecognition.removeEventListener("speech",t)}}),We.createElement(Me.Provider,{value:e},c.children)}function os(){let[c,i]=re(0),e=_e(Me)||h().embed?.ai;e||Se.warn("Couldn't find IntelliWeave instance. Make sure you have <IntelliWeaveProvider /> somewhere in your scene graph, or use the <WebWeaverUI /> component.");let[,t]=re(!!e?.loaded),[,s]=re(e?.error);return te(()=>{let n=o=>t(o.detail.ai.loaded),a=o=>s(o.detail.ai.error),r=()=>i(o=>o+1);return e?.addEventListener("load",n),e?.addEventListener("error",a),e?.addEventListener("input",r),e?.addEventListener("output",r),e?.addEventListener("toolstart",r),e?.addEventListener("tool",r),()=>{e?.removeEventListener("load",n),e?.removeEventListener("error",a),e?.removeEventListener("input",r),e?.removeEventListener("output",r),e?.removeEventListener("toolstart",r),e?.removeEventListener("tool",r)}},[e]),e}function as(c,i=[]){te(()=>{let e=t=>t.sources.push({query:c});return document.addEventListener("webweaver_kb_search",e),()=>document.removeEventListener("webweaver_kb_search",e)},i)}export{w as AudioSystem,D as BufferedWebSocket,_ as ChatGPT,fe as FixedBufferStream,Z as IntelliWeave,ns as IntelliWeaveProvider,Ze as IntelliWeaveStream,Y as IntelliWeaveTranscriptionNode,j as KnowledgeBase,u as Logging,y as ONNXModel,H as OpenAITranscriptionNode,B as PCMPlayerNode,z as PCMReceiverNode,ye as Resampler,W as VoiceChunkOutputNode,C as VoiceDetectionNode,M as WebWeaverEmbed,ss as WebWeaverUI,K as audioToWav,Yt as floatTo16BitPCM,Jt as floatTo64BitPCM,he as getDefaultUserID,Ut as int16ToFloat32BitPCM,h as intelliweaveConfig,v as intelliweaveGlobalThis,de as sseEvents,ce as trimWhitespaceInText,os as useIntelliWeave,as as useIntelliWeaveKnowledge};
|