@intelliweave/embedded 1.8.63 → 1.8.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import{v4 as ge}from"uuid";function ce(l){let i=(l||"").split(`
|
|
2
2
|
`);for(;i.length>0&&i[0].trim()=="";)i.shift();for(;i.length>0&&i[i.length-1].trim()=="";)i.pop();let e=1/0;for(let t of i){let s=t.match(/^\s*/)?.[0].length||0;e=Math.min(e,s)}return e>0&&e<1/0&&(i=i.map(t=>t.substring(e))),i.join(`
|
|
3
|
-
`)}var
|
|
3
|
+
`)}var ke={};function G(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:ke}function p(){return G().intelliweave=G().intelliweave||G().webWeaver||{},G().intelliweave}async function*fe(l){let i="",e=function*(){for(;;){let n=i.indexOf(`
|
|
4
4
|
|
|
5
5
|
`);if(n==-1)break;let o=i.slice(0,n);i=i.slice(n+2);let r={},d=o.split(`
|
|
6
6
|
`);for(let c of d){n=c.indexOf(": ");let a=c.slice(0,n),h=c.slice(n+2);n==-1&&(a=c,h=""),a&&(r[a]!==void 0?r[a]+=`
|
|
7
7
|
`+h:r[a]=h)}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 ye(){if(p().userID)return p().userID||"";if(typeof localStorage<"u"){let l=localStorage.getItem("intelliweave.uid")||"";return l||(l=ge(),localStorage.setItem("intelliweave.uid",l),l)}else return ge()}function ve(l){let i=l;if(i?.type=="object"&&i.properties)return l;let e={type:"object",properties:{},required:[]};if(l&&Array.isArray(l)){let t=l;for(let s of t)e.properties[s.name]={type:s.type||"string",description:s.description||""}}return e}var _=class _{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return _.debug?!0:typeof window<"u"&&p().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)}};_.debug=!1;var u=_;import{countTokens as
|
|
10
|
-
`;this.itemPadding=0;this.sortFunction=(i,e)=>i.sortOrder!==e.sortOrder?i.sortOrder-e.sortOrder:i.dateAdded!==e.dateAdded?i.dateAdded-e.dateAdded:i.content.localeCompare(e.content)}setItemPadding(i){return this.itemPadding=i,this.recalculateTokens(),this}sortBy(i){return this.sortFunction=i,this.items.sort(this.sortFunction),this}setSeparator(i){return this.separator==i?this:(this.separator=i,this.recalculateTokens(),this)}setWeight(i){return this.weight=i,this}recalculateTokens(){this.tokenCount=this.items.reduce((i,e)=>(e.tokenCount=
|
|
9
|
+
`,yield*e()}function ye(){if(p().userID)return p().userID||"";if(typeof localStorage<"u"){let l=localStorage.getItem("intelliweave.uid")||"";return l||(l=ge(),localStorage.setItem("intelliweave.uid",l),l)}else return ge()}function ve(l){let i=l;if(i?.type=="object"&&i.properties)return l;let e={type:"object",properties:{},required:[]};if(l&&Array.isArray(l)){let t=l;for(let s of t)e.properties[s.name]={type:s.type||"string",description:s.description||""}}return e}var _=class _{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return _.debug?!0:typeof window<"u"&&p().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)}};_.debug=!1;var u=_;import{countTokens as D}from"gpt-tokenizer";import{v4 as Xe}from"uuid";var K=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new de;return e.id=i,this.groups.push(e),e}group(i){return this.groups.find(e=>e.id===i)}countTokens(){return this.groups.reduce((i,e)=>i+e.tokenCount,0)}removeOverflow(){let i=this.countTokens(),e=this.groups.reduce((t,s)=>t+s.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((n,o)=>{let r=Math.floor(n.weight/e*this.size),d=Math.floor(o.weight/e*this.size),c=n.tokenCount-r;return o.tokenCount-d-c}),s=this.removeOneItem(t);if(!s)throw new Error("Too many items in the token window that cannot be removed.");i-=s.tokenCount}}removeOneItem(i){for(let e of i){let t=e.items.findIndex(n=>!n.cannotRemove);if(t===-1)continue;let s=e.items[t];return e.items.splice(t,1),e.tokenCount-=s.tokenCount,s}return null}},de=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
10
|
+
`;this.itemPadding=0;this.sortFunction=(i,e)=>i.sortOrder!==e.sortOrder?i.sortOrder-e.sortOrder:i.dateAdded!==e.dateAdded?i.dateAdded-e.dateAdded:i.content.localeCompare(e.content)}setItemPadding(i){return this.itemPadding=i,this.recalculateTokens(),this}sortBy(i){return this.sortFunction=i,this.items.sort(this.sortFunction),this}setSeparator(i){return this.separator==i?this:(this.separator=i,this.recalculateTokens(),this)}setWeight(i){return this.weight=i,this}recalculateTokens(){this.tokenCount=this.items.reduce((i,e)=>(e.tokenCount=D(e.content)+D(this.separator)+this.itemPadding,i+e.tokenCount),0)}add(i){typeof i=="string"&&(i={content:i});let e=i;e.id===void 0&&(e.id=Xe());let t=this.items.find(s=>s.id===e.id);return t?(this.tokenCount-=t.tokenCount,Object.assign(t,e),e=t):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.tokenCount=e.disabled?0:D(i.content)+D(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}getAllAsString(){return this.getAll().map(i=>i.content).join(this.separator)}getAll(){return this.items.filter(i=>!i.disabled)}empty(){this.items=[],this.tokenCount=0}};import{countTokens as Ee}from"gpt-tokenizer";var T=1,x=new u("ChatGPT"),F=class{constructor(i){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let i=new K;return i.createGroup("context").setSeparator(`
|
|
11
11
|
|
|
12
|
-
`),i.createGroup("actions").setItemPadding(25),i.createGroup("messages").setItemPadding(10),i})();this.config={...this.config,...i},this.tokenWindow.size=this.config.maxTokens||4096}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(e),customData:e}),await this.processMessages();let s=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return s?.role=="assistant"&&s.content||""}addAssistantMessage(i){let e={role:"assistant",content:i};this.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(e),customData:e})}addUserMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(i=>i.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),x.debugEnabled&&x.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(t=>t.customData),messages:this.messageGroup.items.map(t=>t.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let t of e.tool_calls)await this.processToolCall(t);await this.processMessages()}}async trimMessages(){for(this.tokenWindow.removeOverflow();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendToAPI(i){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let d=this.messageGroup.items.length-1;d>=0;d--){let c=this.messageGroup.items[d].customData;if(c.role=="assistant"&&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(c.role=="user")break}x.debugEnabled&&x.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(d=>d.customData),messages:this.messageGroup.items.map(d=>d.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(d=>d.customData)]};for(let d of this.toolGroup.getAll()){let c=d.customData;c.description&&c.description.length>1024&&x.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:c.params}};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 d=`${n.status} ${n.statusText}`;try{let a=await n.json();d=a.errorText||a.error?.message||a.error||d}catch{}let c=new Error(d);throw c.code=n.status,c}let o=null,r=null;if(this.config.stream){for await(let c of fe(n.body)){if(c.data=="[DONE]")break;if(!c.data)continue;let a=JSON.parse(c.data);if(r){for(let h in a.choices[0].delta)if(typeof a.choices[0].delta[h]=="string"){if(h=="role"&&r[h]==a.choices[0].delta[h])continue;r[h]=(r[h]||"")+a.choices[0].delta[h]}for(let h of a.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[h.index]){r.tool_calls[h.index]=h;continue}let y=r.tool_calls[h.index];y.function=y.function||{},y.function.name=(y.function.name||"")+(h.function?.name||""),y.function.arguments=(y.function.arguments||"")+(h.function?.arguments||"")}}else r={chunkID:a.id,...a.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}let d=Ee(JSON.stringify(t)+JSON.stringify(r)||"");this.stats.tokensUsed+=d,x.debug(`Estimated ${d} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else o=await n.json(),this.stats.tokensUsed+=o.usage?.total_tokens||0,x.debug(`Used ${o.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),r=o.choices?.[0]?.message;if(r||(x.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.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(r),customData:r}),r.content&&this.config.onAIMessage?.(r.content,!1)}processIncomingMessage(i){}registerTool(i){this.toolGroup.add({id:i.name,cannotRemove:!i.canRemove,content:JSON.stringify(i),customData:i})}async processToolCall(i){try{let t=this.toolGroup.items.find(r=>r.id==i.function.name)?.customData;if(!t)throw new Error(`Tool "${i.function.name}" not found.`);let s=JSON.parse(i.function.arguments);this.config.onAIToolStart?.(i.function.name,s);let n=await t.callback(s);typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success");let o={role:"tool",content:n,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(o),customData:o})}catch(e){x.warn(`Unable to process tool call for "${i?.function?.name}"`,e);let t={role:"tool",content:`Error: ${e.message}`,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(t),customData:t})}}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}};import{v4 as H}from"uuid";import Ae 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(l,i)=>{let e=await i.knowledgeBase.search(l.query),t=i;t._lastKBsearch=l.query,t._nextRequestUseKBitems=e,i.submitAnalyticsEvent({type:"kb-search",query:l.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${n}.`}}];import{Client as we}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Re}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Ve}from"@modelcontextprotocol/sdk/client/sse.js";var S={name:"@intelliweave/embedded",version:"1.8.63",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 && IW_TESTER_API_KEY=97150cfc-5b97-413e-8da3-e86d01f70057 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:{"@modelcontextprotocol/sdk":"^1.12.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",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","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as Le,ToolListChangedNotificationSchema as Pe}from"@modelcontextprotocol/sdk/types.js";var m=new u("MCPKnowledgeClient"),z=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){m.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new we({name:S.name,version:S.version}),t=new Re(new URL(this.config.baseURL));return await e.connect(t),m.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new we({name:S.name,version:S.version}),s=new Ve(new URL(this.config.baseURL));return await t.connect(s),m.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{m.error(`MCP client error: ${e.message}`)},i.onclose=()=>{m.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(Le,e=>{e.params.level=="critical"?m.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?m.error(`[Server] ${e.params.data}`):e.params.level=="error"?m.error(`[Server] ${e.params.data}`):e.params.level=="warning"?m.warn(`[Server] ${e.params.data}`):e.params.level=="info"?m.info(`[Server] ${e.params.data}`):e.params.level=="debug"?m.debug(`[Server] ${e.params.data}`):m.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(Pe,e=>{m.debug("Tool list changed",e),this.fetchTools()}),m.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let s=await this.client.listTools({cursor:e});e=s.nextCursor;for(let n of s.tools||[])i.push(n);if(!s?.tools?.length||!e)break}let t=[];for(let s of i){let n=!!(this.config.searchToolName&&s.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:s.name,name:s.name,content:s.description||"",type:"action",isContext:!0,parameters:s.inputSchema,action:o=>this.performToolCall(s.name,o),disabled:n})}m.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,m.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return m.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let s;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let n=0;n<s.length;n++){let o=s[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return e}async performToolCall(i,e){await this.connect(),m.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let s=t.content?.[0]?.text||"Unknown error";throw m.error(`Error calling tool ${i}: ${s}`),new Error(`Error calling tool ${i}: ${s}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};import{v4 as Be}from"uuid";var Ne=new u("Statistics"),R=[];async function g(l,i){let e={...i,event_id:Be(),event_date:new Date().toISOString(),sdk_version:S.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(R.push(e),!l||(await new Promise(s=>setTimeout(s,5e3)),R.length===0))return;let t=R.slice();R.length=0;try{let s=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){Ne.warn("Failed to submit analytics event:",s),R.push(...t);return}}var C=new u("KnowledgeBase"),he=1,Y=class l{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.${he++}`),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 p().knowledgeBaseSources&&(i=i.concat(p().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();C.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async c=>{try{let a=Date.now(),h=await c.query(i);return C.debug(`Source '${c.id}' took ${Date.now()-a}ms`),h||[]}catch(a){return C.warn(`Knowledge source '${c.id}' failed:`,a),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),p().knowledgeBase&&(n=n.concat(p().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let a=n[c];a.id=a.id||`temp.${c}`,a._functionID=a.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!a.action&&a.type=="tour"&&(a.action=h=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!a.action&&a.type=="info"&&(a.action=h=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new Ae({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(n);let d=o.search(i).map(c=>n.find(a=>a.id==c.id));for(let c of n)c.isContext&&(d.find(a=>a.id===c.id)||d.push(c));return this.lastResults=d,g(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),C.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${he++}`),C.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{C.debug(`Calling remote knowledge base action: ${d.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:d.id,parameters:c},h=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!h.ok)throw new Error(`HTTP Error ${h.status} ${h.statusText}`);let y=await h.json();return r(y.updateItems||[]),y.response},r=d=>{for(let c of d){if(!c.id){C.warn("KB item skipped since it has no ID.",c);continue}let a=t.find(h=>h.id==c.id);if(a){a.name=c.name||a.name||"",a.content=c.content||a.content||"",a.disabled=c.disabled??a.disabled,a.isContext=c.isContext??a.isContext,a.parameters=c.parameters||a.parameters||[],a.tags=c.tags||a.tags,a.type=c.type||a.type;continue}t.push({...c,action:h=>o(c,h)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:d},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 h=await a.json();return n=!h.noCache,s.includes(d)||s.push(d),r(h.items),t})}clone(){let i=new l(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${he++}`);let e=new z(i);return this.registerSource(i.id,t=>e.search(t)),e}};var J=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
12
|
+
`),i.createGroup("actions").setItemPadding(25),i.createGroup("messages").setItemPadding(10),i})();this.config={...this.config,...i},this.tokenWindow.size=this.config.maxTokens||4096}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(e),customData:e}),await this.processMessages();let s=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return s?.role=="assistant"&&s.content||""}addAssistantMessage(i){let e={role:"assistant",content:i};this.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(e),customData:e})}addUserMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(i=>i.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),x.debugEnabled&&x.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(t=>t.customData),messages:this.messageGroup.items.map(t=>t.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let t of e.tool_calls)await this.processToolCall(t);await this.processMessages()}}async trimMessages(){for(this.tokenWindow.removeOverflow();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendToAPI(i){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let d=this.messageGroup.items.length-1;d>=0;d--){let c=this.messageGroup.items[d].customData;if(c.role=="assistant"&&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(c.role=="user")break}x.debugEnabled&&x.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(d=>d.customData),messages:this.messageGroup.items.map(d=>d.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(d=>d.customData)]};for(let d of this.toolGroup.getAll()){let c=d.customData;c.description&&c.description.length>1024&&x.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:c.params}};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 d=`${n.status} ${n.statusText}`;try{let a=await n.json();d=a.errorText||a.error?.message||a.error||d}catch{}let c=new Error(d);throw c.code=n.status,c}let o=null,r=null;if(this.config.stream){for await(let c of fe(n.body)){if(c.data=="[DONE]")break;if(!c.data)continue;let a=JSON.parse(c.data);if(r){for(let h in a.choices[0].delta)if(typeof a.choices[0].delta[h]=="string"){if(h=="role"&&r[h]==a.choices[0].delta[h])continue;r[h]=(r[h]||"")+a.choices[0].delta[h]}for(let h of a.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[h.index]){r.tool_calls[h.index]=h;continue}let y=r.tool_calls[h.index];y.function=y.function||{},y.function.name=(y.function.name||"")+(h.function?.name||""),y.function.arguments=(y.function.arguments||"")+(h.function?.arguments||"")}}else r={chunkID:a.id,...a.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}let d=Ee(JSON.stringify(t)+JSON.stringify(r)||"");this.stats.tokensUsed+=d,x.debug(`Estimated ${d} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else o=await n.json(),this.stats.tokensUsed+=o.usage?.total_tokens||0,x.debug(`Used ${o.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),r=o.choices?.[0]?.message;if(r||(x.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.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(r),customData:r}),r.content&&this.config.onAIMessage?.(r.content,!1)}processIncomingMessage(i){}registerTool(i){this.toolGroup.add({id:i.name,cannotRemove:!i.canRemove,content:JSON.stringify(i),customData:i})}async processToolCall(i){try{let t=this.toolGroup.items.find(r=>r.id==i.function.name)?.customData;if(!t)throw new Error(`Tool "${i.function.name}" not found.`);let s=JSON.parse(i.function.arguments);this.config.onAIToolStart?.(i.function.name,s);let n=await t.callback(s);typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success");let o={role:"tool",content:n,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(o),customData:o})}catch(e){x.warn(`Unable to process tool call for "${i?.function?.name}"`,e);let t={role:"tool",content:`Error: ${e.message}`,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+T++,content:JSON.stringify(t),customData:t})}}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}};import{v4 as H}from"uuid";import Ae 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(l,i)=>{let e=await i.knowledgeBase.search(l.query),t=i;t._lastKBsearch=l.query,t._nextRequestUseKBitems=e,i.submitAnalyticsEvent({type:"kb-search",query:l.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${n}.`}}];import{Client as we}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Re}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Ve}from"@modelcontextprotocol/sdk/client/sse.js";var S={name:"@intelliweave/embedded",version:"1.8.64",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 && IW_TESTER_API_KEY=97150cfc-5b97-413e-8da3-e86d01f70057 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:{"@modelcontextprotocol/sdk":"^1.12.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",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","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as Le,ToolListChangedNotificationSchema as Pe}from"@modelcontextprotocol/sdk/types.js";var m=new u("MCPKnowledgeClient"),z=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){m.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new we({name:S.name,version:S.version}),t=new Re(new URL(this.config.baseURL));return await e.connect(t),m.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new we({name:S.name,version:S.version}),s=new Ve(new URL(this.config.baseURL));return await t.connect(s),m.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{m.error(`MCP client error: ${e.message}`)},i.onclose=()=>{m.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(Le,e=>{e.params.level=="critical"?m.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?m.error(`[Server] ${e.params.data}`):e.params.level=="error"?m.error(`[Server] ${e.params.data}`):e.params.level=="warning"?m.warn(`[Server] ${e.params.data}`):e.params.level=="info"?m.info(`[Server] ${e.params.data}`):e.params.level=="debug"?m.debug(`[Server] ${e.params.data}`):m.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(Pe,e=>{m.debug("Tool list changed",e),this.fetchTools()}),m.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let s=await this.client.listTools({cursor:e});e=s.nextCursor;for(let n of s.tools||[])i.push(n);if(!s?.tools?.length||!e)break}let t=[];for(let s of i){let n=!!(this.config.searchToolName&&s.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:s.name,name:s.name,content:s.description||"",type:"action",isContext:!0,parameters:s.inputSchema,action:o=>this.performToolCall(s.name,o),disabled:n})}m.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,m.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return m.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let s;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let n=0;n<s.length;n++){let o=s[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return e}async performToolCall(i,e){await this.connect(),m.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let s=t.content?.[0]?.text||"Unknown error";throw m.error(`Error calling tool ${i}: ${s}`),new Error(`Error calling tool ${i}: ${s}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};import{v4 as Be}from"uuid";var Ne=new u("Statistics"),R=[];async function g(l,i){let e={...i,event_id:Be(),event_date:new Date().toISOString(),sdk_version:S.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(R.push(e),!l||(await new Promise(s=>setTimeout(s,5e3)),R.length===0))return;let t=R.slice();R.length=0;try{let s=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){Ne.warn("Failed to submit analytics event:",s),R.push(...t);return}}var C=new u("KnowledgeBase"),he=1,Y=class l{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.${he++}`),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 p().knowledgeBaseSources&&(i=i.concat(p().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();C.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async c=>{try{let a=Date.now(),h=await c.query(i);return C.debug(`Source '${c.id}' took ${Date.now()-a}ms`),h||[]}catch(a){return C.warn(`Knowledge source '${c.id}' failed:`,a),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),p().knowledgeBase&&(n=n.concat(p().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let a=n[c];a.id=a.id||`temp.${c}`,a._functionID=a.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!a.action&&a.type=="tour"&&(a.action=h=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!a.action&&a.type=="info"&&(a.action=h=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new Ae({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(n);let d=o.search(i).map(c=>n.find(a=>a.id==c.id));for(let c of n)c.isContext&&(d.find(a=>a.id===c.id)||d.push(c));return this.lastResults=d,g(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),C.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${he++}`),C.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{C.debug(`Calling remote knowledge base action: ${d.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:d.id,parameters:c},h=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!h.ok)throw new Error(`HTTP Error ${h.status} ${h.statusText}`);let y=await h.json();return r(y.updateItems||[]),y.response},r=d=>{for(let c of d){if(!c.id){C.warn("KB item skipped since it has no ID.",c);continue}let a=t.find(h=>h.id==c.id);if(a){a.name=c.name||a.name||"",a.content=c.content||a.content||"",a.disabled=c.disabled??a.disabled,a.isContext=c.isContext??a.isContext,a.parameters=c.parameters||a.parameters||[],a.tags=c.tags||a.tags,a.type=c.type||a.type;continue}t.push({...c,action:h=>o(c,h)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:d},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 h=await a.json();return n=!h.noCache,s.includes(d)||s.push(d),r(h.items),t})}clone(){let i=new l(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${he++}`);let e=new z(i);return this.registerSource(i.id,t=>e.search(t)),e}};var J=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
13
13
|
|
|
14
14
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(e.toLowerCase().includes("true"))return!0;if(e.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+e)}async choose(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
15
15
|
|
|
@@ -27,7 +27,7 @@ ${i.extractions.map(s=>`- ${s.name} (${s.type}): ${s.description||"No descriptio
|
|
|
27
27
|
`)}
|
|
28
28
|
`,t=await this.instruct({...i,instruction:e});if(t=t.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),i.allowMultiple){let s=t.split(`
|
|
29
29
|
`).map(o=>o.trim()).filter(o=>!!o.trim()),n=[];for(let o of s)try{n.push(JSON.parse(o))}catch(r){console.error("Failed to parse line as JSON:",o,r.message)}return n}else return[JSON.parse(t.trim())]}async generateMarkdown(i){return this.instruct({...i,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(i){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>i.instruction,i.callback&&e.addEventListener("output",t=>{i.callback(t.detail.message)}),i.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof i.data=="string"?i.data:JSON.stringify(i.data))||""}};var v=new u("Main"),xe=new Set,O=class O extends EventTarget{constructor(){super(...arguments);this.conversationID=H();this.knowledgeBase=new Y(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new J(this);this.userID=ye();this.extra=p().extra||{};this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this._lastTrackedTokens=0}get loaded(){return!!(this.config&&this.currentModel)}async load(e){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{v.debug("Loading configuration...");let t=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!t.ok)throw new Error(`Failed to load configuration: ${t.status} ${t.statusText}`);try{this.config=await t.json(),v.debug("Config loaded successfully:",this.config),this.config&&v.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(s){v.error("Failed to parse JSON response:",s);try{let n=await t.clone().text();v.error("Raw response that failed parsing:",n)}catch{v.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${s}`)}})(),(async()=>{try{let t=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!t.ok)throw new Error(`Failed to load VAD model: ${t.status} ${t.statusText}`);this.vadModel=await t.blob()}catch(t){v.warn(`Failed to load VAD model, some features will be unavailable. ${t.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let t of this.config.knowledge||[])t.url&&t.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:t.id,searchToolName:t.mcpSearchToolName,baseURL:t.url}):t.url&&this.knowledgeBase.registerSourceFromURL(t.url);for(let t of this.config.knowledge||[])t.entries?.length&&this.knowledgeBase.registerSource(t.id,()=>t.entries||[]);if(this.config.mcpServers)for(let t of this.config.mcpServers)this.knowledgeBase.registerMCPSource(t);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this.config}catch(t){throw v.warn("Failed to load:",t),this.error=t,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:t}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:t}})),t}}setModel(e){let t=this.models.find(s=>s.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);this.currentModel=new F({...t.config,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(s,n)=>{let o=this.knowledgeBase.getCachedEntry(s);this.onAIToolStart?.(o?.id||s,n)}}),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=p().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,content:e}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,content:'You have access to a database of knowledge base items. These include "info" type items which provide information and "tour" type items which contain instructions you should follow (only do one item at a time). Current info and tour items:'});let t=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;for(let n of t)if(n.type=="info"||n.type=="tour"||n.type=="input-event")this.currentModel.contextGroup.add({id:n.id,customData:n,cannotRemove:n.isContext,sortOrder:101,disabled:n.disabled,content:JSON.stringify({id:n.id,type:n.type,name:n.name,content:ce(typeof n.content=="function"?n.content():n.content)})+`
|
|
30
|
-
`});else if(n.type=="action"){let o={name:n._functionID,description:ce(typeof n.content=="function"?n.content():n.content),params:ve(n.parameters||[{name:"value",type:"string",description:"Input"}]),removeFromMessageHistory:!!n.removeFromMessageHistory,callback:r=>this.toolRunKBAction(n,r),kb:n};this.currentModel.toolGroup.add({id:n._functionID,customData:o,cannotRemove:n.isContext,sortOrder:101,disabled:n.disabled,content:JSON.stringify(o)})}else continue;let s=this.currentModel.contextGroup.getAllAsString();this._lastSystemMsg!=s&&(this._lastSystemMsg=s,this.submitAnalyticsEvent({type:"system-msg",txt:s}))}processIncomingMessage(e,t){if(!t){let n=this.currentModel?.stats?.tokensUsed||0,o=n-(this._lastTrackedTokens||0);this._lastTrackedTokens=n,g(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:n}})}let s="";this._lastOutput===void 0?(s=e,this._lastOutput=e):e.startsWith(this._lastOutput)?(s=e.substring(this._lastOutput.length),this._lastOutput=e):(v.warn("Message was changed during chunking. This should not happen.",e,this._lastOutput),s=e,this._lastOutput=e),t||(this._lastOutput=void 0),this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:t,message:e,messageChunk:s}})),this.onAIMessage?.(e,!!t)}async sendMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)return v.warn("Cannot send message while another message is being processed."),null;this.isProcessing=!0;try{return this._messageStartTime=Date.now(),xe.has(this.conversationID)||(xe.add(this.conversationID),g(this,{event_type:"session_start"})),this._lastTrackedTokens=this.currentModel?.stats?.tokensUsed||0,g(this,{event_type:"message_send",value_str:"",event_properties:{message_length:e.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),await this.currentModel.sendMessage(e)}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let s=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:t,ai:this}}));let n=await e.action(t,this),o=Date.now()-s;return g(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:o,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,result:n}})),n}catch(n){let o=Date.now()-s;throw g(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:o,success:!1,error_message:n.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,error:n}})),n}}submitAnalyticsEvent(e){p().analytics===!1||this.config?.analytics===!1||fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(t=>{v.debug("Failed to submit analytics event:",t)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=H(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");let t={role:"assistant",content:e};this.currentModel.messageGroup.add({id:H(),content:JSON.stringify(t),customData:t})}exportState(){return{type:"intelliweave/state/v1",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll().map(e=>e.customData)}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v1")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let t of e.messages)this.currentModel.messageGroup.add({id:H(),content:JSON.stringify(t),customData:t})}clone(){let e=new O;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.extra=this.extra,e.knowledgeBase=this.knowledgeBase.clone(),e}};O.version=S.version;var W=O;var f=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(e={},t=""){this.register();let s=document.createElement(this.tagName);for(let n in e)s.setAttribute(n,e[n]);return s.onBeforeCreate(),s.innerHTML=t,s}static add(e={},t=""){return this.register(),`<${this.tagName} ${Object.keys(e).map(s=>`${s}="${(e[s]+"").replaceAll('"',""")}"`).join(" ")}>${t}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(e,t,s){this._shadow&&this.onUpdate()}get attr(){if(this._attrProxy)return this._attrProxy;let e=t=>(U=U||document.createElement("div"),U.innerText=t||"",U.innerHTML);return this._attrProxy=new Proxy({},{get:(t,s)=>e(this.getAttribute(s.toString())||""),set:(t,s,n)=>(this.getAttribute(s.toString())===n||(n?this.setAttribute(s.toString(),n):this.removeAttribute(s.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(e,t)=>this._state[t],set:(e,t,s)=>(this._state[t]=s,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(e){return!!this.root?.getElementById(e)}child(e){let t=this.root?.getElementById(e);if(!t)throw new Error(`Child with ID ${e} not found`);return t}};f.observedAttributes=[],f.tagName="",f._isRegistered=!1;var U;var Se='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var Ge='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Ze='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var V=class extends f{constructor(){super(...arguments);this.html=()=>`
|
|
30
|
+
`});else if(n.type=="action"){let o={name:n._functionID,description:ce(typeof n.content=="function"?n.content():n.content),params:ve(n.parameters||[{name:"value",type:"string",description:"Input"}]),removeFromMessageHistory:!!n.removeFromMessageHistory,callback:r=>this.toolRunKBAction(n,r),kb:n};this.currentModel.toolGroup.add({id:n._functionID,customData:o,cannotRemove:n.isContext,sortOrder:101,disabled:n.disabled,content:JSON.stringify(o)})}else continue;let s=this.currentModel.contextGroup.getAllAsString();this._lastSystemMsg!=s&&(this._lastSystemMsg=s,this.submitAnalyticsEvent({type:"system-msg",txt:s}))}processIncomingMessage(e,t){if(!t){let n=this.currentModel?.stats?.tokensUsed||0,o=n-(this._lastTrackedTokens||0);this._lastTrackedTokens=n,g(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:n}})}let s="";this._lastOutput===void 0?(s=e,this._lastOutput=e):e.startsWith(this._lastOutput)?(s=e.substring(this._lastOutput.length),this._lastOutput=e):(v.warn("Message was changed during chunking. This should not happen.",e,this._lastOutput),s=e,this._lastOutput=e),t||(this._lastOutput=void 0),this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:t,message:e,messageChunk:s}})),this.onAIMessage?.(e,!!t)}async sendMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)return v.warn("Cannot send message while another message is being processed."),null;this.isProcessing=!0;try{this._messageStartTime=Date.now(),xe.has(this.conversationID)||(xe.add(this.conversationID),g(this,{event_type:"session_start"})),this._lastTrackedTokens=this.currentModel?.stats?.tokensUsed||0,g(this,{event_type:"message_send",value_str:"",event_properties:{message_length:e.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),this.submitAnalyticsEvent({type:"message",role:"user",message:e,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()});let t=await this.currentModel.sendMessage(e);return t&&typeof t=="string"&&t.trim().length>0&&this.submitAnalyticsEvent({type:"message",role:"assistant",message:t,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()}),t}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let s=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:t,ai:this}}));let n=await e.action(t,this),o=Date.now()-s;return g(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:o,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,result:n}})),n}catch(n){let o=Date.now()-s;throw g(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:o,success:!1,error_message:n.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,error:n}})),n}}submitAnalyticsEvent(e){p().analytics===!1||this.config?.analytics===!1||fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(t=>{v.debug("Failed to submit analytics event:",t)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=H(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");let t={role:"assistant",content:e};this.currentModel.messageGroup.add({id:H(),content:JSON.stringify(t),customData:t})}exportState(){return{type:"intelliweave/state/v1",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll().map(e=>e.customData)}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v1")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let t of e.messages)this.currentModel.messageGroup.add({id:H(),content:JSON.stringify(t),customData:t})}clone(){let e=new O;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.extra=this.extra,e.knowledgeBase=this.knowledgeBase.clone(),e}};O.version=S.version;var I=O;var f=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(e={},t=""){this.register();let s=document.createElement(this.tagName);for(let n in e)s.setAttribute(n,e[n]);return s.onBeforeCreate(),s.innerHTML=t,s}static add(e={},t=""){return this.register(),`<${this.tagName} ${Object.keys(e).map(s=>`${s}="${(e[s]+"").replaceAll('"',""")}"`).join(" ")}>${t}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(e,t,s){this._shadow&&this.onUpdate()}get attr(){if(this._attrProxy)return this._attrProxy;let e=t=>(U=U||document.createElement("div"),U.innerText=t||"",U.innerHTML);return this._attrProxy=new Proxy({},{get:(t,s)=>e(this.getAttribute(s.toString())||""),set:(t,s,n)=>(this.getAttribute(s.toString())===n||(n?this.setAttribute(s.toString(),n):this.removeAttribute(s.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(e,t)=>this._state[t],set:(e,t,s)=>(this._state[t]=s,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(e){return!!this.root?.getElementById(e)}child(e){let t=this.root?.getElementById(e);if(!t)throw new Error(`Child with ID ${e} not found`);return t}};f.observedAttributes=[],f.tagName="",f._isRegistered=!1;var U;var Se='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var Ge='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Ze='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var V=class extends f{constructor(){super(...arguments);this.html=()=>`
|
|
31
31
|
|
|
32
32
|
<!-- Styling -->
|
|
33
33
|
<style>
|
|
@@ -270,7 +270,7 @@ ${i.extractions.map(s=>`- ${s.name} (${s.type}): ${s.description||"No descriptio
|
|
|
270
270
|
<div class='llm-selector-item-icon' style="background-image: url('${t.icon}'); "></div>
|
|
271
271
|
<div class='llm-selector-item-name'>${t.name}</div>
|
|
272
272
|
<div class='llm-selector-item-provider'>${t.provider}</div>
|
|
273
|
-
`,s.addEventListener("click",n=>{this.dispatchEvent(new CustomEvent("select",{detail:t.id}))}),e.appendChild(s)}}};P.observedAttributes=["open"];var k=new u("ONNXModel"),b=class l{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,k.debug(`Model input parameters: ${i.inputNames.join(", ")}`),k.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!l.lib}static async load(i){if(!l.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(k.debug("Loading ONNX runtime"),this.onnx=await l.lib()),k.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new l(e)}makeTensor(i,e,t=0){let s=1;for(let o of e)s*=o;let n;if(i=="float32")n=new l.onnx.Tensor(new Float32Array(s),e);else if(i=="int8")n=new l.onnx.Tensor(new Int8Array(s),e);else if(i=="int16")n=new l.onnx.Tensor(new Int16Array(s),e);else if(i=="int32")n=new l.onnx.Tensor(new Int32Array(s),e);else if(i=="int64")n=new l.onnx.Tensor(new BigInt64Array(s),e);else if(i=="uint8")n=new l.onnx.Tensor(new Uint8Array(s),e);else if(i=="uint16")n=new l.onnx.Tensor(new Uint16Array(s),e);else if(i=="uint32")n=new l.onnx.Tensor(new Uint32Array(s),e);else if(i=="uint64")n=new l.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 k.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(){k.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var Ce="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmK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cztyKyspaVthXVtyXS5zZXQodFswXVtyXSl9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Je=new u("PCMPlayerNode"),j=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){Je.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 Q=new u("SpeechOutput"),We=.5,He=.8,$=class extends EventTarget{constructor(e){super();this.maxVolumeHeard=0;this.ai=e,this.ai.addEventListener("output",t=>this.onTextOutputFromAI(t)),this.ai.audio?.speechRecognition.addEventListener("speechstart",t=>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(e){e.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(e.detail.message)}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))}async speak(e){if(!this.ai?.config?.voice?.providerID)return Q.warn("No voice provider configured");let t=`speech-${Oe++}`;await this.ai.audio.beginAccess(t);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(t)}}async _speakWithLock(e){this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=He);let t=this.ai?._voiceTracker||Q.timer(`${this.ai.config.voice.providerID} voice`);t(`Speak: ${e}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let s=new j(this.ai.audio.context,24e3,"int16");this.currentPlayer=s,s.connect(this.analyserNode),s.addEventListener("end",o=>{let r=o;t(`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:e,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:e})});else{Q.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(t(`Received response ${n.status} ${n.statusText}`),!n.ok){Q.warn(`Failed to generate voice sample: ${n.status} ${n.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),t("Playing PCM stream"),await s.play(n.body),t("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let e=this.currentPlayerVolume,t=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=We);let s=400;e.gain.linearRampToValueAtTime(0,s/1e3),await new Promise(n=>setTimeout(n,s+250)),e.disconnect(),t?.stop(),t?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=We)}},Oe=1;function q(l,i){let e=i.reduce((d,c)=>d+c.byteLength,0),t=new DataView(new ArrayBuffer(44));t.setUint8(0,82),t.setUint8(1,73),t.setUint8(2,70),t.setUint8(3,70),t.setUint32(4,44+e,!0),t.setUint8(8,87),t.setUint8(9,65),t.setUint8(10,86),t.setUint8(11,69);let s=1,n=32,o=s*n/8,r=l*o;return t.setUint8(12,102),t.setUint8(13,109),t.setUint8(14,116),t.setUint8(15,32),t.setUint32(16,16,!0),t.setUint16(20,3,!0),t.setUint16(22,s,!0),t.setUint32(24,l,!0),t.setUint32(28,r,!0),t.setUint16(32,o,!0),t.setUint16(34,n,!0),t.setUint8(36,100),t.setUint8(37,97),t.setUint8(38,116),t.setUint8(39,97),t.setUint32(40,e,!0),new File([t,...i],"audio.wav",{type:"audio/wav"})}var ee=class extends AudioWorkletNode{constructor(e,t,s,n){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=s;let o=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!o.includes(s))throw new Error(`Invalid format ${s}, must be one of: ${o.join(", ")}`);if(!n||n<=0)throw new Error(`Invalid buffer size: ${n}`);this.port.onmessage=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 pe=16e3,te=256,I=8,B=new u("VoiceDetectionNode"),N=class N extends ee{constructor(e){super(e,pe,"float32",te*I);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(!N.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 pe}get numberOfSamples(){return te}get numberOfSampleChunks(){return I}get outputBufferSize(){return te*I}get isModelLoaded(){return!!this.vad}async loadModel(){B.debug("Loading VAD model"),this.vad=await b.load(N.vadModelURL),this.vad.ignoreIfBusy=!0,B.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],pe),this.vad.makeState("h","hn","float32",[2,I,64]),this.vad.makeState("c","cn","float32",[2,I,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new b.onnx.Tensor(e,[I,te])});if(!t)return;this.currentProbability=0;for(let o=0;o<t.output.data.length;o++)t.output.data[o]>this.currentProbability&&(this.currentProbability=t.output.data[o]);let s=this.isVoiceActive?this.sentivityEnd:this.sensitivity,n=this.currentProbability>s;if(!n&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=n,n&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),B.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(),B.debug("Stopped speaking after timeout")),!n){let o=Date.now();o>this.nextVadReset&&(this.nextVadReset=o+5e3,this.vad.resetState())}}catch(t){B.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};N.vadModelURL="";var X=N;var ke=new u("VoiceChunkOutputNode"),E=class extends X{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){ke.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);ke.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 ie=new u("OpenAITranscriptionNode"),se=class extends E{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=ie.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=q(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let n="";try{let o=new FormData;o.append("file",s),o.append("model","whisper-1"),o.append("response_format","text");let r=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o,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(o){ie.error(`Failed to transcribe speech: ${o.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return ie.debug("Transcription complete, but no text was found");ie.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var ne=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 w=new u("IntelliWeaveTranscriptionNode"),Ue="wss://speech.intelliweave.ai/api/v1/transcribe",re=class re extends E{constructor(e,t){super(e);this.apiAddress=Ue;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(w.debug("Opening WebSocket connection"),this.ws=new ne(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=()=>{w.debug("WebSocket connection opened")},this.ws.addEventListener("message",s=>{let n=JSON.parse(s.data);if(n.error)return w.warn("Error: "+n.error);if(n.type!="transcription")return w.warn("Invalid response type",n);if(n.streaming&&!n.final)return w.debug("Partial transcription: "+n.partialText);if(this.isTranscribing=!1,!n.text.trim())return w.warn(`Empty transcription (${n.processingTime}ms)`);w.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=>w.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{w.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),re.debugExportWav){let t=q(this.sampleRate,e),s=document.createElement("a");s.href=URL.createObjectURL(t),s.download="recording.wav",s.click()}}onVoiceTranscription(e){}onSocketClose(){w.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};re.debugExportWav=!1;var oe=re;var me=new u("SpeechRecognition"),ae=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(!b.lib||!this.ai?.vadModel||!G().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),X.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new se(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new oe(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=me.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),g(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("speechend",t=>{this.ai._voiceTracker?.("Speech ended");let s=this.recordingStartTime?Date.now()-this.recordingStartTime:0;g(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:s}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),g(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:t.detail.confidence||void 0}}),this.onTranscription(t)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){me.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;me.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 le=new u("AudioSystem"),M=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 ae(this.ai),this.speechOutput=new $(this.ai)}static get isSupported(){return!(!b.lib||!G().AudioWorkletNode)}async beginAccess(i){le.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(le.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await Promise.all([this.context.audioWorklet.addModule(Ce),this.context.audioWorklet.addModule(Te)]))}endAccess(i){le.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(le.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var os=new u("Stream");import ls,{createContext as je,useContext as cs,useEffect as ds,useMemo as hs,useState as us}from"react";var vs=new u("React");var bs=je(void 0);var A=new u("Embed"),Z=class extends f{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
|
|
273
|
+
`,s.addEventListener("click",n=>{this.dispatchEvent(new CustomEvent("select",{detail:t.id}))}),e.appendChild(s)}}};P.observedAttributes=["open"];var W=new u("ONNXModel"),b=class l{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,W.debug(`Model input parameters: ${i.inputNames.join(", ")}`),W.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!l.lib}static async load(i){if(!l.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 l.lib()),W.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new l(e)}makeTensor(i,e,t=0){let s=1;for(let o of e)s*=o;let n;if(i=="float32")n=new l.onnx.Tensor(new Float32Array(s),e);else if(i=="int8")n=new l.onnx.Tensor(new Int8Array(s),e);else if(i=="int16")n=new l.onnx.Tensor(new Int16Array(s),e);else if(i=="int32")n=new l.onnx.Tensor(new Int32Array(s),e);else if(i=="int64")n=new l.onnx.Tensor(new BigInt64Array(s),e);else if(i=="uint8")n=new l.onnx.Tensor(new Uint8Array(s),e);else if(i=="uint16")n=new l.onnx.Tensor(new Uint16Array(s),e);else if(i=="uint32")n=new l.onnx.Tensor(new Uint32Array(s),e);else if(i=="uint64")n=new l.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 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)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(){W.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var Ce="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3IoO3IhPXQubGVuZ3RoOyl7aWYocj50Lmxlbmd0aCl0aHJvd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ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Je=new u("PCMPlayerNode"),j=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){Je.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 Q=new u("SpeechOutput"),Ie=.5,He=.8,$=class extends EventTarget{constructor(e){super();this.maxVolumeHeard=0;this.ai=e,this.ai.addEventListener("output",t=>this.onTextOutputFromAI(t)),this.ai.audio?.speechRecognition.addEventListener("speechstart",t=>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(e){e.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(e.detail.message)}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))}async speak(e){if(!this.ai?.config?.voice?.providerID)return Q.warn("No voice provider configured");let t=`speech-${Oe++}`;await this.ai.audio.beginAccess(t);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(t)}}async _speakWithLock(e){this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=He);let t=this.ai?._voiceTracker||Q.timer(`${this.ai.config.voice.providerID} voice`);t(`Speak: ${e}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let s=new j(this.ai.audio.context,24e3,"int16");this.currentPlayer=s,s.connect(this.analyserNode),s.addEventListener("end",o=>{let r=o;t(`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:e,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:e})});else{Q.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(t(`Received response ${n.status} ${n.statusText}`),!n.ok){Q.warn(`Failed to generate voice sample: ${n.status} ${n.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),t("Playing PCM stream"),await s.play(n.body),t("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let e=this.currentPlayerVolume,t=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Ie);let s=400;e.gain.linearRampToValueAtTime(0,s/1e3),await new Promise(n=>setTimeout(n,s+250)),e.disconnect(),t?.stop(),t?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Ie)}},Oe=1;function q(l,i){let e=i.reduce((d,c)=>d+c.byteLength,0),t=new DataView(new ArrayBuffer(44));t.setUint8(0,82),t.setUint8(1,73),t.setUint8(2,70),t.setUint8(3,70),t.setUint32(4,44+e,!0),t.setUint8(8,87),t.setUint8(9,65),t.setUint8(10,86),t.setUint8(11,69);let s=1,n=32,o=s*n/8,r=l*o;return t.setUint8(12,102),t.setUint8(13,109),t.setUint8(14,116),t.setUint8(15,32),t.setUint32(16,16,!0),t.setUint16(20,3,!0),t.setUint16(22,s,!0),t.setUint32(24,l,!0),t.setUint32(28,r,!0),t.setUint16(32,o,!0),t.setUint16(34,n,!0),t.setUint8(36,100),t.setUint8(37,97),t.setUint8(38,116),t.setUint8(39,97),t.setUint32(40,e,!0),new File([t,...i],"audio.wav",{type:"audio/wav"})}var ee=class extends AudioWorkletNode{constructor(e,t,s,n){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=s;let o=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!o.includes(s))throw new Error(`Invalid format ${s}, must be one of: ${o.join(", ")}`);if(!n||n<=0)throw new Error(`Invalid buffer size: ${n}`);this.port.onmessage=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 pe=16e3,te=256,k=8,B=new u("VoiceDetectionNode"),N=class N extends ee{constructor(e){super(e,pe,"float32",te*k);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(!N.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 pe}get numberOfSamples(){return te}get numberOfSampleChunks(){return k}get outputBufferSize(){return te*k}get isModelLoaded(){return!!this.vad}async loadModel(){B.debug("Loading VAD model"),this.vad=await b.load(N.vadModelURL),this.vad.ignoreIfBusy=!0,B.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],pe),this.vad.makeState("h","hn","float32",[2,k,64]),this.vad.makeState("c","cn","float32",[2,k,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new b.onnx.Tensor(e,[k,te])});if(!t)return;this.currentProbability=0;for(let o=0;o<t.output.data.length;o++)t.output.data[o]>this.currentProbability&&(this.currentProbability=t.output.data[o]);let s=this.isVoiceActive?this.sentivityEnd:this.sensitivity,n=this.currentProbability>s;if(!n&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=n,n&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),B.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(),B.debug("Stopped speaking after timeout")),!n){let o=Date.now();o>this.nextVadReset&&(this.nextVadReset=o+5e3,this.vad.resetState())}}catch(t){B.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};N.vadModelURL="";var X=N;var We=new u("VoiceChunkOutputNode"),E=class extends X{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){We.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);We.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 ie=new u("OpenAITranscriptionNode"),se=class extends E{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=ie.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=q(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let n="";try{let o=new FormData;o.append("file",s),o.append("model","whisper-1"),o.append("response_format","text");let r=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o,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(o){ie.error(`Failed to transcribe speech: ${o.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return ie.debug("Transcription complete, but no text was found");ie.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var ne=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 w=new u("IntelliWeaveTranscriptionNode"),Ue="wss://speech.intelliweave.ai/api/v1/transcribe",re=class re extends E{constructor(e,t){super(e);this.apiAddress=Ue;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(w.debug("Opening WebSocket connection"),this.ws=new ne(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=()=>{w.debug("WebSocket connection opened")},this.ws.addEventListener("message",s=>{let n=JSON.parse(s.data);if(n.error)return w.warn("Error: "+n.error);if(n.type!="transcription")return w.warn("Invalid response type",n);if(n.streaming&&!n.final)return w.debug("Partial transcription: "+n.partialText);if(this.isTranscribing=!1,!n.text.trim())return w.warn(`Empty transcription (${n.processingTime}ms)`);w.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=>w.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{w.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),re.debugExportWav){let t=q(this.sampleRate,e),s=document.createElement("a");s.href=URL.createObjectURL(t),s.download="recording.wav",s.click()}}onVoiceTranscription(e){}onSocketClose(){w.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};re.debugExportWav=!1;var oe=re;var me=new u("SpeechRecognition"),ae=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(!b.lib||!this.ai?.vadModel||!G().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),X.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new se(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new oe(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=me.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),g(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("speechend",t=>{this.ai._voiceTracker?.("Speech ended");let s=this.recordingStartTime?Date.now()-this.recordingStartTime:0;g(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:s}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),g(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:t.detail.confidence||void 0}}),this.onTranscription(t)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){me.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;me.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 le=new u("AudioSystem"),M=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 ae(this.ai),this.speechOutput=new $(this.ai)}static get isSupported(){return!(!b.lib||!G().AudioWorkletNode)}async beginAccess(i){le.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(le.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await Promise.all([this.context.audioWorklet.addModule(Ce),this.context.audioWorklet.addModule(Te)]))}endAccess(i){le.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(le.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var os=new u("Stream");import ls,{createContext as je,useContext as cs,useEffect as ds,useMemo as hs,useState as us}from"react";var vs=new u("React");var bs=je(void 0);var A=new u("Embed"),Z=class extends f{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
|
|
274
274
|
|
|
275
275
|
<!-- Styling -->
|
|
276
276
|
<style>
|
|
@@ -456,4 +456,4 @@ ${i.extractions.map(s=>`- ${s.name} (${s.type}): ${s.description||"No descriptio
|
|
|
456
456
|
|
|
457
457
|
</div>
|
|
458
458
|
|
|
459
|
-
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._isProcessing=!1;this.ai=new
|
|
459
|
+
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._isProcessing=!1;this.ai=new I,M.isSupported&&(this.ai.audio=new M(this.ai))}onCreate(){p().embed&&A.warn("Only one <web-weaver-embed> element should be on the page."),p().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.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||p().apiKey;if(!t)return A.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(t).then(s=>{this.config=s,p().introductionMessage=this.config.introductionMessage,p().analytics=this.config.analytics!==void 0?!!this.config.analytics:p().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(s=>{A.error("Failed to load AI configuration:",s),this.state.loading=!1;let n=this.child("web-weaver-embed-inner");n&&(n.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyConfigStylesAndAttributes(){let e=this.config,t=this.child("root");if(!t)return;let s=!1,o=this.getAttribute("logo")||e.logo;if(o&&o!==this._lastLogo){this._lastLogo=o,s=!0;let y=this.child("web-weaver-logo");y&&y.setAttribute("logo",o)}let d=this.getAttribute("background")||e.background;d!==this._lastBackground&&(this._lastBackground=d,s=!0,d?t.style.background=d:t.style.background="");let a=this.getAttribute("textColor")||e.textColor,h=this.child("interaction-bar");a!==this._lastTextColor&&(this._lastTextColor=a,s=!0,a?(t.style.color=a,h&&h.setAttribute("textColor",a)):(t.style.color="",h&&h.removeAttribute("textColor"))),s&&A.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:o,finalBackground:t.style.background,finalTextColor:t.style.color})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),g(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let e=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;g(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:e}})}this._previousOpenState=this.attr.open,this.attr.open?this.child("root").classList.add("open"):this.child("root").classList.remove("open"),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,this.child("llm-selector-panel").state.items=this.ai.models.sort((e,t)=>(t.priority||0)-(e.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){p().embed==this&&(p().embed=void 0)}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=p().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 p().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.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"}),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.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}catch(s){A.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 it().use(et).use(tt).use(Qe,{target:"_blank",rel:["noopener","noreferrer"]}).use($e).use(qe).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.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}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.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}onSuggestionClick(e,t){this.processInput(t)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}};Z.tagName="intelliweave-embed",Z.observedAttributes=["logo","focusID","open","background","textColor"];var dn=Z;b.lib=()=>import("onnxruntime-web");Z.register();export{dn as default};
|
|
Binary file
|