@intelliweave/embedded 2.0.71 → 2.0.72-beta.10

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,17 +1,18 @@
1
- import Fe,{createContext as wt,useContext as xt,useEffect as ue,useMemo as St,useState as Ze}from"react";import{v4 as Ie}from"uuid";function be(a){let i=(a||"").split(`
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 Oe={};function C(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:Oe}function h(){return C().intelliweave=C().intelliweave||C().webWeaver||{},C().intelliweave}async function*We(a){let i="",e=function*(){for(;;){let n=i.indexOf(`
1
+ import st,{createContext as Zt,useContext as Dt,useEffect as ve,useMemo as Xt,useState as Ge}from"react";import ut from"openai";import{v4 as lt}from"uuid";var L=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new Ce;return e.id=i,this.groups.push(e),e}group(i){return this.groups.find(e=>e.id===i)}static countTokensInText(i){return i==null?i="":typeof i=="number"?i=i+"":typeof i!="string"&&(i=JSON.stringify(i)),Math.ceil(i.length/3)}countTokens(){return this.groups.reduce((i,e)=>i+e.tokenCount,0)}removeOverflow(){let i=this.countTokens(),e=this.groups.reduce((t,n)=>t+n.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((o,s)=>{let a=Math.floor(o.weight/e*this.size),l=Math.floor(s.weight/e*this.size),u=o.tokenCount-a;return s.tokenCount-l-u}),n=this.removeOneItem(t);if(!n)throw new Error("Too many items in the token window that cannot be removed.");i-=n.tokenCount}}removeOneItem(i){for(let e of i){let t=e.items.findIndex(o=>!o.cannotRemove);if(t===-1)continue;let n=e.items[t];return e.items.splice(t,1),e.tokenCount-=n.tokenCount,n}return null}},Ce=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
2
+ `;this.itemPadding=0;this.sortFunction=(i,e)=>i.sortOrder!==e.sortOrder?i.sortOrder-e.sortOrder:i.dateAdded!==e.dateAdded?i.dateAdded-e.dateAdded:0}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=L.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+L.countTokensInText(this.separator)+this.itemPadding,i+e.tokenCount),0)}add(i){typeof i=="string"&&(i={source:"user",data:i});let e=i;e.id===void 0&&(e.id=lt()),!e.sections?.length&&typeof e.data=="string"?e.text=e.data:e.text=e.sections?.map(n=>{if(n.type==="text")return n.text||"";if(n.type==="tool_call")return`[Tool Call: ${n.toolKbName||n.toolName}] `;if(n.type==="tool_result"&&n.toolErrorResponse)return`[Tool Error: ${n.toolErrorResponse}] `}).filter(n=>!!n).join(`
4
3
 
5
- `);if(n==-1)break;let o=i.slice(0,n);i=i.slice(n+2);let r={},d=o.split(`
6
- `);for(let c of d){n=c.indexOf(": ");let l=c.slice(0,n),p=c.slice(n+2);n==-1&&(l=c,p=""),l&&(r[l]!==void 0?r[l]+=`
7
- `+p:r[l]=p)}yield r}},t=new TextDecoder,s=a.getReader();for(;;){let{done:n,value:o}=await s.read();if(n)break;i+=t.decode(o,{stream:!0}),yield*e()}i+=t.decode()+`
4
+ `)||"";let t=this.items.find(n=>n.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.source===void 0&&(e.source="user"),e.sections===void 0&&(e.sections=[]),e.tokenCount=e.disabled?0:L.countTokensInText(typeof i.data=="string"?i.data:JSON.stringify(i.data))+L.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}getAllAsString(){return this.getAll().map(i=>i.text).join(this.separator)}getAll(){return this.items.filter(i=>!i.disabled)}empty(){this.items=[],this.tokenCount=0}};import{v4 as dt}from"uuid";import{v4 as Xe}from"uuid";function ee(r){let i=(r||"").split(`
5
+ `);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 n=t.match(/^\s*/)?.[0].length||0;e=Math.min(e,n)}return e>0&&e<1/0&&(i=i.map(t=>t.substring(e))),i.join(`
6
+ `)}var ct={};function A(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:ct}function h(){return A().intelliweave=A().intelliweave||A().webWeaver||{},A().intelliweave}function Re(){if(h().userID)return h().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let r=localStorage.getItem("intelliweave.uid")||"";return r||(r=Xe(),localStorage.setItem("intelliweave.uid",r),r)}else return Xe()}function Pe(r){let i=r;if(i?.type=="object"&&i.properties)return r;let e={type:"object",properties:{},required:[]};if(r&&Array.isArray(r)){let t=r;for(let n of t)e.properties[n.name]={type:n.type||"string",description:n.description||""}}return e}var te=class te{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return te.debug?!0:typeof window<"u"&&h().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...n)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...n)}};te.debug=!1;var p=te;var Ve=new p("ChatBase"),X=class{constructor(i){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let i=new L;return i.createGroup("context").setSeparator(`
8
7
 
9
- `,yield*e()}function Xe(){if(h().userID)return h().userID||"";if(typeof localStorage<"u"){let a=localStorage.getItem("intelliweave.uid")||"";return a||(a=Ie(),localStorage.setItem("intelliweave.uid",a),a)}else return Ie()}function Te(a){let i=a;if(i?.type=="object"&&i.properties)return a;let e={type:"object",properties:{},required:[]};if(a&&Array.isArray(a)){let t=a;for(let s of t)e.properties[s.name]={type:s.type||"string",description:s.description||""}}return e}var z=class z{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return z.debug?!0:typeof window<"u"&&h().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...s)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...s)}};z.debug=!1;var u=z;import{countTokens as He}from"gpt-tokenizer";import{countTokens as O}from"gpt-tokenizer";import{v4 as Je}from"uuid";var J=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new ve;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}},ve=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=O(e.content)+O(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=Je());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:O(i.content)+O(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}};var X=class{constructor(i){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let i=new J;return i.createGroup("context").setSeparator(`
8
+ `),i.createGroup("actions").setItemPadding(25),i.createGroup("messages").setItemPadding(10),i})();this.config=i,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}getBaseURL(){if(!this.config.endpoint)return;let i=this.config.endpoint;return i.endsWith("/chat/completions")&&(i=i.substring(0,i.length-17)),i}async sendMessage(i,e){throw new Error("Not implemented")}addUserMessage(i){throw new Error("Not implemented")}addAssistantMessage(i){throw new Error("Not implemented")}addTextMessage(i,e,t){this.messageGroup.add({id:"msg-"+dt(),source:e,data:t,sections:[{type:"text",text:i}]})}onBeforeIncomingMessage(i){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(i){return this.toolGroup.add({id:i.name,data:i,cannotRemove:!i.canRemove,sortOrder:101,disabled:!!i.kbItem?.disabled})}findToolBySafeName(i){return this.toolGroup.getAll().find(e=>e.id==i||e.data?.kbItem?.name==i)?.data}async executeTool(i,e){if(!i)throw new Error("Tool not found");Ve.debug(`Executing tool '${i.name}'`,e,i),this.config.onAIToolStart?.(i.kbItem?.name||i.name,e);let t;try{t=await i.callback(e)}catch(n){throw Ve.error(`Error executing tool '${i.name}'`,n),n}return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),t}};import{v4 as pt}from"uuid";var Le=new p("ChatGPT"),ie=class extends X{addUserMessage(i){this.addTextMessage(i,"user",{role:"user",content:i||""})}addAssistantMessage(i){this.addTextMessage(i,"assistant",{role:"assistant",content:i||""})}createOpenAIClient(){return new ut({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(i,e){this.addUserMessage(i);let t=this.createOpenAIClient(),n=!0,o=[];for(;n;){let s="msg-"+pt();n=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),Le.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.data),tools:this.toolGroup.getAll().map(d=>d.data),context:this.contextGroup.getAll().map(d=>d.text)});let a=this.toolGroup.getAll().filter(d=>!!d?.data).map(d=>({type:"function",function:{name:d.data.name,description:d.data.description||"",parameters:{type:"object",...d.data?.params}}})),l,u;if(this.config.stream){let d=t.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(g=>g.data)],tools:a,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let g of d){let m=d.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!m)continue;let f=this.parseMessageBlock(s,m,void 0,!0);this.config.onAIMessage?.([...o,f],!0),e?.([...o,f])}l=await d.finalMessage(),u=await d.totalUsage()}else{let d=await t.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(g=>g.data)],tools:a,parallel_tool_calls:!0});l=d.choices[0].message,u=d.usage}l.role=="assistant"&&!l.content&&!l.tool_calls?.length&&(l.content=""),Le.debug("Message received",l);let c=this.messageGroup.add(this.parseMessageBlock(s,l,u,!1));o.push(c),await Promise.all((l.tool_calls||[]).map(async d=>{if(d.type!="function")return;let g=this.findToolBySafeName(d.function.name);try{let m=null;try{m=d.function.arguments?JSON.parse(d.function.arguments):null}catch(k){throw new Error(`The AI provided invalid JSON arguments for tool call ${d.function.name}: ${k.message}`)}let f=await this.executeTool(g,m),b=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:g?.kbItem?.id,toolKbName:g?.kbItem?.name,toolSuccessResponse:f,toolCallInstanceID:d.id,toolCallHiddenInUI:g?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:f}});o.push(b)}catch(m){let f=m?.message||"An unknown error occurred",b=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:g?.kbItem?.id,toolKbName:g?.kbItem?.name,toolErrorResponse:f,toolCallInstanceID:d.id,toolCallHiddenInUI:g?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:`Error performing tool call ${d.function.name}: ${f}`}});o.push(b)}n=!0,this.config.onAIMessage?.(o,!0),e?.(o)})),this.stats.tokensUsed+=u?.total_tokens||0}return this.config.onAIMessage?.(o,!1),e?.(o),o}parseMessageBlock(i,e,t,n){let o=[];e.reasoning&&o.push({type:"thinking",text:e.reasoning});for(let s of e.tool_calls||[]){if(s.type!="function")continue;let a=this.findToolBySafeName(s.function.name),l=null;if(s.function.arguments)try{l=JSON.parse(s.function.arguments)}catch(u){n||Le.error(`Failed to parse tool parameters for tool call ${s.function.name}:`,u)}o.push({type:"tool_call",toolName:s.function.name,toolKbID:a?.kbItem?.id,toolKbName:a?.kbItem?.name,toolCallInstanceID:s.id,toolCallHiddenInUI:a?.kbItem?.hideActionInUI,toolParameters:l})}return typeof e.content=="string"&&o.push({type:"text",text:e.content||""}),{id:i,data:e,sections:o,source:"assistant",streamingInProgress:n,usage:{inputTokens:t?.prompt_tokens||0,outputTokens:t?.completion_tokens||0,cachedInputTokens:0,totalTokens:(t?.prompt_tokens||0)+(t?.completion_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].data?.role=="tool";)this.messageGroup.items.shift()}};import ht from"@anthropic-ai/sdk";import{v4 as mt}from"uuid";var Be=new p("AnthropicChat"),ne=class extends X{addUserMessage(i){this.addTextMessage(i,"user",{role:"user",content:i||""})}addAssistantMessage(i){this.addTextMessage(i,"assistant",{role:"assistant",content:i||""})}async sendMessage(i,e){this.addUserMessage(i);let t=new ht({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),n=!0,o=[];for(;n;){n=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),Be.debug("Before processing state",{messages:this.messageGroup.getAll().map(c=>c.data),tools:this.toolGroup.getAll().map(c=>c.data),context:this.contextGroup.getAll().map(c=>c.text)});let s=this.toolGroup.getAll().map(c=>({name:c.data?.name||"",description:c.data?.description||"",input_schema:{...c.data?.params,type:"object"}})),a;if(this.config.stream){let c=t.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(d=>d.data),tools:s,stream:!0});c.on("streamEvent",(d,g)=>{let m=this.parseMessageBlock(g,!0);this.config.onAIMessage?.([...o,m],!0),e?.([...o,m])});try{a=await c.finalMessage()}catch(d){throw d?.error?.error?.message?d.error.error:d}}else try{a=await t.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(c=>c.data),tools:s})}catch(c){throw c?.error?.error?.message?c.error.error:c}if(Be.debug("Message received",a),a.content?.length){let c=this.messageGroup.add(this.parseMessageBlock(a,!1));o.push(c)}let l=[],u=[];if(await Promise.all(a.content.map(async c=>{if(c.type!="tool_use")return;let d=this.findToolBySafeName(c.name);try{let g=await this.executeTool(d,c.input);u.push({type:"tool_result",tool_use_id:c.id,content:g}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:c.name,toolSuccessResponse:g,toolCallInstanceID:c.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}catch(g){let m=g?.message||"An unknown error occurred";u.push({type:"tool_result",tool_use_id:c.id,content:`Error performing tool call ${c.name}: ${m}`}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:c.name,toolErrorResponse:m,toolCallInstanceID:c.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}})),u.length>0){let c=this.messageGroup.add({id:"msg-"+mt(),sections:l,data:{role:"user",content:u}});o.push(c),n=!0,this.config.onAIMessage?.(o,!0),e?.(o)}this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return this.config.onAIMessage?.(o,!1),e?.(o),o}parseMessageBlock(i,e){let t=[];for(let n of i.content)if(n.type=="thinking")t.push({type:"thinking",text:n.thinking||""});else if(n.type=="text")t.push({type:"text",text:n.text||""});else if(n.type=="tool_use"){let o=this.findToolBySafeName(n.name);t.push({type:"tool_call",toolName:n.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:n.input,toolCallInstanceID:n.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:i.id,data:{role:i.role,content:i.content},sections:t,source:"assistant",streamingInProgress:e,usage:{inputTokens:i.usage?.input_tokens||0,outputTokens:i.usage?.output_tokens||0,cachedInputTokens:i.usage?.cache_read_input_tokens||0,totalTokens:(i.usage?.input_tokens||0)+(i.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import{v4 as _e}from"uuid";import It from"minisearch";var ze=r=>[{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,hideActionInUI:"after-complete",parameters:[{name:"query",type:"string",description:"The search query"}],action:async(i,e)=>{let t=await e.knowledgeBase.search(i.query),n=e;n._lastKBsearch=i.query,n._nextRequestUseKBitems=t;let o=t.filter(a=>a.type!="action").map(a=>"- "+a.name).join(`
9
+ `)||"- (none)",s=t.filter(a=>a.type=="action").map(a=>"- "+a._functionID).join(`
10
+ `)||"- (none)";return`Search complete, context has been updated.
11
+ New information found:
12
+ ${o}
11
13
 
12
- `),i.createGroup("actions").setItemPadding(25),i.createGroup("messages").setItemPadding(10),i})();this.config=i,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(i){throw new Error("Not implemented")}addUserMessage(i){throw new Error("Not implemented")}addAssistantMessage(i){throw new Error("Not implemented")}onBeforeIncomingMessage(i){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(i){return this.toolGroup.add({id:i.name,customData:i,cannotRemove:i.isContext,sortOrder:101,disabled:i.disabled,content:JSON.stringify(i)})}};import{v4 as T}from"uuid";var x=new u("ChatGPT"),H=class extends X{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(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendRequest(i){let e={};return e["Content-Type"]="application/json",this.config.apiKey&&(e.Authorization=`Bearer ${this.config.apiKey}`),await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:e,body:JSON.stringify(i)})}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 r=this.messageGroup.items.length-1;r>=0;r--){let d=this.messageGroup.items[r].customData;if(d.role=="assistant"&&d.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(d.role=="user")break}x.debugEnabled&&x.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(r=>r.customData),messages:this.messageGroup.items.map(r=>r.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(r=>r.customData)]};for(let r of this.toolGroup.getAll()){let d=r.customData;d.description&&d.description.length>1024&&x.warn(`Tool description for "${d.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:d.name,description:(d.description||"").substring(0,1024),parameters:d.params}};t.tools.push(c)}if(t.user||delete t.user,t.tools.length||delete t.tools,i)return t;let s=await this.sendRequest(t);if(!s.ok){let r=`${s.status} ${s.statusText}`;try{let c=await s.json();r=c.errorText||c.error?.message||c.error||r}catch{}let d=new Error(r);throw d.code=s.status,d}let n=null,o=null;if(this.config.stream){for await(let d of We(s.body)){if(d.data=="[DONE]")break;if(!d.data)continue;let c=JSON.parse(d.data);if(o){for(let l in c.choices[0].delta)if(typeof c.choices[0].delta[l]=="string"){if(l=="role"&&o[l]==c.choices[0].delta[l])continue;o[l]=(o[l]||"")+c.choices[0].delta[l]}for(let l of c.choices[0].delta.tool_calls||[]){if(o.tool_calls||(o.tool_calls=[]),!o.tool_calls[l.index]){o.tool_calls[l.index]=l;continue}let p=o.tool_calls[l.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(l.function?.name||""),p.function.arguments=(p.function.arguments||"")+(l.function?.arguments||"")}}else o={chunkID:c.id,...c.choices[0].delta};o?.content&&!o.content.startsWith("{")&&this.config.onAIMessage?.(o.content,!0)}let r=He(JSON.stringify(t)+JSON.stringify(o)||"");this.stats.tokensUsed+=r,x.debug(`Estimated ${r} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else n=await s.json(),this.stats.tokensUsed+=n?.usage?.total_tokens||0,x.debug(`Used ${n?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),o=n?.choices?.[0]?.message;if(o||(x.warn("No response block in API response."),o={role:"assistant",content:""}),o.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(o),this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(o),customData:o}),o.content&&this.config.onAIMessage?.(o.content,!1)}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})}}};import Ue from"@anthropic-ai/sdk";import{v4 as U}from"uuid";var j=new u("AnthropicChat"),$=class extends X{addUserMessage(i){let e={role:"user",content:i||""};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(e),customData:e})}addAssistantMessage(i){let e={role:"assistant",content:i||""};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(e),customData:e})}async sendMessage(i){this.addUserMessage(i);let e=new Ue({apiKey:this.config.apiKey,baseURL:this.config.endpoint,dangerouslyAllowBrowser:!0}),t=!0,s="",n="";for(;t;){t=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),j.debug("Before processing state",{messages:this.messageGroup.getAll().map(m=>m.customData),tools:this.toolGroup.getAll().map(m=>m.customData),context:this.contextGroup.getAll().map(m=>m.content)});let o=this.toolGroup.getAll().map(m=>({name:m.customData?.name||"",description:m.customData?.description||"",input_schema:{type:"object",required:m.customData?.params.required||[],properties:m.customData?.params.properties||{}}})),r;if(this.config.stream){let m=e.messages.stream({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(Z=>Z.customData),tools:o,stream:!0});m.on("text",Z=>{n+=Z,this.config.onAIMessage?.(n,!0)}),r=await m.finalMessage()}else r=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(m=>m.customData),tools:o});j.debug("Message received",r);let d=!0;Array.isArray(r.content)&&r.content.length==0&&(d=!1);let c={role:r.role,content:r.content};d&&this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(c),customData:c});let l=[];for(let m of r.content)m.type=="thinking"?j.debug(`AI is thinking: ${m.thinking}`):m.type=="text"?s+=m.text||`
13
-
14
- `:m.type=="tool_use"&&l.push(this.performToolCall(m));let p=await Promise.all(l);if(p.length>0){let m={role:"user",content:p};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(m),customData:m}),t=!0}this.config.onAIMessage?.(s,!0),this.stats.tokensUsed+=r.usage.input_tokens+r.usage.output_tokens}return s=s.trim(),this.config.onAIMessage?.(s,!1),s}async performToolCall(i){try{let e=this.toolGroup.getAll().find(s=>s.customData?.name==i.name);if(!e)throw new Error(`Tool ${i.name} not found`);this.config.onAIToolStart?.(i.name,i.input);let t=await e.customData.callback(i.input);return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),{type:"tool_result",tool_use_id:i.id,content:String(t||"")}}catch(e){return j.error(`Error performing tool call ${i.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:i.id,content:`Error performing tool call ${i.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import{v4 as xe}from"uuid";import st from"minisearch";var Ee=a=>[{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(i,e)=>{let t=await e.knowledgeBase.search(i.query),s=e;s._lastKBsearch=i.query,s._nextRequestUseKBitems=t,e.submitAnalyticsEvent({type:"kb-search",query:i.query,results:t});let n=t.filter(r=>r.type!="action").map(r=>"id="+r.id).join(", ")||"(none)",o=t.filter(r=>r.type=="action").map(r=>"name="+r._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:i.url}),`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,e.submitAnalyticsEvent({type:"change-route",path:t}),`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),s=encodeURIComponent(i.subject),n=encodeURIComponent(i.body),o=`mailto:${t}?subject=${s}&body=${n}`;try{window.location.href=o}catch(r){throw new Error(`Failed to open email client: ${r instanceof Error?r.message:String(r)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:i.email_address,subject:i.subject,body_length:i.body.length}),`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as Re}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as $e}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Qe}from"@modelcontextprotocol/sdk/client/sse.js";var S={name:"@intelliweave/embedded",version:"2.0.71",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run 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:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.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 qe,ToolListChangedNotificationSchema as et}from"@modelcontextprotocol/sdk/types.js";var g=new u("MCPKnowledgeClient"),Q=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(){g.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Re({name:S.name,version:S.version}),t=new $e(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Re({name:S.name,version:S.version}),s=new Qe(new URL(this.config.baseURL));return await t.connect(s),g.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{g.error(`MCP client error: ${e.message}`)},i.onclose=()=>{g.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(qe,e=>{e.params.level=="critical"?g.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?g.error(`[Server] ${e.params.data}`):e.params.level=="error"?g.error(`[Server] ${e.params.data}`):e.params.level=="warning"?g.warn(`[Server] ${e.params.data}`):e.params.level=="info"?g.info(`[Server] ${e.params.data}`):e.params.level=="debug"?g.debug(`[Server] ${e.params.data}`):g.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(et,e=>{g.debug("Tool list changed",e),this.fetchTools()}),g.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})}g.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,g.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 g.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(),g.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 g.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 tt}from"uuid";var it=new u("Statistics"),N=[];async function f(a,i){let e={...i,event_id:tt(),event_date:new Date().toISOString(),sdk_version:S.version,conversation_id:a?.conversationID||"",api_key:a?.apiKey||"",user_id:a?.userID||""};if(N.push(e),!a||(await new Promise(s=>setTimeout(s,5e3)),N.length===0))return;let t=N.slice();N.length=0;try{let s=await fetch(a.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){it.warn("Failed to submit analytics event:",s),N.push(...t);return}}var k=new u("KnowledgeBase"),we=1,q=class a{constructor(i){this._sources=[{id:"core.internal",query:async()=>Ee(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${we++}`),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 h().knowledgeBaseSources&&(i=i.concat(h().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();k.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 l=Date.now(),p=await c.query(i);return k.debug(`Source '${c.id}' took ${Date.now()-l}ms`),p||[]}catch(l){return k.warn(`Knowledge source '${c.id}' failed:`,l),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),h().knowledgeBase&&(n=n.concat(h().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let l=n[c];l.id=l.id||`temp.${c}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!l.action&&l.type=="tour"&&(l.action=p=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=p=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new st({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(l=>l.id==c.id));for(let c of n)c.isContext&&(d.find(l=>l.id===c.id)||d.push(c));return this.lastResults=d,f(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),k.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${we++}`),k.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{k.debug(`Calling remote knowledge base action: ${d.id}`);let l={type:"action",userID:this.ai.userID,actionID:d.id,parameters:c},p=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!p.ok)throw new Error(`HTTP Error ${p.status} ${p.statusText}`);let m=await p.json();return r(m.updateItems||[]),m.response},r=d=>{for(let c of d){if(!c.id){k.warn("KB item skipped since it has no ID.",c);continue}let l=t.find(p=>p.id==c.id);if(l){l.name=c.name||l.name||"",l.content=c.content||l.content||"",l.disabled=c.disabled??l.disabled,l.isContext=c.isContext??l.isContext,l.parameters=c.parameters||l.parameters||[],l.tags=c.tags||l.tags,l.type=c.type||l.type;continue}t.push({...c,action:p=>o(c,p)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",query:d},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let p=await l.json();return n=!p.noCache,s.includes(d)||s.push(d),r(p.items),t})}clone(){let i=new a(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${we++}`);let e=new Q(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ee=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
14
+ New tools available:
15
+ ${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),n=encodeURIComponent(i.subject),o=encodeURIComponent(i.body),s=`mailto:${t}?subject=${n}&body=${o}`;try{window.location.href=s}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as ft}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as yt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var E={name:"@intelliweave/embedded",version:"2.0.72-beta.10",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 && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.95","@types/lodash":"^4.17.23","@types/react":"^18.3.12",bestzip:"^2.2.1","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.17",vitest:"^4.0.18"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.74.0","@modelcontextprotocol/sdk":"^1.26.0","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.22.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{LoggingMessageNotificationSchema as bt,ToolListChangedNotificationSchema as wt}from"@modelcontextprotocol/sdk/types.js";var y=new p("MCPKnowledgeClient"),vt="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",oe=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(){y.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new URL(this.config.baseURL),t={};this.config.headers&&(t={...t,...this.config.headers}),this.config.proxy?.enabled&&(t["Mcp-Target-Url"]=e.toString(),t["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",e=new URL(this.config.proxy.url||vt));let n=new ft({name:E.name,version:E.version}),o=new yt(e,{requestInit:{headers:t}});return await n.connect(o),y.debug("Connected with HTTP streaming mode"),n});return await this.disconnect(),this.client=i,i.onerror=e=>{y.error(`MCP client error: ${e.message}`)},i.onclose=()=>{y.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(bt,e=>{e.params.level=="critical"?y.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?y.error(`[Server] ${e.params.data}`):e.params.level=="error"?y.error(`[Server] ${e.params.data}`):e.params.level=="warning"?y.warn(`[Server] ${e.params.data}`):e.params.level=="info"?y.info(`[Server] ${e.params.data}`):e.params.level=="debug"?y.debug(`[Server] ${e.params.data}`):y.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(wt,e=>{y.debug("Tool list changed",e),this.fetchTools()}),y.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 n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let o of n.tools||[])i.push(o);if(!n?.tools?.length||!e)break}let t=[];for(let n of i){let o=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:s=>this.performToolCall(n.name,s),disabled:o})}y.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,y.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(o=>o.name==this.config.searchToolName);if(!t)return y.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(t.inputSchema.required?.length==1){let o=t.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let o=Object.keys(t.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let o=0;o<n.length;o++){let s=n[o];e.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(i,e){await this.connect(),y.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 n=t.content?.[0]?.text||"Unknown error";throw y.error(`Error calling tool ${i}: ${n}`),new Error(`Error calling tool ${i}: ${n}`)}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 xt}from"uuid";var Mt=new p("Statistics"),U=[];async function w(r,i){let e={...i,event_id:xt(),event_date:new Date().toISOString(),sdk_version:E.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(U.push(e),!r||(await new Promise(n=>setTimeout(n,5e3)),U.length===0))return;let t=U.slice();U.length=0;try{let n=await fetch(r.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){Mt.warn("Failed to submit analytics event:",n),U.push(...t);return}}var Z=new p("KnowledgeBase"),Ae=1,se=class r{constructor(i){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.ai=i,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(i=>i.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>ze(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${Ae++}`),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 this.allowGlobalConfigSources&&h().knowledgeBaseSources&&(i=i.concat(h().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(i=i.concat(this._windowSources)),i=i.filter(e=>!e.disabled),i}async search(i){Z.debug(`Searching knowledge base for: ${i}`);let e=Date.now(),t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(t),this._windowSources=t.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async u=>{try{let c=Date.now(),d=await u.query(i);return Z.debug(`Source '${u.id}' took ${Date.now()-c}ms`),d||[]}catch(c){return Z.warn(`Knowledge source '${u.id}' failed:`,c),[]}}))).flat();o=o.concat(t.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&h().knowledgeBase&&(o=o.concat(h().knowledgeBase)),o=o.filter(u=>u&&!u.disabled);for(let u=0;u<o.length;u++){let c=o[u];c.id=c.id||`temp.${u}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new It({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(i).map(u=>o.find(c=>c.id==u.id));for(let u of o)u.isContext&&(l.find(c=>c.id===u.id)||l.push(u));return this.lastResults=l,w(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),Z.debug("Found results:",l),l}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${Ae++}`),Z.debug(`Registering remote knowledge base source: ${i}`);let t=[],n=[],o=!0,s=async(l,u)=>{Z.debug(`Calling remote knowledge base action: ${l.id}`);let c={type:"action",userID:this.ai.userID,actionID:l.id,parameters:u},d=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let g=await d.json();return a(g.updateItems||[]),g.response},a=l=>{for(let u of l){if(!u.id){Z.warn("KB item skipped since it has no ID.",u);continue}let c=t.find(d=>d.id==u.id);if(c){c.name=u.name||c.name||"",c.content=u.content||c.content||"",c.disabled=u.disabled??c.disabled,c.isContext=u.isContext??c.isContext,c.parameters=u.parameters||c.parameters||[],c.tags=u.tags||c.tags,c.type=u.type||c.type;continue}t.push({...u,action:d=>s(u,d)})}};this.registerSource(e,async l=>{if(o&&n.includes(l))return t;let u={type:"search",userID:this.ai?.userID||"",query:l},c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let d=await c.json();return o=!d.noCache,n.includes(l)||n.push(l),a(d.items),t})}clone(){let i=new r(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i.ensureInternalKnowledge(),i}registerMCPSource(i){i.id||(i.id=`external.${Ae++}`);let e=new oe(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ae=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
15
16
 
16
17
  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}
17
18
 
@@ -25,14 +26,33 @@ You will receive some data. Extraction instructions: ${i.instruction}
25
26
  ${i.allowMultiple?"Return a JSONL string only, one JSON object on each line.":"Return a valid JSON object only."}
26
27
 
27
28
  Objects should have the following keys:
28
- ${i.extractions.map(s=>`- ${s.name} (${s.type}): ${s.description||"No description provided."}`).join(`
29
+ ${i.extractions.map(n=>`- ${n.name} (${n.type}): ${n.description||"No description provided."}`).join(`
29
30
  `)}
30
- `,t=await this.instruct({...i,instruction:e});if(t=t.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),i.allowMultiple){let s=t.split(`
31
- `).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"),Ve=new Set,I=class I extends EventTarget{constructor(){super(...arguments);this.conversationID=xe();this.knowledgeBase=new q(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new ee(this);this.userID=Xe();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this._lastTrackedTokens=0}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:I.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}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(n=>n.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let s={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(n,o)=>{let r=this.knowledgeBase.getCachedEntry(n);this.onAIToolStart?.(r?.id||n,o)}};t.config.providerID==="anthropic"?this.currentModel=new $(s):this.currentModel=new H(s),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=h().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=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let t=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,content:t}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,content:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,content:`# Knowledge Database
32
- 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).${e.length==0?`
33
-
34
- (no items found)`:""}`});for(let n of e)if(n.type=="info"||n.type=="tour"||n.type=="input-event"){let o=be(typeof n.content=="function"?n.content():n.content);this.currentModel.contextGroup.add({id:n.id,customData:n,cannotRemove:n.isContext,sortOrder:101,disabled:n.disabled,content:`## ${n.type}: ${n.name}
35
- ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeof n.content=="function"?n.content():n.content),params:Te(n.parameters||[{name:"value",type:"string",description:"Input"}]),removeFromMessageHistory:!!n.removeFromMessageHistory,callback:r=>this.toolRunKBAction(n,r),kb:n};this.currentModel.registerTool(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 s=this.currentModel?.stats?.tokensUsed||0,n=s-(this._lastTrackedTokens||0);this._lastTrackedTokens=s,f(this,{event_type:"message_receive",value:n,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:s}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:t,message:e}})),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(),Ve.has(this.conversationID)||(Ve.add(this.conversationID),f(this,{event_type:"session_start"})),this._lastTrackedTokens=this.currentModel?.stats?.tokensUsed||0,f(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 f(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 f(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){h().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=xe(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(e)}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:xe(),content:JSON.stringify(t),customData:t})}clone(){let e=new I;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.knowledgeBase=this.knowledgeBase.clone(),e}};I.version=S.version,I.builtInActionsVersion="1.0.0",v.debug("\u{1F6A8}\u{1F6A8}\u{1F6A8} NEW SDK BUILD LOADED - Built-in Actions Version:",I.builtInActionsVersion);var W=I;var y=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=""){this.register();let s=n=>n.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;");return`<${this.tagName} ${Object.keys(e).map(n=>`${n}="${s(e[n]+"")}"`).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(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(e,t)=>this.getAttribute(t.toString())||"",set:(e,t,s)=>(this.getAttribute(t.toString())===s||(s?this.setAttribute(t.toString(),s):this.removeAttribute(t.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}};y.observedAttributes=[],y.tagName="",y._isRegistered=!1;var Le='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 Be='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 Pe='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 _=class extends y{constructor(){super(...arguments);this.html=()=>`
31
+ `,t=await this.instruct({...i,instruction:e});if(t=t.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),i.allowMultiple){let n=t.split(`
32
+ `).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of n)try{o.push(JSON.parse(s))}catch(a){console.error("Failed to parse line as JSON:",s,a.message)}return o}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)).then(t=>t.text())}};var P=class{constructor(i){this.messages=i}text(){return this.messages?.flatMap(i=>i.sections)?.filter(i=>i?.type=="text")?.map(i=>i?.text||"")?.filter(i=>!!i)?.join(`
33
+
34
+ `)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((i,e)=>i+(e.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(i=>i.sections||[])||[]}toolCalls(){return this.messages?.flatMap(i=>i.sections?.filter(e=>e.type=="tool_call")||[])||[]}toolResult(i){return this.messages?.map(e=>e.sections?.find(t=>t.type=="tool_result"&&t.toolCallInstanceID==i)).filter(e=>!!e)[0]||null}};var re=class{constructor(i){this.subagents=[];this.cachedSubagents={};this.ai=i}register(i){if(this.subagents.find(e=>e.id==i.id))throw new Error(`Sub-agent with ID ${i.id} already exists`);this.subagents.push(i),this.ai.knowledgeBase.registerSource("subagent:"+i.id,e=>[{type:"action",id:"ask:"+i.id,name:`Ask ${i.name||"subagent"}`,content:i.usageInstructions||`Use this tool to ask ${i.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(t,n)=>await this.runQuery(i,t.query)}])}remove(i){this.subagents=this.subagents.filter(e=>e.id!=i),this.ai.knowledgeBase.removeSource("subagent:"+i)}async runQuery(i,e){let t=i.apiKey||this.ai.apiKey,n=this.cachedSubagents[t];return n||(n=new N,await n.load(t,i.config),this.cachedSubagents[t]=n),n=n.clone(),n.knowledgeBase.allowGlobalConfigSources=!1,n.knowledgeBase.allowWindowSources=!1,i.clearExistingKnowledge&&n.knowledgeBase.reset(),i.knowledge&&n.knowledgeBase.registerSource(i.knowledge),i.onAgentLoaded&&await i.onAgentLoaded(n),(await n.sendMessage(e)).text()}};var M=new p("Main"),je=new Set,D=class D extends EventTarget{constructor(){super(...arguments);this.conversationID=_e();this.knowledgeBase=new se(this);this.subAgents=new re(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new ae(this);this.userID=Re();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:D.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(e,t){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{M.debug("Loading configuration...");let n=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!n.ok)throw new Error(`Failed to load configuration: ${n.status} ${n.statusText}`);try{this.config=await n.json(),M.debug("Config loaded successfully:",this.config),t&&(this.config={...this.config,...t}),this.config&&M.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){M.error("Failed to parse JSON response:",o);try{let s=await n.clone().text();M.error("Raw response that failed parsing:",s)}catch{M.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let n=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!n.ok)throw new Error(`Failed to load VAD model: ${n.status} ${n.statusText}`);this.vadModel=await n.blob()}catch(n){M.warn(`Failed to load VAD model, some features will be unavailable. ${n.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let n of this.config.knowledge||[])n.url&&n.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:n.id,searchToolName:n.mcpSearchToolName,baseURL:n.url}):n.url&&this.knowledgeBase.registerSourceFromURL(n.url);for(let n of this.config.knowledge||[])n.entries?.length&&this.knowledgeBase.registerSource(n.id,()=>n.entries||[]);if(this.config.mcpServers)for(let n of this.config.mcpServers)this.knowledgeBase.registerMCPSource(n);for(let n of this.config.subagents||[])this.subAgents.register(n);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(n){throw M.warn("Failed to load:",n),this.error=n,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:n}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:n}})),n}}setModel(e){let t=this.models.find(o=>o.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let n={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(n):t.config.providerID==="anthropic"?this.currentModel=new ne(n):this.currentModel=new ie(n),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=h().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=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let t=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:t}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,data:ee(`
35
+ # RAG search
36
+ Use the \`search\` tool proactively as much as possible to find missing information or tools.
37
+ Use the \`search\` tool when you are unsure about specific details or actions to take.
38
+ Use the \`search\` tool if you are unable to complete the user's request.
39
+ If you're about to say "I don't have access..." or "I can't..." use the \`search\` tool first.
40
+ `)}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,data:`# Knowledge Database${e.length==0?`
41
+
42
+ (no items found)`:""}`});for(let n of e)if(n.type=="info"||n.type=="tour"||n.type=="input-event"){let o=ee(n.content),s=!0;if(n.attachments?.length)for(let a of n.attachments)a.url&&(s&&(o+=`
43
+
44
+ \`\`\`yaml
45
+ attachments:
46
+ `,s=!1),o+=`- name: "${a.name||""}"
47
+ mimetype: "${a.mimeType||""}"
48
+ url: "${a.url}"
49
+ `);s||(o+="```\n"),this.currentModel.contextGroup.add({id:n.id,data:`## ${n.type}: ${n.name}
50
+ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="function"?n.disabled(this):n.disabled})}else if(n.type=="action"){let o={name:n._functionID,description:ee(n.content),params:Pe(n.parameters||[{name:"value",type:"string",description:"Input"}]),callback:s=>this.toolRunKBAction(n,s),canRemove:!n.isContext,kbItem:n};this.currentModel.registerTool(o)}else continue}processIncomingMessage(e,t){if(!t){let n=this.currentModel?.stats?.tokensUsed||0,o=e.reduce((s,a)=>s+(a.usage?.totalTokens||0),0);w(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}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:t,messages:e}})),this.onAIMessage?.(e,!!t)}async sendMessage(e,t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),je.has(this.conversationID)||(je.add(this.conversationID),w(this,{event_type:"session_start"})),w(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});let n=Date.now(),o=await this.currentModel.sendMessage(e),s=new P(o);(this._voiceTracker||M.debug.bind(M))(`LLM response took ${Date.now()-n}ms`);let l=this.currentModel.contextGroup.getAllAsString();l+=`
51
+
52
+ === TOOLS ===
53
+
54
+ `+this.currentModel.toolGroup.getAll().map(u=>"- "+u.data?.name).join(`
55
+ `),this._lastSystemMsg!=l&&(this._lastSystemMsg=l,this.submitAnalyticsEvent({type:"system-msg",txt:l}));for(let u of o)for(let c of u.sections||[])if(c.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:c.text||""});else if(c.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:c.text||""});else if(c.type=="tool_call"){let d=s.toolResult(c.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:c.toolKbID||"",actionName:c.toolKbName||"",value:c.toolParameters,result:d?.toolErrorResponse||d?.toolSuccessResponse,isError:!!d?.toolErrorResponse})}else c.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let n=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:t,ai:this}}));let o=await e.action(t,this),s=Date.now()-n;return w(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:s,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,result:o}})),o}catch(o){let s=Date.now()-n;throw w(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:s,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,error:o}})),o}}submitAnalyticsEvent(e){if(h().analytics===!1||this.config?.analytics===!1)return;let t=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(n=>{M.debug("Failed to submit analytics event:",n)});this.activeAnalyticsPromises.push(t),t.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(n=>n!==t)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=_e(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(e)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let t of e.messages)this.currentModel.messageGroup.add(t)}clone(){let e=new D;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.knowledgeBase=this.knowledgeBase.clone(),e}get messages(){return this.currentModel?.messageGroup.items||[]}};D.version=E.version,D.builtInActionsVersion="1.0.0",M.debug(`Loaded: version=${E.version} builtInActionsVersion=${D.builtInActionsVersion}`);var N=D;var x=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 n=document.createElement(this.tagName);for(let o in e)n.setAttribute(o,e[o]);return n.onBeforeCreate(),n.innerHTML=t,n}static add(e={},t=""){this.register();let n=o=>o.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;");return`<${this.tagName} ${Object.keys(e).map(o=>`${o}="${n(e[o]+"")}"`).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,n){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(e,t)=>this.getAttribute(t.toString())||"",set:(e,t,n)=>(this.getAttribute(t.toString())===n||(n?this.setAttribute(t.toString(),n):this.removeAttribute(t.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,n)=>(this._state[t]=n,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}};x.observedAttributes=[],x.tagName="",x._isRegistered=!1;var Oe='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 Ye='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 Ue='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 K=class extends x{constructor(){super(...arguments);this.html=()=>`
36
56
 
37
57
  <!-- Styling -->
38
58
  <style>
@@ -40,7 +60,7 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
40
60
  :host {
41
61
  width: 100%;
42
62
  height: 44px;
43
- background-color: rgba(0, 0, 0, 0.1);
63
+ background-color: var(--intelliweave-interaction-bg, rgba(0, 0, 0, 0.1));
44
64
  border-top: 1px solid rgba(255, 255, 255, 0.1);
45
65
  display: flex;
46
66
  align-items: center;
@@ -49,6 +69,11 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
49
69
  color: var(--intelliweave-text-color, white);
50
70
  }
51
71
 
72
+ /** Remove top border in fullscreen UI */
73
+ :host([layout="fullscreen"]) {
74
+ border-top: none;
75
+ }
76
+
52
77
  :host input {
53
78
  flex: 1 1 1px;
54
79
  border: none;
@@ -58,6 +83,10 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
58
83
  color: var(--intelliweave-text-color, white);
59
84
  padding: 10px 16px 10px 10px;
60
85
  }
86
+ :host input::placeholder {
87
+ color: var(--intelliweave-text-color, white);
88
+ opacity: 0.7;
89
+ }
61
90
 
62
91
  :host #llm-button {
63
92
  flex: 0 0 auto;
@@ -71,8 +100,39 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
71
100
  border: 1px solid rgba(255, 255, 255, 0.2);
72
101
  }
73
102
 
103
+ :host #send-button {
104
+ flex: 0 0 auto;
105
+ width: 34px;
106
+ height: 34px;
107
+ margin: 0 4px 0 0;
108
+ border-radius: 8px;
109
+ background-color: var(--intelliweave-persona-bg, var(--intelliweave-background, #4a6572));
110
+ border: none;
111
+ cursor: pointer;
112
+ display: flex;
113
+ align-items: center;
114
+ justify-content: center;
115
+ transition: opacity 0.15s ease;
116
+ }
117
+ :host #send-button svg {
118
+ width: 18px;
119
+ height: 18px;
120
+ fill: var(--intelliweave-text-color, white);
121
+ }
122
+
123
+ /** Remove send button background in widget UI */
124
+ :host([layout="widget"]) #send-button {
125
+ background-color: transparent;
126
+ opacity: 0.5;
127
+ }
128
+
129
+ /** Send button hover */
130
+ :host #send-button:hover {
131
+ opacity: 0.85;
132
+ }
133
+
74
134
  :host #loader {
75
- background-image: url('${Le}');
135
+ background-image: url('${Oe}');
76
136
  background-size: 64px 64px;
77
137
  background-position: center;
78
138
  background-repeat: no-repeat;
@@ -95,7 +155,7 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
95
155
  }
96
156
 
97
157
  :host #microphone-button {
98
- background-image: url('${Be}');
158
+ background-image: url('${Ye}');
99
159
  z-index: 2;
100
160
  margin-right: -10px;
101
161
  }
@@ -119,7 +179,7 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
119
179
  }
120
180
 
121
181
  :host #cancel-speech-button {
122
- background-image: url('${Pe}');
182
+ background-image: url('${Ue}');
123
183
  z-index: 2;
124
184
  }
125
185
 
@@ -140,10 +200,17 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
140
200
  <!-- LLM button -->
141
201
  <div id='llm-button'>LLM</div>
142
202
 
203
+ <!-- Send button -->
204
+ <button id='send-button' type='button' aria-label='Send message'>
205
+ <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
206
+ <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
207
+ </svg>
208
+ </button>
209
+
143
210
  <!-- Loader bar -->
144
211
  <div id='loader'></div>
145
212
 
146
- `;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",e=>this.onInputKeyPress(e),{capture:!0}),this.child("input-field").addEventListener("keydown",e=>e.stopPropagation(),{capture:!0}),this.child("llm-button").addEventListener("click",e=>this.onLLMButtonClick(e)),this.child("microphone-button").addEventListener("click",e=>this.onMicButtonClick(e)),this.child("cancel-speech-button").addEventListener("click",e=>this.onCancelSpeechButtonClick(e))}connectAI(e){this.ai=e,this.ai.audio?.speechRecognition.addEventListener("speech",t=>this.onSpeechEvent(t)),this.ai.audio?.speechRecognition.addEventListener("start",t=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",t=>this.onUpdate()),this.onUpdate()}onUpdate(){this.attr.textColor&&document.documentElement.style.setProperty("--intelliweave-text-color",this.attr.textColor),this.child("input-field").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("llm-button").style.display=this.attr.loading||!this.attr.llmButtonVisible||this.state.micActiv?"none":"",this.child("llm-button").innerText=this.attr.llmName||"LLM",this.child("loader").style.display=this.attr.loading?"block":"",this.child("microphone-button").style.display=!this.ai?.audio?.speechRecognition?.isSupported||this.attr.loading&&!this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("cancel-speech-button").style.display="none",this.ai?.audio?.speechRecognition.isRunning&&this.ai?.audio?.speechOutput.isSpeaking&&(this.child("microphone-button").style.display="none",this.child("cancel-speech-button").style.display=""),!this.attr.loading&&this._wasLoading&&this.child("input-field").focus(),this._wasLoading=this.attr.loading,this.child("microphone-button-bg").classList.toggle("active",!!this.ai?.audio?.speechRecognition.isRunning);let e=this.ai?.audio?.speechRecognition.isRunning&&!this.attr.loading;e&&!this.micStateAnimationTimer?this.micStateAnimationTimer=setInterval(()=>this.onMicAnimation(),1e3/60):!e&&this.micStateAnimationTimer&&(this.voiceAnimationPieces.forEach(t=>t.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(e){if(e.stopPropagation(),e.key!="Enter")return;let t=this.child("input-field"),s=t.value?.trim();t.value="",s&&this.dispatchEvent(new CustomEvent("input-message",{detail:s}))}onLLMButtonClick(e){e.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onMicButtonClick(e){e.preventDefault(),this.ai.audio?.speechRecognition.isRunning?this.ai.audio?.speechRecognition.stop():this.ai.audio?.speechRecognition.start()}onMicAnimation(){if(!this.attr.loading){if(this._micAnimFrameCounter++,this._micAnimFrameCounter%5==0){let e="rgba(140, 170, 200, 0.5)";this.ai?.audio?.speechRecognition.voiceDetection?.isModelLoaded||(e="rgba(255, 0, 0, 0.5)"),this.ai?.audio?.speechRecognition.voiceDetection?.isTranscribing&&(e="rgba(96, 66, 245, 0.9)"),this.ai?.audio?.speechRecognition.wordsCurrentlyBeingSpoken&&(e="rgba(0, 128, 255, 0.9)"),this.ai?.audio?.speechRecognition.voiceDetection?.isVoicePossiblyEnding&&(e="rgba(0, 128, 255, 0.5)"),this.ai?.isProcessing&&(e="rgba(255, 255, 0, 0.5)"),this.ai?.audio?.speechOutput.isSpeaking&&(e="rgba(0, 255, 0, 0.5)");let t=this.ai?.audio?.speechRecognition.volumeLevel||0,s=30,n=6,o=Math.round(t*(s-n)+n),r=document.createElement("div");r.posX=50,r.style.cssText=`position: absolute; top: calc(50% - ${o}px/2); left: 0px; width: 6px; height: ${o}px; background-color: ${e}; border-radius: 3px; pointer-events: none; `,this.root?.appendChild(r),this.voiceAnimationPieces.push(r)}for(let e=0;e<this.voiceAnimationPieces.length;e++){let t=this.voiceAnimationPieces[e];t.posX+=2,t.style.transform=`translate(${t.posX}px, 0px)`,!(t.posX<400)&&(this.voiceAnimationPieces.splice(e--,1),t.remove())}}}onSpeechEvent(e){this.attr.loading||e.detail.isFinal&&this.dispatchEvent(new CustomEvent("input-message",{detail:e.detail.transcript}))}onCancelSpeechButtonClick(e){this.ai.audio?.speechOutput.interrupt(),this.onUpdate()}};_.observedAttributes=["loading","llmName","llmButtonVisible","textColor"];var Ae='data:image/svg+xml,<svg id="eLjt8NmVnoY1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 300 300" shape-rendering="geometricPrecision" text-rendering="geometricPrecision" project-id="defaf4a7213e40159eb368f9622a2af1" export-id="e0405e7e1d4a45c0a08fbbedb06a02a8" cached="false"><defs><radialGradient id="eLjt8NmVnoY6-fill" cx="0" cy="0" r="1" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-58.520001 292.985 -172.197 -34.394001 203.907 57.158)"><stop id="eLjt8NmVnoY6-fill-0" offset="0%" stop-color="%232b3d43"/><stop id="eLjt8NmVnoY6-fill-1" offset="33%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-2" offset="58%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-3" offset="100%" stop-color="%237ebf96"/></radialGradient><radialGradient id="eLjt8NmVnoY7-fill" cx="0" cy="0" r="1.112049" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(182.129 -94.016999 94.016999 182.129 43.4553 184.626)"><stop id="eLjt8NmVnoY7-fill-0" offset="0%" stop-color="%233f2d2d"/><stop id="eLjt8NmVnoY7-fill-1" offset="28%" stop-color="%23c83b35"/><stop id="eLjt8NmVnoY7-fill-2" offset="81%" stop-color="%23f69153"/><stop id="eLjt8NmVnoY7-fill-3" offset="100%" stop-color="%23ffe388"/></radialGradient><radialGradient id="eLjt8NmVnoY9-fill" cx="0" cy="0" r="593.59" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-0.196117 0.98058 -0.578542 -0.115709 406.499077 117.274778)"><stop id="eLjt8NmVnoY9-fill-0" offset="0%" stop-color="%23252d3a"/><stop id="eLjt8NmVnoY9-fill-1" offset="60%" stop-color="%23c50"/><stop id="eLjt8NmVnoY9-fill-2" offset="100%" stop-color="%23fddc85"/></radialGradient><radialGradient id="eLjt8NmVnoY10-fill" cx="0" cy="0" r="454.77" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="translate(87.33 340.7)"><stop id="eLjt8NmVnoY10-fill-0" offset="0%" stop-color="%23002936"/><stop id="eLjt8NmVnoY10-fill-1" offset="44%" stop-color="%23007aa1"/><stop id="eLjt8NmVnoY10-fill-2" offset="67%" stop-color="%2326ab7f"/><stop id="eLjt8NmVnoY10-fill-3" offset="100%" stop-color="%2395e0c8"/></radialGradient></defs><g transform="matrix(.339855 0 0 0.339855 65.056641 64.89012)"><path d="M337.93,111.85c17.31-4.12,30.6-2.15,38.55,5.96c12.9,13.16,10.13,41.58-7.64,77.95-34.66,70.98-116.01,153.37-181.35,183.6-4.15,1.92-8.16,3.6-12.02,5.03l.05.18C83.95,418.36,13.7,365.53,1.49,278.27C15.34,403.24,121.28,500.43,249.94,500.43c138.07,0,250-111.93,250-250c0-9.8-.58-19.46-1.68-28.96-12-82.27-75.81-133.5-160.33-109.62Z" fill="url(%23eLjt8NmVnoY9-fill)"/><path d="M249.94,0.43c-138.07,0-250,111.93-250,250c0,9.41.54,18.69,1.55,27.84C13.7,365.54,83.95,418.36,175.52,384.58l-.05-.18c-11.22,4.17-21.17,6.24-29.61,6.24-9.59,0-17.18-2.67-22.44-8.03-12.9-13.19-10.13-41.61,7.64-77.98c18.26-37.41,49.51-77.98,84.51-112.41c31.45-32.33,62.2-54.66,91.14-68.47.16-.08.34-.16.49-.23c1.74-.85,3.47-1.68,5.18-2.49c9.22-4.27,17.77-7.33,25.54-9.17c84.52-23.88,148.33,27.35,160.33,109.62C483.91,97.04,378.22,0.43,249.94,0.43Z" fill="url(%23eLjt8NmVnoY10-fill)"/><path d="M337.93,111.85c-7.77,1.84-16.32,4.9-25.54,9.17-1.71.8-3.45,1.63-5.18,2.49-.16.08-.34.16-.49.23-28.94,13.81-59.69,36.14-91.14,68.47-35,34.43-66.24,75-84.51,112.41-17.77,36.37-20.54,64.79-7.64,77.98c5.26,5.36,12.85,8.03,22.44,8.03c8.45,0,18.39-2.07,29.61-6.24c3.86-1.42,7.88-3.11,12.02-5.03c65.34-30.23,146.68-112.62,181.35-183.6c17.77-36.37,20.54-64.79,7.64-77.95-7.95-8.11-21.24-10.08-38.55-5.96h-.01Z" fill="%23252d3a"/></g></svg>%0D%0A';var D=class extends y{constructor(){super(...arguments);this.html=()=>`
213
+ `;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",e=>this.onInputKeyPress(e),{capture:!0}),this.child("input-field").addEventListener("keydown",e=>e.stopPropagation(),{capture:!0}),this.child("llm-button").addEventListener("click",e=>this.onLLMButtonClick(e)),this.child("send-button").addEventListener("click",e=>this.onSendButtonClick(e)),this.child("microphone-button").addEventListener("click",e=>this.onMicButtonClick(e)),this.child("cancel-speech-button").addEventListener("click",e=>this.onCancelSpeechButtonClick(e))}connectAI(e){this.ai=e,this.ai.audio?.speechRecognition.addEventListener("speech",t=>this.onSpeechEvent(t)),this.ai.audio?.speechRecognition.addEventListener("start",t=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",t=>this.onUpdate()),this.onUpdate()}onUpdate(){this.attr.textColor&&document.documentElement.style.setProperty("--intelliweave-text-color",this.attr.textColor),this.child("input-field").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("llm-button").style.display=this.attr.loading||!this.attr.llmButtonVisible||this.state.micActiv?"none":"",this.child("llm-button").innerText=this.attr.llmName||"LLM",this.child("send-button").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("loader").style.display=this.attr.loading?"block":"",this.child("microphone-button").style.display=!this.ai?.audio?.speechRecognition?.isSupported||this.attr.loading&&!this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("cancel-speech-button").style.display="none",this.ai?.audio?.speechRecognition.isRunning&&this.ai?.audio?.speechOutput.isSpeaking&&(this.child("microphone-button").style.display="none",this.child("cancel-speech-button").style.display=""),!this.attr.loading&&this._wasLoading&&this.child("input-field").focus(),this._wasLoading=this.attr.loading,this.child("microphone-button-bg").classList.toggle("active",!!this.ai?.audio?.speechRecognition.isRunning);let e=this.ai?.audio?.speechRecognition.isRunning&&!this.attr.loading;e&&!this.micStateAnimationTimer?this.micStateAnimationTimer=setInterval(()=>this.onMicAnimation(),1e3/60):!e&&this.micStateAnimationTimer&&(this.voiceAnimationPieces.forEach(t=>t.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(e){if(e.stopPropagation(),e.key!="Enter")return;let t=this.child("input-field"),n=t.value?.trim();t.value="",n&&this.dispatchEvent(new CustomEvent("input-message",{detail:n}))}onLLMButtonClick(e){e.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onSendButtonClick(e){e.preventDefault();let t=this.child("input-field"),n=t.value?.trim();t.value="",n&&this.dispatchEvent(new CustomEvent("input-message",{detail:n}))}onMicButtonClick(e){e.preventDefault(),this.ai.audio?.speechRecognition.isRunning?this.ai.audio?.speechRecognition.stop():this.ai.audio?.speechRecognition.start()}onMicAnimation(){if(!this.attr.loading){if(this._micAnimFrameCounter++,this._micAnimFrameCounter%5==0){let e="rgba(140, 170, 200, 0.5)";this.ai?.audio?.speechRecognition.voiceDetection?.isModelLoaded||(e="rgba(255, 0, 0, 0.5)"),this.ai?.audio?.speechRecognition.voiceDetection?.isTranscribing&&(e="rgba(96, 66, 245, 0.9)"),this.ai?.audio?.speechRecognition.wordsCurrentlyBeingSpoken&&(e="rgba(0, 128, 255, 0.9)"),this.ai?.audio?.speechRecognition.voiceDetection?.isVoicePossiblyEnding&&(e="rgba(0, 128, 255, 0.5)"),this.ai?.isProcessing&&(e="rgba(255, 255, 0, 0.5)"),this.ai?.audio?.speechOutput.isSpeaking&&(e="rgba(0, 255, 0, 0.5)");let t=this.ai?.audio?.speechRecognition.volumeLevel||0,n=30,o=6,s=Math.round(t*(n-o)+o),a=document.createElement("div");a.posX=50,a.style.cssText=`position: absolute; top: calc(50% - ${s}px/2); left: 0px; width: 6px; height: ${s}px; background-color: ${e}; border-radius: 3px; pointer-events: none; `,this.root?.appendChild(a),this.voiceAnimationPieces.push(a)}for(let e=0;e<this.voiceAnimationPieces.length;e++){let t=this.voiceAnimationPieces[e];t.posX+=2,t.style.transform=`translate(${t.posX}px, 0px)`,!(t.posX<400)&&(this.voiceAnimationPieces.splice(e--,1),t.remove())}}}onSpeechEvent(e){this.attr.loading||e.detail.isFinal&&this.dispatchEvent(new CustomEvent("input-message",{detail:e.detail.transcript}))}onCancelSpeechButtonClick(e){this.ai.audio?.speechOutput.interrupt(),this.onUpdate()}};K.observedAttributes=["loading","llmName","llmButtonVisible","textColor","layout"];var Ke='data:image/svg+xml,<svg id="eLjt8NmVnoY1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 300 300" shape-rendering="geometricPrecision" text-rendering="geometricPrecision" project-id="defaf4a7213e40159eb368f9622a2af1" export-id="e0405e7e1d4a45c0a08fbbedb06a02a8" cached="false"><defs><radialGradient id="eLjt8NmVnoY6-fill" cx="0" cy="0" r="1" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-58.520001 292.985 -172.197 -34.394001 203.907 57.158)"><stop id="eLjt8NmVnoY6-fill-0" offset="0%" stop-color="%232b3d43"/><stop id="eLjt8NmVnoY6-fill-1" offset="33%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-2" offset="58%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-3" offset="100%" stop-color="%237ebf96"/></radialGradient><radialGradient id="eLjt8NmVnoY7-fill" cx="0" cy="0" r="1.112049" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(182.129 -94.016999 94.016999 182.129 43.4553 184.626)"><stop id="eLjt8NmVnoY7-fill-0" offset="0%" stop-color="%233f2d2d"/><stop id="eLjt8NmVnoY7-fill-1" offset="28%" stop-color="%23c83b35"/><stop id="eLjt8NmVnoY7-fill-2" offset="81%" stop-color="%23f69153"/><stop id="eLjt8NmVnoY7-fill-3" offset="100%" stop-color="%23ffe388"/></radialGradient><radialGradient id="eLjt8NmVnoY9-fill" cx="0" cy="0" r="593.59" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-0.196117 0.98058 -0.578542 -0.115709 406.499077 117.274778)"><stop id="eLjt8NmVnoY9-fill-0" offset="0%" stop-color="%23252d3a"/><stop id="eLjt8NmVnoY9-fill-1" offset="60%" stop-color="%23c50"/><stop id="eLjt8NmVnoY9-fill-2" offset="100%" stop-color="%23fddc85"/></radialGradient><radialGradient id="eLjt8NmVnoY10-fill" cx="0" cy="0" r="454.77" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="translate(87.33 340.7)"><stop id="eLjt8NmVnoY10-fill-0" offset="0%" stop-color="%23002936"/><stop id="eLjt8NmVnoY10-fill-1" offset="44%" stop-color="%23007aa1"/><stop id="eLjt8NmVnoY10-fill-2" offset="67%" stop-color="%2326ab7f"/><stop id="eLjt8NmVnoY10-fill-3" offset="100%" stop-color="%2395e0c8"/></radialGradient></defs><g transform="matrix(.339855 0 0 0.339855 65.056641 64.89012)"><path d="M337.93,111.85c17.31-4.12,30.6-2.15,38.55,5.96c12.9,13.16,10.13,41.58-7.64,77.95-34.66,70.98-116.01,153.37-181.35,183.6-4.15,1.92-8.16,3.6-12.02,5.03l.05.18C83.95,418.36,13.7,365.53,1.49,278.27C15.34,403.24,121.28,500.43,249.94,500.43c138.07,0,250-111.93,250-250c0-9.8-.58-19.46-1.68-28.96-12-82.27-75.81-133.5-160.33-109.62Z" fill="url(%23eLjt8NmVnoY9-fill)"/><path d="M249.94,0.43c-138.07,0-250,111.93-250,250c0,9.41.54,18.69,1.55,27.84C13.7,365.54,83.95,418.36,175.52,384.58l-.05-.18c-11.22,4.17-21.17,6.24-29.61,6.24-9.59,0-17.18-2.67-22.44-8.03-12.9-13.19-10.13-41.61,7.64-77.98c18.26-37.41,49.51-77.98,84.51-112.41c31.45-32.33,62.2-54.66,91.14-68.47.16-.08.34-.16.49-.23c1.74-.85,3.47-1.68,5.18-2.49c9.22-4.27,17.77-7.33,25.54-9.17c84.52-23.88,148.33,27.35,160.33,109.62C483.91,97.04,378.22,0.43,249.94,0.43Z" fill="url(%23eLjt8NmVnoY10-fill)"/><path d="M337.93,111.85c-7.77,1.84-16.32,4.9-25.54,9.17-1.71.8-3.45,1.63-5.18,2.49-.16.08-.34.16-.49.23-28.94,13.81-59.69,36.14-91.14,68.47-35,34.43-66.24,75-84.51,112.41-17.77,36.37-20.54,64.79-7.64,77.98c5.26,5.36,12.85,8.03,22.44,8.03c8.45,0,18.39-2.07,29.61-6.24c3.86-1.42,7.88-3.11,12.02-5.03c65.34-30.23,146.68-112.62,181.35-183.6c17.77-36.37,20.54-64.79,7.64-77.95-7.95-8.11-21.24-10.08-38.55-5.96h-.01Z" fill="%23252d3a"/></g></svg>%0D%0A';var F=class extends x{constructor(){super(...arguments);this.html=()=>`
147
214
 
148
215
  <!-- Styling -->
149
216
  <style>
@@ -196,7 +263,7 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
196
263
  <!-- Logo -->
197
264
  <img id='root' />
198
265
 
199
- `;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let t=this.attr.logo||Ae;this._lastLogoSrc!=t&&(this._lastLogoSrc=t,e.src=t);let s=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(s){let n=window.visualViewport?.offsetTop||0,o=window.visualViewport?.offsetLeft||0,r=s.getBoundingClientRect();if(!r)return;e.classList.add("focused-mode"),e.style.width="128px",e.style.height="128px",e.style.left=Math.round(r.x+r.width/2-128/2+o)+"px",e.style.top=Math.round(r.y+r.height/2-128/2+n)+"px"}else e.classList.remove("focused-mode"),e.style.width="",e.style.height="",e.style.left="",e.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};D.observedAttributes=["logo","focusID"];import mt from"rehype-external-links";import gt from"rehype-format";import ft from"rehype-stringify";import yt from"remark-parse";import bt from"remark-rehype";import{unified as vt}from"unified";var K=class extends y{constructor(){super(...arguments);this.html=()=>`
266
+ `;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let t=this.attr.logo||Ke;this._lastLogoSrc!=t&&(this._lastLogoSrc=t,e.src=t);let n=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(n){let o=window.visualViewport?.offsetTop||0,s=window.visualViewport?.offsetLeft||0,a=n.getBoundingClientRect();if(!a)return;e.classList.add("focused-mode"),e.style.width="128px",e.style.height="128px",e.style.left=Math.round(a.x+a.width/2-128/2+s)+"px",e.style.top=Math.round(a.y+a.height/2-128/2+o)+"px"}else e.classList.remove("focused-mode"),e.style.width="",e.style.height="",e.style.left="",e.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};F.observedAttributes=["logo","focusID"];import qe from"rehype-external-links";import et from"rehype-format";import tt from"rehype-stringify";import it from"remark-parse";import nt from"remark-rehype";import{unified as ot}from"unified";var H=class extends x{constructor(){super(...arguments);this.html=()=>`
200
267
 
201
268
  <!-- Styling -->
202
269
  <style>
@@ -279,15 +346,24 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
279
346
  <div id='llm-selector-list'></div>
280
347
  </div>
281
348
 
282
- `}onUpdate(){this.child("llm-selector-panel").className=this.attr.open?"open":"closed";let e=this.child("llm-selector-list");for(;e.lastChild;)e.lastChild.remove();for(let t of this.state.items||[]){let s=document.createElement("div");s.className="llm-selector-item"+(t.id==this.state.selectedID?" selected":""),s.innerHTML=`
349
+ `}onUpdate(){this.child("llm-selector-panel").className=this.attr.open?"open":"closed";let e=this.child("llm-selector-list");for(;e.lastChild;)e.lastChild.remove();for(let t of this.state.items||[]){let n=document.createElement("div");n.className="llm-selector-item"+(t.id==this.state.selectedID?" selected":""),n.innerHTML=`
283
350
  <div class='llm-selector-item-icon' style="background-image: url('${t.icon}'); "></div>
284
351
  <div class='llm-selector-item-name'>${t.name}</div>
285
352
  <div class='llm-selector-item-provider'>${t.provider}</div>
286
- `,s.addEventListener("click",n=>{this.dispatchEvent(new CustomEvent("select",{detail:t.id}))}),e.appendChild(s)}}};K.observedAttributes=["open"];var E=new u("ONNXModel"),G=class a{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,E.debug(`Model input parameters: ${i.inputNames.join(", ")}`),E.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!a.lib}static async load(i){if(!a.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(E.debug("Loading ONNX runtime"),this.onnx=await a.lib()),E.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new a(e)}makeTensor(i,e,t=0){let s=1;for(let o of e)s*=o;let n;if(i=="float32")n=new a.onnx.Tensor(new Float32Array(s),e);else if(i=="int8")n=new a.onnx.Tensor(new Int8Array(s),e);else if(i=="int16")n=new a.onnx.Tensor(new Int16Array(s),e);else if(i=="int32")n=new a.onnx.Tensor(new Int32Array(s),e);else if(i=="int64")n=new a.onnx.Tensor(new BigInt64Array(s),e);else if(i=="uint8")n=new a.onnx.Tensor(new Uint8Array(s),e);else if(i=="uint16")n=new a.onnx.Tensor(new Uint16Array(s),e);else if(i=="uint32")n=new a.onnx.Tensor(new Uint32Array(s),e);else if(i=="uint64")n=new a.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 E.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(){E.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var Ne="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBj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dPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var ct=new u("PCMPlayerNode"),R=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})}static async registerModule(e){await e.audioWorklet.addModule(Ne)}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){ct.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 te=new u("SpeechOutput"),_e=.5,dt=.8,ie=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 te.warn("No voice provider configured");let t=`speech-${ht++}`;await this.ai.audio.beginAccess(t);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(t)}}async _speakWithLock(e){let t=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:e}});if(this.dispatchEvent(t),e=t.detail.message,t.defaultPrevented||!e)return;this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=dt);let s=this.ai?._voiceTracker||te.timer(`${this.ai.config.voice.providerID} voice`);s(`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 n=new R(this.ai.audio.context,24e3,"int16");this.currentPlayer=n,n.connect(this.analyserNode),n.addEventListener("end",r=>{let d=r;s(`PCM stream ${d.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==n&&!d.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let o;if(this.ai.config.voice.providerID=="openai")o=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")o=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{te.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(s(`Received response ${o.status} ${o.statusText}`),!o.ok){te.warn(`Failed to generate voice sample: ${o.status} ${o.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),s("Playing PCM stream"),await n.play(o.body),s("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=_e);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=_e)}},ht=1;function se(a,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=a*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,a,!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 De="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoZSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGUpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWUsdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsZSl9fX1pbml0aWFsaXplQnVm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ucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var V=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})}static async registerModule(e){await e.audioWorklet.addModule(De)}onWorkletMessage(e){if(e.data.action=="data"){let t=null;if(this.format=="int16"&&(t=new Int16Array(e.data.buffer)),this.format=="int64"&&(t=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(t=new Float32Array(e.data.buffer)),!t)throw new Error(`Invalid format: ${this.format}`);this.onData(t),this.dispatchEvent(new CustomEvent("data",{detail:{data:t}}))}}onData(e){}};var Se=16e3,ne=256,L=8,F=new u("VoiceDetectionNode"),Y=class Y extends V{constructor(e){super(e,Se,"float32",ne*L);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(!Y.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return Se}get numberOfSamples(){return ne}get numberOfSampleChunks(){return L}get outputBufferSize(){return ne*L}get isModelLoaded(){return!!this.vad}async loadModel(){F.debug("Loading VAD model"),this.vad=await G.load(Y.vadModelURL),this.vad.ignoreIfBusy=!0,F.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],Se),this.vad.makeState("h","hn","float32",[2,L,64]),this.vad.makeState("c","cn","float32",[2,L,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new G.onnx.Tensor(e,[L,ne])});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(),F.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(),F.debug("Stopped speaking after timeout")),!n){let o=Date.now();o>this.nextVadReset&&(this.nextVadReset=o+5e3,this.vad.resetState())}}catch(t){F.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};Y.vadModelURL="";var B=Y;var Ke=new u("VoiceChunkOutputNode"),P=class extends B{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 oe=new u("OpenAITranscriptionNode"),ae=class extends P{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=oe.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=se(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){oe.error(`Failed to transcribe speech: ${o.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return oe.debug("Transcription complete, but no text was found");oe.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var re=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"),pt="wss://speech.intelliweave.ai/api/v1/transcribe",ce=class ce extends P{constructor(e,t){super(e);this.apiAddress=pt;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 re(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"})),ce.debugExportWav){let t=se(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}};ce.debugExportWav=!1;var le=ce;var Ge=new u("SpeechRecognition"),de=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(!G.lib||!this.ai?.vadModel||!C().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),B.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new ae(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new le(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=Ge.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),f(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;f(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}`),f(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){Ge.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;Ge.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 he=new u("AudioSystem"),M=class a{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 de(this.ai),this.speechOutput=new ie(this.ai)}static get isSupported(){return!(!G.lib||!C().AudioWorkletNode)}static async registerModules(i){await Promise.all([R.registerModule(i),V.registerModule(i)])}async beginAccess(i){he.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(he.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await a.registerModules(this.context))}endAccess(i){he.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(he.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var Ps=new u("Stream");var b=new u("Embed"),A=class extends y{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
353
+ `,n.addEventListener("click",o=>{this.dispatchEvent(new CustomEvent("select",{detail:t.id}))}),e.appendChild(n)}}};H.observedAttributes=["open"];var V=new p("ONNXModel"),C=class r{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,V.debug(`Model input parameters: ${i.inputNames.join(", ")}`),V.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!r.lib}static async load(i){if(!r.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(V.debug("Loading ONNX runtime"),this.onnx=await r.lib()),V.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new r(e)}makeTensor(i,e,t=0){let n=1;for(let s of e)n*=s;let o;if(i=="float32")o=new r.onnx.Tensor(new Float32Array(n),e);else if(i=="int8")o=new r.onnx.Tensor(new Int8Array(n),e);else if(i=="int16")o=new r.onnx.Tensor(new Int16Array(n),e);else if(i=="int32")o=new r.onnx.Tensor(new Int32Array(n),e);else if(i=="int64")o=new r.onnx.Tensor(new BigInt64Array(n),e);else if(i=="uint8")o=new r.onnx.Tensor(new Uint8Array(n),e);else if(i=="uint16")o=new r.onnx.Tensor(new Uint16Array(n),e);else if(i=="uint32")o=new r.onnx.Tensor(new Uint32Array(n),e);else if(i=="uint64")o=new r.onnx.Tensor(new BigUint64Array(n),e);else throw new Error(`Invalid type: ${i}`);return t!==0&&(i=="int64"||i=="uint64")?o.data.fill(BigInt(t)):t!==0&&o.data.fill(t),o}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,n=0){return this.registerConstant(i,this.makeTensor(e,t,n))}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,n,o=0){return this.registerState(i,e,this.makeTensor(t,n,o))}async run(i={}){if(this._runActive&&this.ignoreIfBusy)return V.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 n=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=n}return e}finally{this._runActive=!1}}resetState(){V.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var Fe="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3IoO3IhP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7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var At=new p("PCMPlayerNode"),B=class extends AudioWorkletNode{constructor(e,t,n){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(!n||n!="int16"&&n!="float32")throw new Error(`Invalid format: ${n}`);this.sampleRate=t,this.format=n,this.port.onmessage=o=>this.onWorkletMessage(o),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:n})}static async registerModule(e){await e.audioWorklet.addModule(Fe)}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:n,value:o}=await t.read();if(n||!o)break;this.feed(o)}}catch(t){At.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 I=new p("ElevenLabs");function Ee(r,i,e="pcm_24000"){let t=[],n=Date.now(),o=!1,s,a;return{stream:new ReadableStream({start:d=>{s=d,a=new WebSocket(`wss://api.elevenlabs.io/v1/text-to-speech/${i}/stream-input?inactivity_timeout=120&output_format=${e}`),a.addEventListener("open",()=>{I.debug(`[at ${Date.now()-n}ms] WebSocket connected`),a.send(JSON.stringify({text:" ","xi-api-key":r}));for(let g of t)a.send(JSON.stringify({text:g}));t.length=0}),a.addEventListener("close",()=>{I.debug(`[at ${Date.now()-n}ms] WebSocket closed`),s?.close(),o=!0}),a.addEventListener("message",g=>{let m=JSON.parse(g.data);if(m.final){a.close(),s?.close();return}if(I.debug(`[at ${Date.now()-n}ms] Message received: ${m.audio?.length||0} bytes of audio data`),!m.audio)return;let f=Uint8Array.from(atob(m.audio),b=>b.charCodeAt(0));s?.enqueue(f)})},cancel:()=>{I.debug(`[at ${Date.now()-n}ms] Stream cancelled`),a?.close(),o=!0}}),sendText:d=>{d&&(I.debug(`[at ${Date.now()-n}ms] Sending text: "${d}"`),a?.readyState===WebSocket.OPEN?a.send(JSON.stringify({text:d})):t.push(d))},endText:()=>{a?.readyState===WebSocket.OPEN?a.send(JSON.stringify({text:""})):t.push("")},get isClosed(){return o}}}function He(r,i="pcm_16000",e=16e3,t="vad"){let n=[],o=Date.now(),s=!1,a,l;return{stream:new ReadableStream({start:async m=>{a=m;let f=await fetch("https://api.elevenlabs.io/v1/single-use-token/realtime_scribe",{method:"POST",headers:{"xi-api-key":r}});if(!f.ok)throw new Error(`Failed to generate single-use token: ${f.status} ${f.statusText}`);let b=await f.json(),k=b.token;if(!k)throw new Error(`No token found in response: ${JSON.stringify(b)}`);l=new WebSocket(`wss://api.elevenlabs.io/v1/speech-to-text/realtime?token=${encodeURIComponent(k)}&audio_format=${i}&commit_strategy=${t}`),l.addEventListener("open",()=>{I.debug(`[at ${Date.now()-o}ms] WebSocket connected`);for(let $ of n)l.send($);n.length=0}),l.addEventListener("close",()=>{I.debug(`[at ${Date.now()-o}ms] WebSocket closed`),a?.close(),s=!0}),l.addEventListener("message",$=>{let T=JSON.parse($.data);T.message_type=="committed_transcript"?(I.debug(`[at ${Date.now()-o}ms] Committed transcript received: "${T.text}"`),a?.enqueue(T.text)):T.error&&(I.warn(`[at ${Date.now()-o}ms] Error received: ${T.error}`),a?.error(new Error(T.error)),l?.close(),s=!0)})},cancel:()=>{I.debug(`[at ${Date.now()-o}ms] Stream cancelled`),l?.close(),s=!0}}),sendAudio:m=>{let f=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:btoa(String.fromCharCode(...new Uint8Array(m))),commit:!1,sample_rate:e});I.debug(`[at ${Date.now()-o}ms] Sending audio: ${m.byteLength} bytes`),l?.readyState===WebSocket.OPEN?l.send(f):n.push(f)},commit:()=>{let m=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:e});l?.readyState===WebSocket.OPEN?l.send(m):n.push(m)},close:()=>{I.debug("Closing connection"),l?.close(),s=!0,setTimeout(()=>{a?.close()},1e3)},get isClosed(){return s}}}var le=new p("SpeechOutput"),Je=.5,Et=.8,ce=class extends EventTarget{constructor(e){super();this.autoSpeak=!0;this.preemptiveConnection=!0;this.processedMessages=new Set;this.maxVolumeHeard=0;this._queuedText=[];this._queueActive=!1;this.ai=e,this.ai.addEventListener("output",t=>this.onOutputFromAI(t)),this.ai.audio?.speechRecognition.addEventListener("speechstart",t=>this.interrupt())}onOutputFromAI(e){let t=e.detail.messages,n=e.detail.isPartial;if(!(!this.ai?.audio?.speechRecognition.isRunning||!this.autoSpeak)){for(let o of t)if(!o.streamingInProgress&&!(!o.id||this.processedMessages.has(o.id))){this.processedMessages.add(o.id);for(let s of o.sections||[])s.type=="text"&&s.text&&this.speak(s.text)}n||this.processedMessages.clear()}}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let n of this.analyserBuffer)e+=n*n;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 le.warn("No voice provider configured");this.ai._voiceTracker?.(`Added text to queue: ${e}`),this._queuedText.push(e),this._runQueue()}async _runQueue(){if(this._queueActive)return;let e=this._queuedText.shift();if(!e)return;this._queueActive=!0;let t=`speech-${Nt++}`;try{await this.ai.audio.beginAccess(t),await this._speakWithLock(e)}finally{this._queueActive=!1,this.ai.audio.endAccess(t)}this._queuedText.length?await this._runQueue():this.onSpeechEnd()}_getElevenLabsConnection(){let e=this._elevenLabsPrecachedConnection;return(!e||e.isClosed)&&(e=Ee(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),this.preemptiveConnection&&(this._elevenLabsPrecachedConnection=Ee(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),e}async _speakWithLock(e){let t=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:e}});if(this.dispatchEvent(t),e=t.detail.message,t.defaultPrevented||!e)return;this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Et);let n=this.ai?._voiceTracker||le.timer(`${this.ai.config.voice.providerID} voice`);n(`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 o=new B(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",l=>{let u=l;n(`PCM stream ${u.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!u.detail.interrupted&&(this.currentPlayer=void 0)});let s=Date.now(),a=null;if(this.ai.config.voice.providerID=="openai"){let l=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"})});if(!l.ok){le.warn(`Failed to generate voice sample: ${l.status} ${l.statusText}`);return}a=l.body}else if(this.ai.config.voice.providerID=="elevenlabs"){let l=this._getElevenLabsConnection();l.sendText(e),l.endText(),a=l.stream}else{le.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}n(`Received response in ${Date.now()-s}ms`),this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),n("Playing PCM stream"),await o.play(a),n("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(this._queuedText=[],!this.currentPlayerVolume)return;this.ai._voiceTracker?.("Interrupted");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=Je);let n=400;e.gain.linearRampToValueAtTime(0,n/1e3),await new Promise(o=>setTimeout(o,n+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=Je)}},Nt=1;function de(r,i){let e=i.reduce((l,u)=>l+u.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 n=1,o=32,s=n*o/8,a=r*s;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,n,!0),t.setUint32(24,r,!0),t.setUint32(28,a,!0),t.setUint16(32,s,!0),t.setUint16(34,o,!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 Qe="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaX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n,o){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=n;let s=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!s.includes(n))throw new Error(`Invalid format ${n}, must be one of: ${s.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:n,bufferSize:o})}static async registerModule(e){await e.audioWorklet.addModule(Qe)}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 Ne=16e3,ue=256,_=8,J=new p("VoiceDetectionNode"),Q=class Q extends z{constructor(e){super(e,Ne,"float32",ue*_);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(!Q.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 Ne}get numberOfSamples(){return ue}get numberOfSampleChunks(){return _}get outputBufferSize(){return ue*_}get isModelLoaded(){return!!this.vad}async loadModel(){J.debug("Loading VAD model"),this.vad=await C.load(Q.vadModelURL),this.vad.ignoreIfBusy=!0,J.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],Ne),this.vad.makeState("h","hn","float32",[2,_,64]),this.vad.makeState("c","cn","float32",[2,_,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new C.onnx.Tensor(e,[_,ue])});if(!t)return;this.currentProbability=0;for(let s=0;s<t.output.data.length;s++)t.output.data[s]>this.currentProbability&&(this.currentProbability=t.output.data[s]);let n=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>n;if(!o&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=o,o&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),J.debug("Started speaking")):o?this.lastVoiceActiveDate=Date.now():!o&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!o&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),J.debug("Stopped speaking after timeout")),!o){let s=Date.now();s>this.nextVadReset&&(this.nextVadReset=s+5e3,this.vad.resetState())}}catch(t){J.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};Q.vadModelURL="";var j=Q;var $e=new p("VoiceChunkOutputNode"),W=class extends j{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){$e.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((n,o)=>n+o.length,0);$e.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 pe=new p("OpenAITranscriptionNode"),he=class extends W{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=pe.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let n=de(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let s=new FormData;s.append("file",n),s.append("model","whisper-1"),s.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);t("Response received"),o=await a.text(),t("Content received: "+o),this.lastRequestAbortController=void 0}catch(s){pe.error(`Failed to transcribe speech: ${s.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return pe.debug("Transcription complete, but no text was found");pe.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(e){}};var me=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 S=new p("IntelliWeaveTranscriptionNode"),Gt="wss://speech.intelliweave.ai/api/v1/transcribe",fe=class fe extends W{constructor(e,t){super(e);this.apiAddress=Gt;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(S.debug("Opening WebSocket connection"),this.ws=new me(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=()=>{S.debug("WebSocket connection opened")},this.ws.addEventListener("message",n=>{let o=JSON.parse(n.data);if(o.error)return S.warn("Error: "+o.error);if(o.type!="transcription")return S.warn("Invalid response type",o);if(o.streaming&&!o.final)return S.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return S.warn(`Empty transcription (${o.processingTime}ms)`);S.debug(`Transcription: ${o.text} (${o.processingTime}ms)`),this.onVoiceTranscription(o.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",n=>S.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{S.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),fe.debugExportWav){let t=de(this.sampleRate,e),n=document.createElement("a");n.href=URL.createObjectURL(t),n.download="recording.wav",n.click()}}onVoiceTranscription(e){}onSocketClose(){S.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};fe.debugExportWav=!1;var ge=fe;var O=new p("ElevenLabsTranscriptionNode"),ye=class extends W{constructor(e,t){super(e);this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0;let t=new Int16Array(e.length);for(let o=0;o<e.length;o++)t[o]=e[o]*32767;!this.connection||this.connection.isClosed?(this.connection?.close(),this.connection=void 0,O.debug(`Opening connection. sampleRate: ${this.sampleRate} format=${this.format}`),this.connection=He(this.apiKey,"pcm_"+this.sampleRate,this.sampleRate,"manual"),this.startReading(this.connection),this.connection.sendAudio(t.buffer)):this.connection.sendAudio(t.buffer);let n=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{O.debug("Shutting down WebSocket connection"),this.connection?.close(),this.connection=void 0},n)}async startReading(e){let t=e.stream.getReader();try{for(;;){let{value:n,done:o}=await t.read();if(o){O.debug("Stream closed");break}if(!n?.trim()){O.warn("Empty transcription received");continue}this.isTranscribing=!1,O.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}}catch(n){O.error(`Failed to read transcription stream: ${n.message}`),this.connection==e&&(this.connection=void 0);return}}async onVoiceEnd(e){this.connection?.commit()}onVoiceTranscription(e){}};var We=new p("SpeechRecognition"),be=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e}get isSupported(){if(!C.lib||!this.ai?.vadModel||!A().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey)){if(!(this.ai?.config?.transcription?.providerID=="elevenlabs"&&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),j.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new he(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):this.ai?.config?.transcription?.providerID=="elevenlabs"?(this.voiceDetection=new ye(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new ge(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=We.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),w(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 n=this.recordingStartTime?Date.now()-this.recordingStartTime:0;w(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:n}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),w(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){We.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 n of this.analyserBuffer)e+=n*n;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;We.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 we=new p("AudioSystem"),G=class r{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 be(this.ai),this.speechOutput=new ce(this.ai)}static get isSupported(){return!(!C.lib||!A().AudioWorkletNode)}static async registerModules(i){await Promise.all([B.registerModule(i),z.registerModule(i)])}async beginAccess(i){we.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(we.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await r.registerModules(this.context))}endAccess(i){we.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(we.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var v=new p("Embed"),Y=class extends x{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
287
354
 
288
355
  <!-- Styling -->
289
356
  <style>
290
357
 
358
+ :host {
359
+ display: block;
360
+ }
361
+ :host([layout="fullscreen"]),
362
+ :host([positioningmode="container"]) {
363
+ width: 100%;
364
+ height: 100%;
365
+ }
366
+
291
367
  #root {
292
368
  position: fixed;
293
369
  width: 64px;
@@ -322,6 +398,24 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
322
398
  max-height: calc(max(50vh, 100vh - 320px));
323
399
  overflow: visible;
324
400
  }
401
+ #root.layout-fullscreen {
402
+ position: absolute;
403
+ inset: 0;
404
+ width: 100%;
405
+ height: 100%;
406
+ max-width: none;
407
+ max-height: none;
408
+ border-radius: 0;
409
+ box-shadow: none;
410
+ background: transparent !important;
411
+ overflow: hidden;
412
+ box-sizing: border-box;
413
+ padding-bottom: calc(12px + env(safe-area-inset-bottom));
414
+ }
415
+ #root.layout-fullscreen #web-weaver-logo,
416
+ #root.layout-fullscreen #pulseanim {
417
+ display: none;
418
+ }
325
419
 
326
420
  #root #web-weaver-logo {
327
421
  position: absolute;
@@ -332,6 +426,58 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
332
426
  border-radius:50%;
333
427
  z-index:999;
334
428
  }
429
+ #root #fullscreen-header {
430
+ display: none;
431
+ width: 100%;
432
+ max-width: 860px;
433
+ padding: 12px 24px;
434
+ box-sizing: border-box;
435
+ position: absolute;
436
+ top: 0;
437
+ left: 50%;
438
+ transform: translateX(-50%);
439
+ z-index: 10;
440
+ transition: opacity 0.2s ease;
441
+ }
442
+ #root.layout-fullscreen #fullscreen-header {
443
+ display: flex;
444
+ justify-content: space-between;
445
+ align-items: center;
446
+ }
447
+ #root.layout-fullscreen #fullscreen-persona {
448
+ display: flex;
449
+ align-items: center;
450
+ gap: 10px;
451
+ font-size: 16px;
452
+ font-weight: 600;
453
+ color: #333;
454
+ }
455
+ #root.layout-fullscreen #fullscreen-logo {
456
+ width: 32px;
457
+ height: 32px;
458
+ border-radius: 8px;
459
+ object-fit: contain;
460
+ }
461
+ #root.layout-fullscreen #fullscreen-branding {
462
+ display: none;
463
+ align-items: center;
464
+ gap: 6px;
465
+ font-size: 11px;
466
+ color: #666;
467
+ text-transform: uppercase;
468
+ letter-spacing: 0.5px;
469
+ }
470
+ #root.layout-fullscreen #fullscreen-branding.visible {
471
+ display: flex;
472
+ }
473
+ #root.layout-fullscreen #fullscreen-branding .brand-label {
474
+ opacity: 0.6;
475
+ font-weight: 400;
476
+ }
477
+ #root.layout-fullscreen #fullscreen-branding .brand-name {
478
+ font-weight: 600;
479
+ color: #333;
480
+ }
335
481
 
336
482
  #root.open #web-weaver-logo {
337
483
  background-color: rgba(0,0,0,0);
@@ -353,6 +499,16 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
353
499
  border-bottom-left-radius: 16px;
354
500
  position: relative;
355
501
  }
502
+ #root.layout-fullscreen #poweredby {
503
+ background-color: transparent;
504
+ color: #111111;
505
+ border: none;
506
+ border-top: none;
507
+ width: 100%;
508
+ max-width: 720px;
509
+ margin: 0 auto;
510
+ border-radius: 0;
511
+ }
356
512
 
357
513
  #root.open #poweredby {
358
514
  display: flex; /* Show when open */
@@ -383,6 +539,15 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
383
539
  box-sizing: border-box;
384
540
  line-height: 1.3;
385
541
  }
542
+ #root.layout-fullscreen #web-weaver-embed-inner {
543
+ padding: 56px 24px 16px 24px;
544
+ display: flex;
545
+ flex-direction: column;
546
+ gap: 12px;
547
+ width: 100%;
548
+ max-width: 860px;
549
+ margin: 0 auto;
550
+ }
386
551
  #web-weaver-embed-inner::-webkit-scrollbar {
387
552
  width: 0;
388
553
  background: transparent;
@@ -393,6 +558,14 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
393
558
  text-align: center;
394
559
  font-size: 14px;
395
560
  }
561
+ #root.layout-fullscreen #web-weaver-embed-inner .introduction-message {
562
+ padding: 8px 12px;
563
+ border-radius: 14px;
564
+ background: var(--intelliweave-persona-bg-muted, rgba(32, 38, 44, 0.8));
565
+ text-align: center;
566
+ width: 100%;
567
+ box-sizing: border-box;
568
+ }
396
569
 
397
570
  #web-weaver-embed-inner .suggestion-button {
398
571
  margin: 10px 20px;
@@ -409,6 +582,17 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
409
582
  font-size: 12px;
410
583
  opacity: 0.5;
411
584
  }
585
+ #root.layout-fullscreen #web-weaver-embed-inner .input {
586
+ align-self: flex-end;
587
+ max-width: min(80%, 720px);
588
+ margin: 0 0 0 auto;
589
+ padding: 6px 12px;
590
+ border-radius: 14px;
591
+ background: var(--intelliweave-persona-bg, rgba(32, 38, 44, 0.92));
592
+ opacity: 0.9;
593
+ font-size: 14px;
594
+ color: var(--intelliweave-user-bubble-text, inherit);
595
+ }
412
596
 
413
597
  #web-weaver-embed-inner .tool {
414
598
  margin: 10px 20px 0px 20px;
@@ -420,11 +604,102 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
420
604
  margin: 6px 20px 30px 20px;
421
605
  font-size: 14px;
422
606
  }
607
+ #root.layout-fullscreen #web-weaver-embed-inner .output {
608
+ align-self: flex-start;
609
+ max-width: min(80%, 720px);
610
+ margin: 0;
611
+ padding: 6px 12px;
612
+ border-radius: 14px;
613
+ background: var(--intelliweave-assistant-bubble-bg, rgba(32, 38, 44, 0.78));
614
+ font-size: 14px;
615
+ color: var(--intelliweave-assistant-bubble-text, inherit);
616
+ }
617
+ #root.layout-fullscreen #web-weaver-embed-inner .output > * {
618
+ margin-top: 0;
619
+ margin-bottom: 0;
620
+ }
621
+ #root.layout-fullscreen #web-weaver-embed-inner .output > * + * {
622
+ margin-top: 8px;
623
+ }
624
+
625
+ /* Image styles for markdown-rendered images in AI responses */
626
+ #web-weaver-embed-inner .output img {
627
+ max-width: 100%;
628
+ max-height: 300px;
629
+ width: auto;
630
+ height: auto;
631
+ border-radius: 8px;
632
+ margin: 8px 0;
633
+ display: block;
634
+ object-fit: contain;
635
+ }
636
+ #root.layout-fullscreen #web-weaver-embed-inner .output img {
637
+ max-width: 100%;
638
+ max-height: 400px;
639
+ }
423
640
 
641
+ /** Info block */
642
+ #web-weaver-embed-inner .info-block {
643
+ display: flex;
644
+ flex-direction: row;
645
+ align-items: flex-start;
646
+ margin: 10px 20px 10px 20px;
647
+ border: 1px solid var(--intelliweave-assistant-bubble-bg, rgba(42, 48, 54, 0.78));
648
+ border-radius: 8px;
649
+ background-color: var(--intelliweave-assistant-bubble-bg, rgba(42, 48, 54, 0.78));
650
+ padding: 10px;
651
+ gap: 8px;
652
+ color: var(--intelliweave-assistant-bubble-text, inherit);
653
+ }
654
+ #web-weaver-embed-inner .info-block .info-block-icon {
655
+ width: 14px;
656
+ height: 14px;
657
+ background-size: contain;
658
+ background-position: center;
659
+ background-repeat: no-repeat;
660
+ flex: 0 0 auto;
661
+ opacity: 0.5;
662
+ }
663
+ #web-weaver-embed-inner .info-block .info-block-text {
664
+ flex: 1 1 1px;
665
+ font-size: 11px;
666
+ opacity: 0.5;
667
+ }
668
+ #web-weaver-embed-inner .info-block .info-block-text > p:first-child {
669
+ margin-top: 0px;
670
+ }
671
+ #web-weaver-embed-inner .info-block .info-block-text > p:last-child {
672
+ margin-bottom: 0px;
673
+ }
674
+
675
+ /** Info block icons */
676
+ #web-weaver-embed-inner .info-block-icon.thinking-icon {
677
+ background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB4PSIwIiB5PSIwIiB2aWV3Qm94PSIwIDAgNTEyLjAwOCA1MTIiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDUxMiA1MTIiIHhtbDpzcGFjZT0icHJlc2VydmUiIGNsYXNzPSIiPjxnPjxwYXRoIGQ9Ik04LjA5NCAxODQuMTA1YTU0Ljg3NiA1NC44NzYgMCAwIDAgMjMuMjQyIDIwLjkxYzQuNTU5IDIuMTY5IDYuNDk2IDcuNjI2IDQuMzI0IDEyLjE4OC0yLjE3MiA0LjU1OS03LjYyOSA2LjQ5Ni0xMi4xODcgNC4zMjRhNzMuMDc0IDczLj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TUzLjAzMyA1My41OS01My41OWExNC45OTkgMTQuOTk5IDAgMCAwLTYuNzQ2LTI1LjEwMWMtNDYuNDgyLTEyLjM4Ni05Ni40MTMuOTc5LTEzMC4zMDMgMzQuODctMzcuMjY5IDM3LjI2OC00OS4xOTQgOTMuMDg2LTMxLjI4NiAxNDEuOTg4TDIzLjcyIDM4Ni40NzhDOC45MzcgMzk5Ljg1My41MjEgNDE4LjE5NC4wMjMgNDM4LjEyM2MtLjQ5OCAxOS45MyA2Ljk5MSAzOC42NjkgMjEuMDg4IDUyLjc2NkMzNC43NjggNTA0LjU0NSA1Mi43OCA1MTIgNzIuMDExIDUxMmMuNjIgMCAxLjI0My0uMDA4IDEuODY2LS4wMjMgMTkuOTI5LS40OTggMzguMjcxLTguOTE0IDUxLjY0Ni0yMy42OTdMMzMwLjU5IDI2MS42MjZhMTM0LjUyIDEzNC41MiAwIDAgMCA0Ni4yODkgOC4xODljMzUuMTYxIDAgNjkuODg4LTEzLjY2MSA5NS43MDktMzkuNDgzIDMzLjg5MS0zMy44OTEgNDcuMjUyLTgzLjgyMSAzNC44Ny0xMzAuMzAzek03NC4xNDQgNDUyLjg1NWMtOC4yODQgMC0xNS02LjcxNi0xNS0xNXM2LjcxNi0xNSAxNS0xNSAxNSA2LjcxNiAxNSAxNS02LjcxNSAxNS0xNSAxNXoiIGZpbGw9IiNmZmZmZmYiIG9wYWNpdHk9IjEiIGRhdGEtb3JpZ2luYWw9IiMwMDAwMDAiPjwvcGF0aD48L2c+PC9zdmc+");
681
+ }
682
+
424
683
  :host a, :host a:visited {
425
684
  color: rgba(128, 192, 255, 1);
426
685
  text-decoration: none;
427
686
  }
687
+ #root.layout-fullscreen #interaction-bar {
688
+ width: 100%;
689
+ max-width: 720px;
690
+ margin: 12px auto 0 auto;
691
+ border-radius: 12px;
692
+ overflow: hidden;
693
+ }
694
+ #root.layout-fullscreen #interaction-bar {
695
+ background-color: var(--intelliweave-interaction-bg, rgba(32, 38, 44, 0.9));
696
+ }
697
+ @media (max-width: 768px) {
698
+ #root.layout-fullscreen #interaction-bar {
699
+ width: calc(100% - 24px);
700
+ margin-bottom: calc(12px + env(safe-area-inset-bottom));
701
+ }
702
+ }
428
703
 
429
704
  .circle {
430
705
  width: 64px;
@@ -456,18 +731,32 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
456
731
  <div id='root' class='hidden'>
457
732
 
458
733
  <!-- Logo -->
459
- ${D.add({id:"web-weaver-logo",logo:this.attr.logo})}
734
+ ${F.add({id:"web-weaver-logo",logo:this.attr.logo})}
460
735
  <div id='pulseanim' class="circle pulse"></div>
461
736
 
737
+
738
+
739
+ <!-- Fullscreen header -->
740
+ <div id='fullscreen-header'>
741
+ <div id='fullscreen-persona'>
742
+ <img id='fullscreen-logo' src='' alt='' />
743
+ <span id='fullscreen-name'></span>
744
+ </div>
745
+ <div id='fullscreen-branding' class='branding-chatterly'>
746
+ <span class='brand-label'>CREATED WITH</span>
747
+ <span class='brand-name'>Chatterly</span>
748
+ </div>
749
+ </div>
750
+
462
751
  <!-- Inner container contains all the UI when the panel is open -->
463
752
  <div id='web-weaver-embed-inner'>
464
753
  </div>
465
754
 
466
755
  <!-- LLM selector panel -->
467
- ${K.add({id:"llm-selector-panel"})}
756
+ ${H.add({id:"llm-selector-panel"})}
468
757
 
469
758
  <!-- Interaction panel -->
470
- ${_.add({id:"interaction-bar"})}
759
+ ${K.add({id:"interaction-bar"})}
471
760
 
472
761
 
473
762
  <!-- Powered by IW banner -->
@@ -477,4 +766,11 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:be(typeo
477
766
 
478
767
  </div>
479
768
 
480
- `;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new W,M.isSupported&&(this.ai.audio=new M(this.ai))}onCreate(){h().embed&&b.warn("Only one <web-weaver-embed> element should be on the page."),h().embed=this;let e=h();b.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(b.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.positioningMode&&!this.attr.positioningMode&&(b.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(b.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(b.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(b.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(b.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),b.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",n=>this.onContainerClick(n)),this.child("web-weaver-logo").addEventListener("click",n=>this.onLogoClick(n)),this.child("interaction-bar").addEventListener("input-message",n=>this.processInput(n.detail)),this.child("interaction-bar").addEventListener("llm-button-click",n=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",n=>this.onLLMModelSelect(n)),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:n=>(this.suggestions.push(n.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:n.text}),"Suggestion button added")});let s=this.attr.apiKey||h().apiKey;if(!s)return b.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(s).then(n=>{this.config=n,h().introductionMessage=this.config.introductionMessage,h().analytics=this.config.analytics!==void 0?!!this.config.analytics:h().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(n=>{b.error("Failed to load AI configuration:",n),this.state.loading=!1;let o=this.child("web-weaver-embed-inner");o&&(o.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.attr.logo||e.logo;if(o&&o!==this._lastLogo){this._lastLogo=o,s=!0;let ke=this.child("web-weaver-logo");ke&&ke.setAttribute("logo",o)}let d=this.attr.background||e.background;d!==this._lastBackground&&(this._lastBackground=d,s=!0,d?t.style.background=d:t.style.background="");let l=this.attr.textColor||e.textColor,p=this.child("interaction-bar");l!==this._lastTextColor&&(this._lastTextColor=l,s=!0,l?(t.style.color=l,p&&p.setAttribute("textColor",l)):(t.style.color="",p&&p.removeAttribute("textColor")));let Z=this.attr.displayMode||e.displayMode||"closed";Z!==this._lastDisplayMode&&(this._lastDisplayMode=Z,s=!0,Z==="open"&&!this.attr.open&&(this.attr.open=!0));let pe=this.attr.positioningMode||e.positioningMode||"fixed";pe!==this._lastPositioningMode&&(this._lastPositioningMode=pe,s=!0);let me=this.attr.positionX||e.positionX||"right";me!==this._lastPositionX&&(this._lastPositionX=me,s=!0);let ge=this.attr.positionY||e.positionY||"bottom";ge!==this._lastPositionY&&(this._lastPositionY=ge,s=!0);let Ce=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,fe=Ce!==void 0?Ce:e.offsetX!==void 0?e.offsetX:20;fe!==this._lastOffsetX&&(this._lastOffsetX=fe,s=!0);let Me=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,ye=Me!==void 0?Me:e.offsetY!==void 0?e.offsetY:20;ye!==this._lastOffsetY&&(this._lastOffsetY=ye,s=!0),s&&b.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:o,finalBackground:t.style.background,finalTextColor:t.style.color,finalDisplayMode:Z,finalPositioningMode:pe,finalPositionX:me,finalPositionY:ge,finalOffsetX:fe,finalOffsetY:ye})}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(),f(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let d=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;f(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:d}})}this._previousOpenState=this.attr.open,this.attr.open?this.child("root").classList.add("open"):this.child("root").classList.remove("open");let e=this.child("root"),t=this._lastPositioningMode||"fixed",s=this._lastPositionX||"right",n=this._lastPositionY||"bottom",o=this._lastOffsetX!==void 0?this._lastOffsetX:20,r=this._lastOffsetY!==void 0?this._lastOffsetY:20;t==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),t!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",s==="left"?e.style.left=o+"px":e.style.right=o+"px",n==="top"?e.style.top=r+"px":e.style.bottom=r+"px"),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((d,c)=>(c.priority||0)-(d.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){h().embed==this&&(h().embed=void 0)}onContainerClick(e){(this._lastDisplayMode||"closed")!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.open=!0))}onLogoClick(e){if(e.preventDefault(),e.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{if((this._lastDisplayMode||"closed")==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=h().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let s of h().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=s,n.addEventListener("click",o=>this.onSuggestionClick(o,s)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let t=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let n of Array.from(t.querySelectorAll(".suggestion-button")))n.remove();this.attr.focusID="";let s=document.createElement("div");s.className="input",s.innerText=e,t.appendChild(s),this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output",this.currentOutputElement.style.display="none",this.currentOutputElement.innerHTML="",t.appendChild(this.currentOutputElement),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){b.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 vt().use(yt).use(bt).use(mt,{target:"_blank",rel:["noopener","noreferrer"]}).use(gt).use(ft).processSync(e);this.currentOutputElement&&(this.currentOutputElement.style.display="",this.currentOutputElement.innerHTML=t.toString("utf-8"));let s=this.child("web-weaver-embed-inner");for(let n of Array.from(s.querySelectorAll(".tool")))n.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}};A.tagName="intelliweave-embed",A.observedAttributes=["logo","focusID","open","background","textColor","displayMode","positioningMode","positionX","positionY","offsetX","offsetY"];var Ye=new u("React"),Vn=a=>typeof window>"u"?null:(A.register(),h().analytics=a.analytics??h().analytics,h().debug=a.debug??h().debug,a.context&&(h().pageSummary=a.context),a.introductionMessage&&(h().introductionMessage=a.introductionMessage),a.introductionSuggestions&&(h().introductionSuggestions=a.introductionSuggestions),a.userID&&(h().userID=a.userID),ue(()=>{let i=e=>{for(let t of a.knowledgeBase||[])e.entries.push(t);for(let t of a.sources||[])e.sources.push(t)};return document.addEventListener("webweaver_kb_search",i),()=>document.removeEventListener("webweaver_kb_search",i)},[a.knowledgeBase]),Fe.createElement("intelliweave-embed",{logo:a.logo,background:a.background,textColor:a.textColor,apiKey:a.apiKey,offsetX:a.offsetX||20,offsetY:a.offsetY||20,hubAPI:a.hubAPI,displayMode:a.displayMode,positioningMode:a.positioningMode,positionX:a.positionX,positionY:a.positionY})),ze=wt(void 0);function Ln(a){function i(){Ye.debug("Creating new IntelliWeave instance for <IntelliWeaveProvider />");let t=new W;return M.isSupported&&(t.audio=new M(t)),t.load(a.apiKey),t}h().analytics=a.analytics??h().analytics,h().debug=a.debug??h().debug;let e=St(()=>a.ai||i(),[a.ai,a.apiKey]);return ue(()=>{let t=s=>{let n=s;n.detail.isFinal&&e.sendMessage(n.detail.transcript)};return e.audio?.speechRecognition.addEventListener("speech",t),()=>{e.audio?.speechRecognition.removeEventListener("speech",t)}}),Fe.createElement(ze.Provider,{value:e},a.children)}function Bn(){let[a,i]=Ze(0),e=xt(ze)||h().embed?.ai;e||Ye.warn("Couldn't find IntelliWeave instance. Make sure you have <IntelliWeaveProvider /> somewhere in your scene graph, or use the <WebWeaverUI /> component.");let[,t]=Ze(!!e?.loaded),[,s]=Ze(e?.error);return ue(()=>{let n=d=>t(d.detail.ai.loaded),o=d=>s(d.detail.ai.error),r=()=>i(d=>d+1);return e?.addEventListener("load",n),e?.addEventListener("error",o),e?.addEventListener("input",r),e?.addEventListener("output",r),e?.addEventListener("toolstart",r),e?.addEventListener("tool",r),()=>{e?.removeEventListener("load",n),e?.removeEventListener("error",o),e?.removeEventListener("input",r),e?.removeEventListener("output",r),e?.removeEventListener("toolstart",r),e?.removeEventListener("tool",r)}},[e]),e}function Pn(a,i=[]){ue(()=>{let e=t=>t.sources.push({query:a});return document.addEventListener("webweaver_kb_search",e),()=>document.removeEventListener("webweaver_kb_search",e)},i)}export{Ln as IntelliWeaveProvider,Vn as WebWeaverUI,Bn as useIntelliWeave,Pn as useIntelliWeaveKnowledge};
769
+ `;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new N,G.isSupported&&(this.ai.audio=new G(this.ai))}onCreate(){h().embed&&v.warn("Only one <web-weaver-embed> element should be on the page."),h().embed=this;let e=h();v.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(v.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.layout&&!this.attr.layout&&(v.debug("[WebWeaverEmbed] Setting layout from client config:",e.layout),this.attr.layout=e.layout),e.positioningMode&&!this.attr.positioningMode&&(v.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(v.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(v.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(v.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(v.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),v.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",o=>this.onContainerClick(o)),this.child("web-weaver-logo").addEventListener("click",o=>this.onLogoClick(o)),this.child("interaction-bar").addEventListener("input-message",o=>this.processInput(o.detail)),this.child("interaction-bar").addEventListener("llm-button-click",o=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",o=>this.onLLMModelSelect(o)),this.child("web-weaver-embed-inner").addEventListener("scroll",o=>this.onContentScroll(o)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.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,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:o=>(this.suggestions.push(o.text),"Suggestion button added")}),this.ai.knowledgeBase.addEntry({id:"_iw_image_instructions",type:"info",name:"Using Images",content:`
770
+ You can display images in Markdown format, example: ![filename](url)
771
+ Image URLs must be absolute. When using an image URL from the knowledge base, include all parameters.`,isContext:!0});let n=this.attr.apiKey||h().apiKey;if(!n)return v.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(n).then(o=>{this.config=o.config,h().introductionMessage||(h().introductionMessage=this.config.introductionMessage),h().analytics=this.config.analytics!==void 0?!!this.config.analytics:h().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.config.managedBy&&this.updateBrandingFor(this.config.managedBy),this.resetConversation()}).catch(o=>{v.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(e,t){if(!t){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.removeProperty("--intelliweave-interaction-bg");return}let n=this.parseColorToRGB(t);if(!n){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.setProperty("--intelliweave-interaction-bg",t);return}let{r:o,g:s,b:a}=n;e.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${a}, 0.65)`),e.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),e.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${a}, 0.9)`)}parseColorToRGB(e){if(!e)return null;let t=e.trim();if(t.startsWith("#")){let n=t.slice(1);if(n.length===3){let o=parseInt(n[0]+n[0],16),s=parseInt(n[1]+n[1],16),a=parseInt(n[2]+n[2],16);return{r:o,g:s,b:a}}if(n.length===6){let o=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);return{r:o,g:s,b:a}}return null}if(t.startsWith("rgb")){let n=t.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return n?{r:Math.max(0,Math.min(255,Math.round(Number(n[1])))),g:Math.max(0,Math.min(255,Math.round(Number(n[2])))),b:Math.max(0,Math.min(255,Math.round(Number(n[3]))))}:null}return null}applyConfigStylesAndAttributes(){let e=this.config,t=this.child("root");if(!t)return;let n=!1,s=this.attr.logo||e.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,n=!0;let q=this.child("web-weaver-logo");q&&q.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),u=e.name||"";u!==this._lastPersonaName&&(this._lastPersonaName=u,l&&(l.textContent=u),n=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),n=!0);let c=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(c){let q=d==="hidden"||d==="none"||d==="false";c.style.display=!q&&(s||u)?"":"none"}let m=this.attr.background||e.background;m!==this._lastBackground&&(this._lastBackground=m,n=!0,m?(t.style.background=m,t.style.setProperty("--intelliweave-persona-bg",m),this.applyPersonaColorVariants(t,m)):(t.style.background="",t.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(t,void 0)));let b=this.attr.textColor||e.textColor,k=this.child("interaction-bar");b!==this._lastTextColor&&(this._lastTextColor=b,n=!0,b?(t.style.color=b,t.style.setProperty("--intelliweave-user-bubble-text",b),t.style.setProperty("--intelliweave-assistant-bubble-text",b),k&&k.setAttribute("textColor",b)):(t.style.color="",t.style.removeProperty("--intelliweave-user-bubble-text"),t.style.removeProperty("--intelliweave-assistant-bubble-text"),k&&k.removeAttribute("textColor")));let T=this.attr.displayMode||e.displayMode||"closed";T!==this._lastDisplayMode&&(this._lastDisplayMode=T,n=!0,T==="open"&&!this.attr.open&&(this.attr.open=!0));let xe=this.attr.layout||e.layout||"widget";xe!==this._lastLayout&&(this._lastLayout=xe,n=!0);let Me=this.attr.positioningMode||e.positioningMode||"fixed";Me!==this._lastPositioningMode&&(this._lastPositioningMode=Me,n=!0);let Ie=this.attr.positionX||e.positionX||"right";Ie!==this._lastPositionX&&(this._lastPositionX=Ie,n=!0);let Te=this.attr.positionY||e.positionY||"bottom";Te!==this._lastPositionY&&(this._lastPositionY=Te,n=!0);let Ze=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,Se=Ze!==void 0?Ze:e.offsetX!==void 0?e.offsetX:20;Se!==this._lastOffsetX&&(this._lastOffsetX=Se,n=!0);let De=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,ke=De!==void 0?De:e.offsetY!==void 0?e.offsetY:20;ke!==this._lastOffsetY&&(this._lastOffsetY=ke,n=!0),n&&v.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:t.style.background,finalTextColor:t.style.color,finalDisplayMode:T,finalLayout:xe,finalPositioningMode:Me,finalPositionX:Ie,finalPositionY:Te,finalOffsetX:Se,finalOffsetY:ke})}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.child("interaction-bar").attr.layout=this._lastLayout||"widget",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),w(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let u=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;w(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:u}})}this._previousOpenState=this.attr.open;let e=this.child("root");this.attr.open?e.classList.add("open"):e.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(e.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):e.classList.remove("layout-fullscreen");let n=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;n==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),n!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",o==="left"?e.style.left=a+"px":e.style.right=a+"px",s==="top"?e.style.top=l+"px":e.style.bottom=l+"px"),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((u,c)=>(c.priority||0)-(u.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){h().embed==this&&(h().embed=void 0)}onContainerClick(e){let t=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&t!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.open=!0))}onLogoClick(e){if(e.preventDefault(),e.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let t=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||t==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=h().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let n of h().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=n,o.addEventListener("click",s=>this.onSuggestionClick(s,n)),e.appendChild(o)}}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 a of Array.from(t.querySelectorAll(".suggestion-button")))a.remove();this.attr.focusID="";let n=document.createElement("div");n.className="input",n.innerText=e,t.appendChild(n);let o=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",t.appendChild(this.currentOutputElement);let s=Math.ceil(t.clientHeight-300);s<0&&(s=0),s>600&&(s=600),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"}),await this.ai.sendMessage(e);for(let a of this.suggestions){let l=document.createElement("div");l.className="suggestion-button",l.innerText=a,l.addEventListener("click",u=>this.onSuggestionClick(u,a)),this.currentOutputElement.appendChild(l)}}catch(n){v.error("Failed to process input:",n);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+n.message,t.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),t.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e,t){let n=[];for(let o of e)for(let s=0;s<(o.sections?.length||0);s++){let a=o.sections[s],l=`msgelem-${o.id||""}_${s}_${a.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let u=a.text||"";u.includes(`
772
+ `)&&(u=u.split(`
773
+ `)[0]),this.updateInfoElement(l,u,"thinking-icon"),n.push(l)}else if(a.type=="tool_call"){let c=new P(e).toolResult(a.toolCallInstanceID||"");if(a.toolCallHiddenInUI!="always"){if(c?.toolErrorResponse)this.updateInfoElement(l,"**Error:** "+c.toolErrorResponse||"","tool-icon"),n.push(l);else if(!(a.toolCallHiddenInUI=="after-complete"&&c))if(a.toolKbID=="search"){let d=a.toolParameters?.query?`**Search:** ${a.toolParameters.query}`:"**Search**";this.updateInfoElement(l,d,"tool-icon"),n.push(l)}else if(a.toolKbID?.startsWith("ask:")&&a.toolParameters?.query){let d=a.toolKbID.substring(4),m=`**Ask ${this.ai.subAgents.subagents.find(f=>f.id===d)?.name||"agent"}:** ${a.toolParameters.query}`;this.updateInfoElement(l,m,"tool-icon"),n.push(l)}else this.updateInfoElement(l,a.toolKbName||"","tool-icon"),n.push(l)}}else if(a.type!="tool_result"){if(!a.text)continue;this.updateTextElement(l,a.text||""),n.push(l)}}for(let o of Array.from(this.currentOutputElement.children))n.includes(o.id)||o.remove()}updateTextElement(e,t){let n=this.currentOutputElement.querySelector(`#${e}`);n||(n=document.createElement("div"),n.id=e,n.className="output",this.currentOutputElement.appendChild(n));let o=ot().use(it).use(nt).use(qe,{target:"_blank",rel:["noopener","noreferrer"]}).use(et).use(tt).processSync(t||"");n.innerHTML=o.toString("utf-8")}updateInfoElement(e,t,n){let o=this.currentOutputElement.querySelector(`#${e}`);o||(o=document.createElement("div"),o.id=e,o.className="info-block",o.innerHTML=`
774
+ <div class='info-block-icon'></div>
775
+ <div class='info-block-text'></div>
776
+ `,this.currentOutputElement.appendChild(o));let s=ot().use(it).use(nt).use(qe,{target:"_blank",rel:["noopener","noreferrer"]}).use(et).use(tt).processSync(t||"");o.querySelector(".info-block-icon").className="info-block-icon "+n,o.querySelector(".info-block-text").innerHTML=s.toString("utf-8")}onSuggestionClick(e,t){this.processInput(t)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}onContentScroll(e){let t=this.child("fullscreen-header");if(!t)return;let n=e.target.scrollTop,o=0,s=60;if(n<=o)t.style.opacity="1",t.style.pointerEvents="";else if(n>=s)t.style.opacity="0",t.style.pointerEvents="none";else{let a=1-(n-o)/(s-o);t.style.opacity=String(a),t.style.pointerEvents=a<.5?"none":""}}updateBrandingFor(e){if(!e)return;this.root?.querySelectorAll(`.branding-${e}`)?.forEach(n=>{n.classList.add("visible")})}};Y.tagName="intelliweave-embed",Y.observedAttributes=["logo","focusID","open","background","textColor","displayMode","layout","header","positioningMode","positionX","positionY","offsetX","offsetY"];var at=new p("React"),ks=r=>typeof window>"u"?null:(Y.register(),h().analytics=r.analytics??h().analytics,h().debug=r.debug??h().debug,r.context&&(h().pageSummary=r.context),r.introductionMessage&&(h().introductionMessage=r.introductionMessage),r.introductionSuggestions&&(h().introductionSuggestions=r.introductionSuggestions),r.userID&&(h().userID=r.userID),ve(()=>{let i=e=>{for(let t of r.knowledgeBase||[])e.entries.push(t);for(let t of r.sources||[])e.sources.push(t)};return document.addEventListener("webweaver_kb_search",i),()=>document.removeEventListener("webweaver_kb_search",i)},[r.knowledgeBase]),st.createElement("intelliweave-embed",{logo:r.logo,background:r.background,textColor:r.textColor,apiKey:r.apiKey,offsetX:r.offsetX||20,offsetY:r.offsetY||20,hubAPI:r.hubAPI,displayMode:r.displayMode,layout:r.layout,header:r.header,positioningMode:r.positioningMode,positionX:r.positionX,positionY:r.positionY})),rt=Zt(void 0);function Cs(r){function i(){at.debug("Creating new IntelliWeave instance for <IntelliWeaveProvider />");let t=new N;return G.isSupported&&(t.audio=new G(t)),t.load(r.apiKey),t}h().analytics=r.analytics??h().analytics,h().debug=r.debug??h().debug;let e=Xt(()=>r.ai||i(),[r.ai,r.apiKey]);return ve(()=>{let t=n=>{let o=n;o.detail.isFinal&&e.sendMessage(o.detail.transcript)};return e.audio?.speechRecognition.addEventListener("speech",t),()=>{e.audio?.speechRecognition.removeEventListener("speech",t)}}),st.createElement(rt.Provider,{value:e},r.children)}function Ls(){let[r,i]=Ge(0),e=Dt(rt)||h().embed?.ai;e||at.warn("Couldn't find IntelliWeave instance. Make sure you have <IntelliWeaveProvider /> somewhere in your scene graph, or use the <WebWeaverUI /> component.");let[,t]=Ge(!!e?.loaded),[,n]=Ge(e?.error);return ve(()=>{let o=l=>t(l.detail.ai.loaded),s=l=>n(l.detail.ai.error),a=()=>i(l=>l+1);return e?.addEventListener("load",o),e?.addEventListener("error",s),e?.addEventListener("input",a),e?.addEventListener("output",a),e?.addEventListener("toolstart",a),e?.addEventListener("tool",a),()=>{e?.removeEventListener("load",o),e?.removeEventListener("error",s),e?.removeEventListener("input",a),e?.removeEventListener("output",a),e?.removeEventListener("toolstart",a),e?.removeEventListener("tool",a)}},[e]),e}function As(r,i=[]){ve(()=>{let e=t=>t.sources.push({query:r});return document.addEventListener("webweaver_kb_search",e),()=>document.removeEventListener("webweaver_kb_search",e)},i)}export{Cs as IntelliWeaveProvider,ks as WebWeaverUI,Ls as useIntelliWeave,As as useIntelliWeaveKnowledge};