@intelliweave/embedded 2.2.82 → 2.2.84

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,18 +1,18 @@
1
- import Rt,{createContext as xi,useContext as Mi,useEffect as Ke,useMemo as Ii,useState as lt}from"react";import Yt from"openai";import{v4 as zt}from"uuid";var _=class{constructor(){this.size=4096;this.groups=[]}createGroup(n){let e=new $e;return e.id=n,this.groups.push(e),e}group(n){return this.groups.find(e=>e.id===n)}static countTokensInText(n){return n==null?n="":typeof n=="number"?n=n+"":typeof n!="string"&&(n=JSON.stringify(n)),Math.ceil(n.length/3)}countTokens(){return this.groups.reduce((n,e)=>n+e.tokenCount,0)}removeOverflow(){let n=this.countTokens(),e=this.groups.reduce((t,i)=>t+i.weight,0);for(;n>this.size;){let t=this.groups.slice().sort((o,s)=>{let r=Math.floor(o.weight/e*this.size),l=Math.floor(s.weight/e*this.size),u=o.tokenCount-r;return s.tokenCount-l-u}),i=this.removeOneItem(t);if(!i)throw new Error("Too many items in the token window that cannot be removed.");n-=i.tokenCount}}removeOneItem(n){for(let e of n){let t=e.items.findIndex(o=>!o.cannotRemove);if(t===-1)continue;let i=e.items[t];return e.items.splice(t,1),e.tokenCount-=i.tokenCount,i}return null}},$e=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
2
- `;this.itemPadding=0;this.sortFunction=(n,e)=>n.sortOrder!==e.sortOrder?n.sortOrder-e.sortOrder:n.dateAdded!==e.dateAdded?n.dateAdded-e.dateAdded:0}setItemPadding(n){return this.itemPadding=n,this.recalculateTokens(),this}sortBy(n){return this.sortFunction=n,this.items.sort(this.sortFunction),this}setSeparator(n){return this.separator==n?this:(this.separator=n,this.recalculateTokens(),this)}setWeight(n){return this.weight=n,this}recalculateTokens(){this.tokenCount=this.items.reduce((n,e)=>(e.tokenCount=_.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+_.countTokensInText(this.separator)+this.itemPadding,n+e.tokenCount),0)}add(n){typeof n=="string"&&(n={source:"user",data:n});let e=n;e.id===void 0&&(e.id=zt()),!e.sections?.length&&typeof e.data=="string"?e.text=e.data:e.text=e.sections?.map(i=>{if(i.type==="text")return i.text||"";if(i.type==="tool_call")return`[Tool Call: ${i.toolKbName||i.toolName}] `;if(i.type==="tool_result"&&i.toolErrorResponse)return`[Tool Error: ${i.toolErrorResponse}] `}).filter(i=>!!i).join(`
1
+ import Rt,{createContext as xi,useContext as Mi,useEffect as He,useMemo as Ii,useState as at}from"react";import Yt from"openai";import{v4 as zt}from"uuid";var O=class{constructor(){this.size=4096;this.groups=[]}createGroup(n){let e=new Je;return e.id=n,this.groups.push(e),e}group(n){return this.groups.find(e=>e.id===n)}static countTokensInText(n){return n==null?n="":typeof n=="number"?n=n+"":typeof n!="string"&&(n=JSON.stringify(n)),Math.ceil(n.length/3)}countTokens(){return this.groups.reduce((n,e)=>n+e.tokenCount,0)}removeOverflow(){let n=this.countTokens(),e=this.groups.reduce((t,i)=>t+i.weight,0);for(;n>this.size;){let t=this.groups.slice().sort((o,r)=>{let s=Math.floor(o.weight/e*this.size),l=Math.floor(r.weight/e*this.size),u=o.tokenCount-s;return r.tokenCount-l-u}),i=this.removeOneItem(t);if(!i)throw new Error("Too many items in the token window that cannot be removed.");n-=i.tokenCount}}removeOneItem(n){for(let e of n){let t=e.items.findIndex(o=>!o.cannotRemove);if(t===-1)continue;let i=e.items[t];return e.items.splice(t,1),e.tokenCount-=i.tokenCount,i}return null}},Je=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
2
+ `;this.itemPadding=0;this.sortFunction=(n,e)=>n.sortOrder!==e.sortOrder?n.sortOrder-e.sortOrder:n.dateAdded!==e.dateAdded?n.dateAdded-e.dateAdded:0}setItemPadding(n){return this.itemPadding=n,this.recalculateTokens(),this}sortBy(n){return this.sortFunction=n,this.items.sort(this.sortFunction),this}setSeparator(n){return this.separator==n?this:(this.separator=n,this.recalculateTokens(),this)}setWeight(n){return this.weight=n,this}recalculateTokens(){this.tokenCount=this.items.reduce((n,e)=>(e.tokenCount=O.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+O.countTokensInText(this.separator)+this.itemPadding,n+e.tokenCount),0)}add(n){typeof n=="string"&&(n={source:"user",data:n});let e=n;e.id===void 0&&(e.id=zt()),!e.sections?.length&&typeof e.data=="string"?e.text=e.data:e.text=e.sections?.map(i=>{if(i.type==="text")return i.text||"";if(i.type==="tool_call")return`[Tool Call: ${i.toolKbName||i.toolName}] `;if(i.type==="tool_result"&&i.toolErrorResponse)return`[Tool Error: ${i.toolErrorResponse}] `}).filter(i=>!!i).join(`
3
3
 
4
- `)||"";let t=this.items.find(i=>i.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:_.countTokensInText(typeof n.data=="string"?n.data:JSON.stringify(n.data))+_.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}remove(n){let e=this.items.findIndex(t=>t.id===n);return e===-1?!1:(this.tokenCount-=this.items[e].tokenCount||0,this.items.splice(e,1),!0)}getAllAsString(){return this.getAll().map(n=>n.text).join(this.separator)}getAll(){return this.items.filter(n=>!n.disabled)}empty(){this.items=[],this.tokenCount=0}};import{v4 as Vt}from"uuid";import{v4 as ut}from"uuid";function ke(a){let n=(a||"").split(`
4
+ `)||"";let t=this.items.find(i=>i.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:O.countTokensInText(typeof n.data=="string"?n.data:JSON.stringify(n.data))+O.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}remove(n){let e=this.items.findIndex(t=>t.id===n);return e===-1?!1:(this.tokenCount-=this.items[e].tokenCount||0,this.items.splice(e,1),!0)}getAllAsString(){return this.getAll().map(n=>n.text).join(this.separator)}getAll(){return this.items.filter(n=>!n.disabled)}empty(){this.items=[],this.tokenCount=0}};import{v4 as Vt}from"uuid";import{v4 as ut}from"uuid";function Se(a){let n=(a||"").split(`
5
5
  `);for(;n.length>0&&n[0].trim()=="";)n.shift();for(;n.length>0&&n[n.length-1].trim()=="";)n.pop();let e=1/0;for(let t of n){let i=t.match(/^\s*/)?.[0].length||0;e=Math.min(e,i)}return e>0&&e<1/0&&(n=n.map(t=>t.substring(e))),n.join(`
6
- `)}var Ot={};function z(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:Ot}function b(){return z().intelliweave=z().intelliweave||z().webWeaver||{},z().intelliweave}function pt(){if(b().userID)return b().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let a=localStorage.getItem("intelliweave.uid")||"";return a||(a=ut(),localStorage.setItem("intelliweave.uid",a),a)}else return ut()}function ht(a){let n=a;if(n?.type=="object"&&n.properties)return a;let e={type:"object",properties:{},required:[]};if(a&&Array.isArray(a)){let t=a;for(let i of t)e.properties[i.name]={type:i.type||"string",description:i.description||""}}return e}var Se=class Se{constructor(n){this.module="IntelliWeave";this.module=n}get debugEnabled(){return Se.debug?!0:typeof window<"u"&&b().debug}log(...n){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...n)}debug(...n){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...n)}info(...n){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...n)}warn(...n){console.warn(`[IntelliWeave > ${this.module}]`,...n)}error(...n){console.error(`[IntelliWeave > ${this.module}]`,...n)}timer(n,...e){let t=Date.now();return this.debug(`[${n} 0ms] Started`,...e),(...i)=>this.debug(`[${n} ${Math.floor(Date.now()-t)}ms]`,...i)}};Se.debug=!1;var f=Se;var mt=new f("ChatBase"),Q=class{constructor(n){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let n=new _;return n.createGroup("context").setSeparator(`
6
+ `)}var Ot={};function V(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:Ot}function b(){return V().intelliweave=V().intelliweave||V().webWeaver||{},V().intelliweave}function pt(){if(b().userID)return b().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let a=localStorage.getItem("intelliweave.uid")||"";return a||(a=ut(),localStorage.setItem("intelliweave.uid",a),a)}else return ut()}function ht(a){let n=a;if(n?.type=="object"&&n.properties)return a;let e={type:"object",properties:{},required:[]};if(a&&Array.isArray(a)){let t=a;for(let i of t)e.properties[i.name]={type:i.type||"string",description:i.description||""}}return e}var Te=class Te{constructor(n){this.module="IntelliWeave";this.module=n}get debugEnabled(){return Te.debug?!0:typeof window<"u"&&b().debug}log(...n){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...n)}debug(...n){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...n)}info(...n){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...n)}warn(...n){console.warn(`[IntelliWeave > ${this.module}]`,...n)}error(...n){console.error(`[IntelliWeave > ${this.module}]`,...n)}timer(n,...e){let t=Date.now();return this.debug(`[${n} 0ms] Started`,...e),(...i)=>this.debug(`[${n} ${Math.floor(Date.now()-t)}ms]`,...i)}};Te.debug=!1;var f=Te;var mt=new f("ChatBase"),ie=class{constructor(n){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let n=new O;return n.createGroup("context").setSeparator(`
7
7
 
8
- `),n.createGroup("actions").setItemPadding(25),n.createGroup("messages").setItemPadding(10),n})();this.config=n,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 n=this.config.endpoint;return n.endsWith("/chat/completions")&&(n=n.substring(0,n.length-17)),n}async sendMessage(n,e){throw new Error("Not implemented")}addUserMessage(n){throw new Error("Not implemented")}addAssistantMessage(n){throw new Error("Not implemented")}addTextMessage(n,e,t){this.messageGroup.add({id:"msg-"+Vt(),source:e,data:t,sections:[{type:"text",text:n}]})}onBeforeIncomingMessage(n){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(n){return this.toolGroup.add({id:n.name,data:n,cannotRemove:!n.canRemove,sortOrder:101,disabled:!!n.kbItem?.disabled})}findToolBySafeName(n){return this.toolGroup.getAll().find(e=>e.id==n||e.data?.kbItem?.name==n)?.data}async executeTool(n,e){if(!n)throw new Error("Tool not found");mt.debug(`Executing tool '${n.name}'`,e,n),this.config.onAIToolStart?.(n.kbItem?.name||n.name,e);let t;try{t=await n.callback(e)}catch(i){throw mt.error(`Error executing tool '${n.name}'`,i),i}return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),t}};import{v4 as Ft}from"uuid";var Qe=new f("ChatGPT"),Te=class extends Q{addUserMessage(n){this.addTextMessage(n,"user",{role:"user",content:n||""})}addAssistantMessage(n){this.addTextMessage(n,"assistant",{role:"assistant",content:n||""})}createOpenAIClient(){return new Yt({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(n,e){this.addUserMessage(n);let t=this.createOpenAIClient(),i=!0,o=[];for(;i;){let s="msg-"+Ft();i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),Qe.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 r=this.toolGroup.getAll().filter(c=>!!c?.data).map(c=>({type:"function",function:{name:c.data.name,description:c.data.description||"",parameters:{type:"object",...c.data?.params}}})),l,u;if(this.config.stream){let c=t.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(h=>h.data)],tools:r,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let h of c){let p=c.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!p)continue;let m=this.parseMessageBlock(s,p,void 0,!0);this.config.onAIMessage?.([...o,m],!0),e?.([...o,m])}l=await c.finalMessage(),u=await c.totalUsage()}else{let c=await t.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(h=>h.data)],tools:r,parallel_tool_calls:!0});l=c.choices[0].message,u=c.usage}l.role=="assistant"&&!l.content&&!l.tool_calls?.length&&(l.content=""),Qe.debug("Message received",l);let d=this.messageGroup.add(this.parseMessageBlock(s,l,u,!1));o.push(d),await Promise.all((l.tool_calls||[]).map(async c=>{if(c.type!="function")return;let h=this.findToolBySafeName(c.function.name);try{let p=null;try{p=c.function.arguments?JSON.parse(c.function.arguments):null}catch(y){throw new Error(`The AI provided invalid JSON arguments for tool call ${c.function.name}: ${y.message}`)}let m=await this.executeTool(h,p),g=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:c.function.name,toolKbID:h?.kbItem?.id,toolKbName:h?.kbItem?.name,toolSuccessResponse:m,toolCallInstanceID:c.id,toolCallHiddenInUI:h?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:c.id,content:m}});o.push(g)}catch(p){let m=p?.message||"An unknown error occurred",g=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:c.function.name,toolKbID:h?.kbItem?.id,toolKbName:h?.kbItem?.name,toolErrorResponse:m,toolCallInstanceID:c.id,toolCallHiddenInUI:h?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:c.id,content:`Error performing tool call ${c.function.name}: ${m}`}});o.push(g)}i=!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(n,e,t,i){let o=[];e.reasoning&&o.push({type:"thinking",text:e.reasoning});for(let s of e.tool_calls||[]){if(s.type!="function")continue;let r=this.findToolBySafeName(s.function.name),l=null;if(s.function.arguments)try{l=JSON.parse(s.function.arguments)}catch(u){i||Qe.error(`Failed to parse tool parameters for tool call ${s.function.name}:`,u)}o.push({type:"tool_call",toolName:s.function.name,toolKbID:r?.kbItem?.id,toolKbName:r?.kbItem?.name,toolCallInstanceID:s.id,toolCallHiddenInUI:r?.kbItem?.hideActionInUI,toolParameters:l})}return typeof e.content=="string"&&o.push({type:"text",text:e.content||""}),{id:n,data:e,sections:o,source:"assistant",streamingInProgress:i,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 Ut from"@anthropic-ai/sdk";import{v4 as Kt}from"uuid";var gt=new f("AnthropicChat"),Ce=class extends Q{addUserMessage(n){this.addTextMessage(n,"user",{role:"user",content:n||""})}addAssistantMessage(n){this.addTextMessage(n,"assistant",{role:"assistant",content:n||""})}async sendMessage(n,e){this.addUserMessage(n);let t=new Ut({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),i=!0,o=[];for(;i;){i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),gt.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 s=this.toolGroup.getAll().map(d=>({name:d.data?.name||"",description:d.data?.description||"",input_schema:{...d.data?.params,type:"object"}})),r;if(this.config.stream){let d=t.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(c=>c.data),tools:s,stream:!0});d.on("streamEvent",(c,h)=>{let p=this.parseMessageBlock(h,!0);this.config.onAIMessage?.([...o,p],!0),e?.([...o,p])});try{r=await d.finalMessage()}catch(c){throw c?.error?.error?.message?c.error.error:c}}else try{r=await t.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(d=>d.data),tools:s})}catch(d){throw d?.error?.error?.message?d.error.error:d}if(gt.debug("Message received",r),r.content?.length){let d=this.messageGroup.add(this.parseMessageBlock(r,!1));o.push(d)}let l=[],u=[];if(await Promise.all(r.content.map(async d=>{if(d.type!="tool_use")return;let c=this.findToolBySafeName(d.name);try{let h=await this.executeTool(c,d.input);u.push({type:"tool_result",tool_use_id:d.id,content:h}),l.push({type:"tool_result",toolKbID:c?.kbItem?.id,toolKbName:c?.kbItem?.name,toolName:d.name,toolSuccessResponse:h,toolCallInstanceID:d.id,toolCallHiddenInUI:c?.kbItem?.hideActionInUI})}catch(h){let p=h?.message||"An unknown error occurred";u.push({type:"tool_result",tool_use_id:d.id,content:`Error performing tool call ${d.name}: ${p}`}),l.push({type:"tool_result",toolKbID:c?.kbItem?.id,toolKbName:c?.kbItem?.name,toolName:d.name,toolErrorResponse:p,toolCallInstanceID:d.id,toolCallHiddenInUI:c?.kbItem?.hideActionInUI})}})),u.length>0){let d=this.messageGroup.add({id:"msg-"+Kt(),sections:l,data:{role:"user",content:u}});o.push(d),i=!0,this.config.onAIMessage?.(o,!0),e?.(o)}this.stats.tokensUsed+=r.usage.input_tokens+r.usage.output_tokens}return this.config.onAIMessage?.(o,!1),e?.(o),o}parseMessageBlock(n,e){let t=[];for(let i of n.content)if(i.type=="thinking")t.push({type:"thinking",text:i.thinking||""});else if(i.type=="text")t.push({type:"text",text:i.text||""});else if(i.type=="tool_use"){let o=this.findToolBySafeName(i.name);t.push({type:"tool_call",toolName:i.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:i.input,toolCallInstanceID:i.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:n.id,data:{role:n.role,content:n.content},sections:t,source:"assistant",streamingInProgress:e,usage:{inputTokens:n.usage?.input_tokens||0,outputTokens:n.usage?.output_tokens||0,cachedInputTokens:n.usage?.cache_read_input_tokens||0,totalTokens:(n.usage?.input_tokens||0)+(n.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 yt}from"uuid";import ni from"minisearch";var ft=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,hideActionInUI:"after-complete",disabled:!a?.knowledgeBase?.allowRagSearch,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(n,e)=>{let t=await e.knowledgeBase.search(n.query),i=e;i._lastKBsearch=n.query,i._nextRequestUseKBitems=t;let o=t.filter(r=>r.type!="action").map(r=>"- "+r.name).join(`
9
- `)||"- (none)",s=t.filter(r=>r.type=="action").map(r=>"- "+r._functionID).join(`
8
+ `),n.createGroup("actions").setItemPadding(25),n.createGroup("messages").setItemPadding(10),n})();this.config=n,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 n=this.config.endpoint;return n.endsWith("/chat/completions")&&(n=n.substring(0,n.length-17)),n}async sendMessage(n,e){throw new Error("Not implemented")}addUserMessage(n){throw new Error("Not implemented")}addAssistantMessage(n){throw new Error("Not implemented")}addTextMessage(n,e,t){this.messageGroup.add({id:"msg-"+Vt(),source:e,data:t,sections:[{type:"text",text:n}]})}onBeforeIncomingMessage(n){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(n){return this.toolGroup.add({id:n.name,data:n,cannotRemove:!n.canRemove,sortOrder:101,disabled:!!n.kbItem?.disabled})}findToolBySafeName(n){return this.toolGroup.getAll().find(e=>e.id==n||e.data?.kbItem?.name==n)?.data}async executeTool(n,e){if(!n)throw new Error("Tool not found");mt.debug(`Executing tool '${n.name}'`,e,n),this.config.onAIToolStart?.(n.kbItem?.name||n.name,e);let t;try{t=await n.callback(e)}catch(i){throw mt.error(`Error executing tool '${n.name}'`,i),i}return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),t}};import{v4 as Ft}from"uuid";var $e=new f("ChatGPT"),Ce=class extends ie{addUserMessage(n){this.addTextMessage(n,"user",{role:"user",content:n||""})}addAssistantMessage(n){this.addTextMessage(n,"assistant",{role:"assistant",content:n||""})}createOpenAIClient(){return new Yt({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(n,e){this.addUserMessage(n);let t=this.createOpenAIClient(),i=!0,o=[];for(;i;){let r="msg-"+Ft();i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),$e.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 s=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(h=>h.data)],tools:s,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let h of d){let p=d.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!p)continue;let m=this.parseMessageBlock(r,p,void 0,!0);this.config.onAIMessage?.([...o,m],!0),e?.([...o,m])}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(h=>h.data)],tools:s,parallel_tool_calls:!0});l=d.choices[0].message,u=d.usage}l.role=="assistant"&&!l.content&&!l.tool_calls?.length&&(l.content=""),$e.debug("Message received",l);let c=this.messageGroup.add(this.parseMessageBlock(r,l,u,!1));o.push(c),await Promise.all((l.tool_calls||[]).map(async d=>{if(d.type!="function")return;let h=this.findToolBySafeName(d.function.name);try{let p=null;try{p=d.function.arguments?JSON.parse(d.function.arguments):null}catch(y){throw new Error(`The AI provided invalid JSON arguments for tool call ${d.function.name}: ${y.message}`)}let m=await this.executeTool(h,p),g=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:h?.kbItem?.id,toolKbName:h?.kbItem?.name,toolSuccessResponse:m,toolCallInstanceID:d.id,toolCallHiddenInUI:h?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:m}});o.push(g)}catch(p){let m=p?.message||"An unknown error occurred",g=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:h?.kbItem?.id,toolKbName:h?.kbItem?.name,toolErrorResponse:m,toolCallInstanceID:d.id,toolCallHiddenInUI:h?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:`Error performing tool call ${d.function.name}: ${m}`}});o.push(g)}i=!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(n,e,t,i){let o=[];e.reasoning&&o.push({type:"thinking",text:e.reasoning});for(let r of e.tool_calls||[]){if(r.type!="function")continue;let s=this.findToolBySafeName(r.function.name),l=null;if(r.function.arguments)try{l=JSON.parse(r.function.arguments)}catch(u){i||$e.error(`Failed to parse tool parameters for tool call ${r.function.name}:`,u)}o.push({type:"tool_call",toolName:r.function.name,toolKbID:s?.kbItem?.id,toolKbName:s?.kbItem?.name,toolCallInstanceID:r.id,toolCallHiddenInUI:s?.kbItem?.hideActionInUI,toolParameters:l})}return typeof e.content=="string"&&o.push({type:"text",text:e.content||""}),{id:n,data:e,sections:o,source:"assistant",streamingInProgress:i,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 Ut from"@anthropic-ai/sdk";import{v4 as Kt}from"uuid";var gt=new f("AnthropicChat"),Ee=class extends ie{addUserMessage(n){this.addTextMessage(n,"user",{role:"user",content:n||""})}addAssistantMessage(n){this.addTextMessage(n,"assistant",{role:"assistant",content:n||""})}async sendMessage(n,e){this.addUserMessage(n);let t=new Ut({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),i=!0,o=[];for(;i;){i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),gt.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 r=this.toolGroup.getAll().map(c=>({name:c.data?.name||"",description:c.data?.description||"",input_schema:{...c.data?.params,type:"object"}})),s;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:r,stream:!0});c.on("streamEvent",(d,h)=>{let p=this.parseMessageBlock(h,!0);this.config.onAIMessage?.([...o,p],!0),e?.([...o,p])});try{s=await c.finalMessage()}catch(d){throw d?.error?.error?.message?d.error.error:d}}else try{s=await t.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(c=>c.data),tools:r})}catch(c){throw c?.error?.error?.message?c.error.error:c}if(gt.debug("Message received",s),s.content?.length){let c=this.messageGroup.add(this.parseMessageBlock(s,!1));o.push(c)}let l=[],u=[];if(await Promise.all(s.content.map(async c=>{if(c.type!="tool_use")return;let d=this.findToolBySafeName(c.name);try{let h=await this.executeTool(d,c.input);u.push({type:"tool_result",tool_use_id:c.id,content:h}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:c.name,toolSuccessResponse:h,toolCallInstanceID:c.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}catch(h){let p=h?.message||"An unknown error occurred";u.push({type:"tool_result",tool_use_id:c.id,content:`Error performing tool call ${c.name}: ${p}`}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:c.name,toolErrorResponse:p,toolCallInstanceID:c.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}})),u.length>0){let c=this.messageGroup.add({id:"msg-"+Kt(),sections:l,data:{role:"user",content:u}});o.push(c),i=!0,this.config.onAIMessage?.(o,!0),e?.(o)}this.stats.tokensUsed+=s.usage.input_tokens+s.usage.output_tokens}return this.config.onAIMessage?.(o,!1),e?.(o),o}parseMessageBlock(n,e){let t=[];for(let i of n.content)if(i.type=="thinking")t.push({type:"thinking",text:i.thinking||""});else if(i.type=="text")t.push({type:"text",text:i.text||""});else if(i.type=="tool_use"){let o=this.findToolBySafeName(i.name);t.push({type:"tool_call",toolName:i.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:i.input,toolCallInstanceID:i.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:n.id,data:{role:n.role,content:n.content},sections:t,source:"assistant",streamingInProgress:e,usage:{inputTokens:n.usage?.input_tokens||0,outputTokens:n.usage?.output_tokens||0,cachedInputTokens:n.usage?.cache_read_input_tokens||0,totalTokens:(n.usage?.input_tokens||0)+(n.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 yt}from"uuid";import ni from"minisearch";var ft=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,hideActionInUI:"after-complete",disabled:!a?.knowledgeBase?.allowRagSearch,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(n,e)=>{let t=await e.knowledgeBase.search(n.query),i=e;i._lastKBsearch=n.query,i._nextRequestUseKBitems=t;let o=t.filter(s=>s.type!="action").map(s=>"- "+s.name).join(`
9
+ `)||"- (none)",r=t.filter(s=>s.type=="action").map(s=>"- "+s._functionID).join(`
10
10
  `)||"- (none)";return`Search complete, context has been updated.
11
11
  New information found:
12
12
  ${o}
13
13
 
14
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"||!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:(n,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(!n.url||typeof n.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(n.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${n.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:(n,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(!n.path||typeof n.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(n.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"||!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:(n,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(!n.email_address||typeof n.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!n.subject||typeof n.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!n.body||typeof n.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(n.email_address),i=encodeURIComponent(n.subject),o=encodeURIComponent(n.body),s=`mailto:${t}?subject=${i}&body=${o}`;try{window.location.href=s}catch(r){throw new Error(`Failed to open email client: ${r instanceof Error?r.message:String(r)}`)}return`Email opened in default mail client. Recipient: ${n.email_address}, Subject: ${n.subject}`}}];import{Client as Jt}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as $t}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var O={name:"@intelliweave/embedded",version:"2.2.82",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.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.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 Qt,ToolListChangedNotificationSchema as qt}from"@modelcontextprotocol/sdk/types.js";var I=new f("MCPKnowledgeClient"),ei="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",Ee=class{constructor(n){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=n}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(){I.debug("Connecting to MCP client");let n=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||ei));let i=new Jt({name:O.name,version:O.version}),o=new $t(e,{requestInit:{headers:t}});return await i.connect(o),I.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=n,n.onerror=e=>{I.error(`MCP client error: ${e.message}`)},n.onclose=()=>{I.debug("MCP client connection closed"),this.client=void 0},n.setNotificationHandler(Qt,e=>{e.params.level=="critical"?I.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?I.error(`[Server] ${e.params.data}`):e.params.level=="error"?I.error(`[Server] ${e.params.data}`):e.params.level=="warning"?I.warn(`[Server] ${e.params.data}`):e.params.level=="info"?I.info(`[Server] ${e.params.data}`):e.params.level=="debug"?I.debug(`[Server] ${e.params.data}`):I.log(`[Server] ${e.params.data}`)}),n.setNotificationHandler(qt,e=>{I.debug("Tool list changed",e),this.fetchTools()}),I.debug("Fetching tools from MCP server..."),await this.fetchTools(),n}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let n=[],e;for(;;){let o=await this.client.listTools({cursor:e});e=o.nextCursor;for(let s of o.tools||[])n.push(s);if(!o?.tools?.length||!e)break}let t=[],i=this.config.id||"mcp";for(let o of n){let s=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),r=`${i}_${o.name}`;t.push({id:r,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:s})}I.debug(`Fetched ${n.length} tools from MCP server.`),this.tools=n,this.iwActions=t}async search(n){if(n==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(n);return e=e.concat(t),this.lastSearchQuery=n,this.lastSearchResults=e,I.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(n){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(o=>o.name==this.config.searchToolName);if(!t)return I.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let i;if(t.inputSchema.required?.length==1){let o=t.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:n})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let o=Object.keys(t.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:n})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[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 i=="string"?i:JSON.stringify(i)});return e}async performToolCall(n,e){await this.connect(),I.debug(`Performing tool call for ${n} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:n,arguments:e});if(t.isError){let i=t.content?.[0]?.text||"Unknown error";throw I.error(`Error calling tool ${n}: ${i}`),new Error(`Error calling tool ${n}: ${i}`)}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 ti}from"uuid";var ii=new f("Statistics"),ge=[];async function C(a,n){let e={...n,event_id:ti(),event_date:new Date().toISOString(),sdk_version:O.version,conversation_id:a?.conversationID||"",api_key:a?.apiKey||"",user_id:a?.userID||""};if(ge.push(e),!a||(await new Promise(i=>setTimeout(i,5e3)),ge.length===0))return;let t=ge.slice();ge.length=0;try{let i=await fetch(a.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){ii.warn("Failed to submit analytics event:",i),ge.push(...t);return}}var V=new f("KnowledgeBase"),oi=8*1024,qe=1,Ae=class a{constructor(n){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=n,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(n=>n.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>ft(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(n,e){let t=n;return typeof n=="function"&&(e=n,t=`source.${qe++}`),this._sources.push({id:t,query:e}),t}removeSource(n){this._sources=this.sources.filter(e=>e.id!==n&&e.query!==n)}addEntry(n){this.manualEntries.push(n)}removeEntry(n){this.manualEntries=this.manualEntries.filter(e=>e.id!==n)}get sources(){let n=this._sources;return this.allowGlobalConfigSources&&b().knowledgeBaseSources&&(n=n.concat(b().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(n=n.concat(this._windowSources)),n=n.filter(e=>!e.disabled),n}async search(n){V.debug(`Searching knowledge base for: ${n}`);let e=Date.now(),t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=n,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 c=>{try{let h=Date.now(),p=await c.query(n);return V.debug(`Source '${c.id}' took ${Date.now()-h}ms`),p||[]}catch(h){return V.warn(`Knowledge source '${c.id}' failed:`,h),[]}}))).flat();o=o.concat(t.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&b().knowledgeBase&&(o=o.concat(b().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);let s=new Map;for(let c of o)c.id&&s.set(c.id,(s.get(c.id)||0)+1);for(let[c,h]of s)if(h>1){V.warn(`Duplicate knowledge base item ID detected: '${c}' appears ${h} times. Adding suffixes to make them unique.`);let p=1,m=!0;for(let g of o)if(g.id===c){if(m){m=!1;continue}g.id=`${c}(${p})`,p++}}for(let c=0;c<o.length;c++){let h=o[c];h.id=h.id||`temp.${c}`,h._functionID=h.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let r=new ni({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});r.addAll(o);let u=r.search(n).map(c=>o.find(h=>h.id==c.id)).filter(Boolean),d=0;u=u.filter(c=>{if(c.isContext)return!0;let h=(c.content||"").length;return d+h>oi?!1:(d+=h,!0)});for(let c of o)c.isContext&&(u.find(h=>h.id===c.id)||u.push(c));return this.lastResults=u,C(this.ai,{event_type:"kb_search",value:u.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),V.debug("Found results:",u),u}getCachedEntry(n){return this.lastResults.find(e=>e.id==n||e._functionID==n)}registerSourceFromURL(n,e){e||(e=`external.${qe++}`),V.debug(`Registering remote knowledge base source: ${n}`);let t=[],i=[],o=!0,s=async(l,u)=>{V.debug(`Calling remote knowledge base action: ${l.id}`);let d={type:"action",userID:this.ai.userID,actionID:l.id,parameters:u},c=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let h=await c.json();return r(h.updateItems||[]),h.response},r=l=>{for(let u of l){if(!u.id){V.warn("KB item skipped since it has no ID.",u);continue}let d=t.find(c=>c.id==u.id);if(d){d.name=u.name||d.name||"",d.content=u.content||d.content||"",d.disabled=u.disabled??d.disabled,d.isContext=u.isContext??d.isContext,d.parameters=u.parameters||d.parameters||[],d.tags=u.tags||d.tags,d.type=u.type||d.type;continue}t.push({...u,action:c=>s(u,c)})}};this.registerSource(e,async l=>{if(o&&i.includes(l))return t;let u={type:"search",userID:this.ai?.userID||"",query:l},d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let c=await d.json();return o=!c.noCache,i.includes(l)||i.push(l),r(c.items),t})}clone(n){let e=new a(n);return e._sources=this._sources.slice(),e._windowSources=this._windowSources.slice(),e.manualEntries=this.manualEntries.slice(),e.allowGlobalConfigSources=this.allowGlobalConfigSources,e.allowWindowSources=this.allowWindowSources,e.allowRagSearch=this.allowRagSearch,e.ensureInternalKnowledge(),e}registerMCPSource(n){n.id||(n.id=`external.${qe++}`);let e=new Ee(n);return this.registerSource(n.id,t=>e.search(t)),e}};var Le=class{constructor(n){this.ai=n}async boolean(n){let e=await this.instruct({...n,instruction:`${n.instruction}
15
+ ${r}`}},{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:(n,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(!n.url||typeof n.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(n.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${n.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:(n,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(!n.path||typeof n.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(n.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"||!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:(n,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(!n.email_address||typeof n.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!n.subject||typeof n.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!n.body||typeof n.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(n.email_address),i=encodeURIComponent(n.subject),o=encodeURIComponent(n.body),r=`mailto:${t}?subject=${i}&body=${o}`;try{window.location.href=r}catch(s){throw new Error(`Failed to open email client: ${s instanceof Error?s.message:String(s)}`)}return`Email opened in default mail client. Recipient: ${n.email_address}, Subject: ${n.subject}`}}];import{Client as Jt}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as $t}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var Y={name:"@intelliweave/embedded",version:"2.2.84",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.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.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 Qt,ToolListChangedNotificationSchema as qt}from"@modelcontextprotocol/sdk/types.js";var I=new f("MCPKnowledgeClient"),ei="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",Ne=class{constructor(n){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=n}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(){I.debug("Connecting to MCP client");let n=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||ei));let i=new Jt({name:Y.name,version:Y.version}),o=new $t(e,{requestInit:{headers:t}});return await i.connect(o),I.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=n,n.onerror=e=>{I.error(`MCP client error: ${e.message}`)},n.onclose=()=>{I.debug("MCP client connection closed"),this.client=void 0},n.setNotificationHandler(Qt,e=>{e.params.level=="critical"?I.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?I.error(`[Server] ${e.params.data}`):e.params.level=="error"?I.error(`[Server] ${e.params.data}`):e.params.level=="warning"?I.warn(`[Server] ${e.params.data}`):e.params.level=="info"?I.info(`[Server] ${e.params.data}`):e.params.level=="debug"?I.debug(`[Server] ${e.params.data}`):I.log(`[Server] ${e.params.data}`)}),n.setNotificationHandler(qt,e=>{I.debug("Tool list changed",e),this.fetchTools()}),I.debug("Fetching tools from MCP server..."),await this.fetchTools(),n}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let n=[],e;for(;;){let o=await this.client.listTools({cursor:e});e=o.nextCursor;for(let r of o.tools||[])n.push(r);if(!o?.tools?.length||!e)break}let t=[],i=this.config.id||"mcp";for(let o of n){let r=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),s=`${i}_${o.name}`;t.push({id:s,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:r})}I.debug(`Fetched ${n.length} tools from MCP server.`),this.tools=n,this.iwActions=t}async search(n){if(n==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(n);return e=e.concat(t),this.lastSearchQuery=n,this.lastSearchResults=e,I.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(n){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(o=>o.name==this.config.searchToolName);if(!t)return I.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let i;if(t.inputSchema.required?.length==1){let o=t.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:n})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let o=Object.keys(t.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:n})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let r=i[o];e.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof r=="string"?r:JSON.stringify(r)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return e}async performToolCall(n,e){await this.connect(),I.debug(`Performing tool call for ${n} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:n,arguments:e});if(t.isError){let i=t.content?.[0]?.text||"Unknown error";throw I.error(`Error calling tool ${n}: ${i}`),new Error(`Error calling tool ${n}: ${i}`)}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 ti}from"uuid";var ii=new f("Statistics"),ge=[];async function C(a,n){let e={...n,event_id:ti(),event_date:new Date().toISOString(),sdk_version:Y.version,conversation_id:a?.conversationID||"",api_key:a?.apiKey||"",user_id:a?.userID||""};if(ge.push(e),!a||(await new Promise(i=>setTimeout(i,5e3)),ge.length===0))return;let t=ge.slice();ge.length=0;try{let i=await fetch(a.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){ii.warn("Failed to submit analytics event:",i),ge.push(...t);return}}var F=new f("KnowledgeBase"),oi=8*1024,Qe=1,Ae=class a{constructor(n){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=n,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(n=>n.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>ft(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(n,e){let t=n;return typeof n=="function"&&(e=n,t=`source.${Qe++}`),this._sources.push({id:t,query:e}),t}removeSource(n){this._sources=this.sources.filter(e=>e.id!==n&&e.query!==n)}addEntry(n){this.manualEntries.push(n)}removeEntry(n){this.manualEntries=this.manualEntries.filter(e=>e.id!==n)}get sources(){let n=this._sources;return this.allowGlobalConfigSources&&b().knowledgeBaseSources&&(n=n.concat(b().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(n=n.concat(this._windowSources)),n=n.filter(e=>!e.disabled),n}async search(n){F.debug(`Searching knowledge base for: ${n}`);let e=Date.now(),t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=n,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 d=>{try{let h=Date.now(),p=await d.query(n);return F.debug(`Source '${d.id}' took ${Date.now()-h}ms`),p||[]}catch(h){return F.warn(`Knowledge source '${d.id}' failed:`,h),[]}}))).flat();o=o.concat(t.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&b().knowledgeBase&&(o=o.concat(b().knowledgeBase)),o=o.filter(d=>d&&!d.disabled);let r=new Map;for(let d of o)d.id&&r.set(d.id,(r.get(d.id)||0)+1);for(let[d,h]of r)if(h>1){F.warn(`Duplicate knowledge base item ID detected: '${d}' appears ${h} times. Adding suffixes to make them unique.`);let p=1,m=!0;for(let g of o)if(g.id===d){if(m){m=!1;continue}g.id=`${d}(${p})`,p++}}for(let d=0;d<o.length;d++){let h=o[d];h.id=h.id||`temp.${d}`,h._functionID=h.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new ni({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let u=s.search(n).map(d=>o.find(h=>h.id==d.id)).filter(Boolean),c=0;u=u.filter(d=>{if(d.isContext)return!0;let h=(d.content||"").length;return c+h>oi?!1:(c+=h,!0)});for(let d of o)d.isContext&&(u.find(h=>h.id===d.id)||u.push(d));return this.lastResults=u,C(this.ai,{event_type:"kb_search",value:u.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),F.debug("Found results:",u),u}getCachedEntry(n){return this.lastResults.find(e=>e.id==n||e._functionID==n)}registerSourceFromURL(n,e){e||(e=`external.${Qe++}`),F.debug(`Registering remote knowledge base source: ${n}`);let t=[],i=[],o=!0,r=async(l,u)=>{F.debug(`Calling remote knowledge base action: ${l.id}`);let c={type:"action",userID:this.ai.userID,actionID:l.id,parameters:u},d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let h=await d.json();return s(h.updateItems||[]),h.response},s=l=>{for(let u of l){if(!u.id){F.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=>r(u,d)})}};this.registerSource(e,async l=>{if(o&&i.includes(l))return t;let u={type:"search",userID:this.ai?.userID||"",query:l},c=await fetch(n,{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,i.includes(l)||i.push(l),s(d.items),t})}clone(n){let e=new a(n);return e._sources=this._sources.slice(),e._windowSources=this._windowSources.slice(),e.manualEntries=this.manualEntries.slice(),e.allowGlobalConfigSources=this.allowGlobalConfigSources,e.allowWindowSources=this.allowWindowSources,e.allowRagSearch=this.allowRagSearch,e.ensureInternalKnowledge(),e}registerMCPSource(n){n.id||(n.id=`external.${Qe++}`);let e=new Ne(n);return this.registerSource(n.id,t=>e.search(t)),e}};var Le=class{constructor(n){this.ai=n}async boolean(n){let e=await this.instruct({...n,instruction:`${n.instruction}
16
16
 
17
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(n){let e=await this.instruct({...n,instruction:`${n.instruction}
18
18
 
@@ -29,9 +29,9 @@ Objects should have the following keys:
29
29
  ${n.extractions.map(i=>`- ${i.name} (${i.type}): ${i.description||"No description provided."}`).join(`
30
30
  `)}
31
31
  `,t=await this.instruct({...n,instruction:e});if(t=t.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),n.allowMultiple){let i=t.split(`
32
- `).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of i)try{o.push(JSON.parse(s))}catch(r){console.error("Failed to parse line as JSON:",s,r.message)}return o}else return[JSON.parse(t.trim())]}async generateMarkdown(n){return this.instruct({...n,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(n){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>n.instruction,n.callback&&e.addEventListener("output",t=>{n.callback(t.detail.message)}),n.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof n.data=="string"?n.data:JSON.stringify(n.data)).then(t=>t.text())}};function et(a){let n="",e=[],t=0;for(;t<a.length;){let i=a.indexOf("<[[",t);if(i===-1){n+=a.slice(t);break}n+=a.slice(t,i);let o=a.indexOf("]]>",i+3);if(o===-1)break;let s=a.slice(i,o+3),r=a.slice(i+3,o).trim(),l={raw:s,content:r};try{let u=JSON.parse(r);u&&typeof u=="object"&&!Array.isArray(u)&&(l.action=u)}catch{}e.push(l),t=o+3}return{visibleText:n,actions:e.flatMap(i=>i.action?[i.action]:[]),blocks:e}}function bt(a){return et(a).visibleText}var ee=class{constructor(n){this.messages=n}text(){return this.messages?.flatMap(n=>n.sections)?.filter(n=>n?.type=="text")?.map(n=>bt(n?.text||""))?.filter(n=>!!n)?.join(`
32
+ `).map(r=>r.trim()).filter(r=>!!r.trim()),o=[];for(let r of i)try{o.push(JSON.parse(r))}catch(s){console.error("Failed to parse line as JSON:",r,s.message)}return o}else return[JSON.parse(t.trim())]}async generateMarkdown(n){return this.instruct({...n,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(n){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>n.instruction,n.callback&&e.addEventListener("output",t=>{n.callback(t.detail.message)}),n.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof n.data=="string"?n.data:JSON.stringify(n.data)).then(t=>t.text())}};function qe(a){let n="",e=[],t=0;for(;t<a.length;){let i=a.indexOf("<[[",t);if(i===-1){n+=a.slice(t);break}n+=a.slice(t,i);let o=a.indexOf("]]>",i+3);if(o===-1)break;let r=a.slice(i,o+3),s=a.slice(i+3,o).trim(),l={raw:r,content:s};try{let u=JSON.parse(s);u&&typeof u=="object"&&!Array.isArray(u)&&(l.action=u)}catch{}e.push(l),t=o+3}return{visibleText:n,actions:e.flatMap(i=>i.action?[i.action]:[]),blocks:e}}function bt(a){return qe(a).visibleText}var oe=class{constructor(n){this.messages=n}text(){return this.messages?.flatMap(n=>n.sections)?.filter(n=>n?.type=="text")?.map(n=>bt(n?.text||""))?.filter(n=>!!n)?.join(`
33
33
 
34
- `)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((n,e)=>n+(e.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((n,e)=>n+(e.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((n,e)=>n+(e.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((n,e)=>n+(e.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(n=>n.sections||[])||[]}toolCalls(){return this.messages?.flatMap(n=>n.sections?.filter(e=>e.type=="tool_call")||[])||[]}toolResult(n){return this.messages?.map(e=>e.sections?.find(t=>t.type=="tool_result"&&t.toolCallInstanceID==n)).filter(e=>!!e)[0]||null}};var Ne=class{constructor(n){this.subagents=[];this.cachedSubagents={};this.ai=n}register(n){if(this.subagents.find(e=>e.id==n.id))throw new Error(`Sub-agent with ID ${n.id} already exists`);this.subagents.push(n),this.ai.knowledgeBase.registerSource("subagent:"+n.id,e=>[{type:"action",id:"ask:"+n.id,name:`Ask ${n.name||"subagent"}`,content:n.usageInstructions||`Use this tool to ask ${n.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(t,i)=>await this.runQuery(n,t.query)}])}remove(n){this.subagents=this.subagents.filter(e=>e.id!=n),this.ai.knowledgeBase.removeSource("subagent:"+n)}async runQuery(n,e){let t=n.apiKey||this.ai.apiKey,i=this.cachedSubagents[t];return i||(i=new Y,i.userID=this.ai.userID,await i.load(t,n.config),this.cachedSubagents[t]=i),i=i.clone(),i.knowledgeBase.allowGlobalConfigSources=!1,i.knowledgeBase.allowWindowSources=!1,n.clearExistingKnowledge&&i.knowledgeBase.reset(),i.knowledgeBase.allowRagSearch=!n.disableRagSearch,n.knowledge&&i.knowledgeBase.registerSource(n.knowledge),n.onAgentLoaded&&await n.onAgentLoaded(i),(await i.sendMessage(e)).text()}};var A=new f("Main"),wt=new Set,$=class $ extends EventTarget{constructor(){super(...arguments);this.conversationID=yt();this.knowledgeBase=new Ae(this);this.subAgents=new Ne(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new Le(this);this.userID=pt();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:$.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","embedded.suggestion - Add hidden follow-up suggestion buttons in the built-in UI","embedded.emoji - Trigger hidden emoji effects in the built-in UI","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.");t?.userID&&(this.userID=t.userID),t?.hubAPI&&(this.hubAPI=t.hubAPI);try{await Promise.all([(async()=>{A.debug("Loading configuration...");let i=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,userID:this.userID})});if(!i.ok){let o=`${i.status} ${i.statusText}`;try{let s=await i.json();s.error?o=s.error:s.message&&(o=s.message)}catch(s){A.debug("Could not parse error response body:",s)}throw new Error(`Failed to load configuration: ${o}`)}try{this.config=await i.json(),A.debug("Config loaded successfully:",this.config),t&&(this.config={...this.config,...t}),this.config&&A.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){A.error("Failed to parse JSON response:",o);try{let s=await i.clone().text();A.error("Raw response that failed parsing:",s)}catch{A.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let i=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!i.ok)throw new Error(`Failed to load VAD model: ${i.status} ${i.statusText}`);this.vadModel=await i.blob()}catch(i){A.warn(`Failed to load VAD model, some features will be unavailable. ${i.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let i of this.config.knowledge||[])i.url&&i.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:i.id,searchToolName:i.mcpSearchToolName,baseURL:i.url}):i.url&&this.knowledgeBase.registerSourceFromURL(i.url);for(let i of this.config.knowledge||[])i.entries?.length&&this.knowledgeBase.registerSource(i.id,()=>i.entries||[]);if(this.config.mcpServers)for(let i of this.config.mcpServers)this.knowledgeBase.registerMCPSource(i);for(let i of this.config.subagents||[])this.subAgents.register(i);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(i){throw A.warn("Failed to load:",i),this.error=i,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:i}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:i}})),i}}setModel(e){let t=this.models.find(o=>o.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let i={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let r=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(r?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(i):t.config.providerID==="anthropic"?this.currentModel=new Ce(i):this.currentModel=new Te(i),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=b().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,disabled:!this.knowledgeBase.allowRagSearch,data:ke(`
34
+ `)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((n,e)=>n+(e.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((n,e)=>n+(e.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((n,e)=>n+(e.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((n,e)=>n+(e.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(n=>n.sections||[])||[]}toolCalls(){return this.messages?.flatMap(n=>n.sections?.filter(e=>e.type=="tool_call")||[])||[]}toolResult(n){return this.messages?.map(e=>e.sections?.find(t=>t.type=="tool_result"&&t.toolCallInstanceID==n)).filter(e=>!!e)[0]||null}};var De=class{constructor(n){this.subagents=[];this.cachedSubagents={};this.ai=n}register(n){if(this.subagents.find(e=>e.id==n.id))throw new Error(`Sub-agent with ID ${n.id} already exists`);this.subagents.push(n),this.ai.knowledgeBase.registerSource("subagent:"+n.id,e=>[{type:"action",id:"ask:"+n.id,name:`Ask ${n.name||"subagent"}`,content:n.usageInstructions||`Use this tool to ask ${n.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(t,i)=>await this.runQuery(n,t.query)}])}remove(n){this.subagents=this.subagents.filter(e=>e.id!=n),this.ai.knowledgeBase.removeSource("subagent:"+n)}async runQuery(n,e){let t=n.apiKey||this.ai.apiKey,i=this.cachedSubagents[t];return i||(i=new U,i.userID=this.ai.userID,await i.load(t,n.config),this.cachedSubagents[t]=i),i=i.clone(),i.knowledgeBase.allowGlobalConfigSources=!1,i.knowledgeBase.allowWindowSources=!1,n.clearExistingKnowledge&&i.knowledgeBase.reset(),i.knowledgeBase.allowRagSearch=!n.disableRagSearch,n.knowledge&&i.knowledgeBase.registerSource(n.knowledge),n.onAgentLoaded&&await n.onAgentLoaded(i),(await i.sendMessage(e)).text()}};var A=new f("Main"),wt=new Set,Q=class Q extends EventTarget{constructor(){super(...arguments);this.conversationID=yt();this.knowledgeBase=new Ae(this);this.subAgents=new De(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new Le(this);this.userID=pt();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:Q.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","embedded.suggestion - Add hidden follow-up suggestion buttons in the built-in UI","embedded.emoji - Trigger hidden emoji effects in the built-in UI","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.");t?.userID&&(this.userID=t.userID),t?.hubAPI&&(this.hubAPI=t.hubAPI);try{await Promise.all([(async()=>{A.debug("Loading configuration...");let i=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,userID:this.userID})});if(!i.ok){let o=`${i.status} ${i.statusText}`;try{let r=await i.json();r.error?o=r.error:r.message&&(o=r.message)}catch(r){A.debug("Could not parse error response body:",r)}throw new Error(`Failed to load configuration: ${o}`)}try{this.config=await i.json(),A.debug("Config loaded successfully:",this.config),t&&(this.config={...this.config,...t}),this.config&&A.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){A.error("Failed to parse JSON response:",o);try{let r=await i.clone().text();A.error("Raw response that failed parsing:",r)}catch{A.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let i=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!i.ok)throw new Error(`Failed to load VAD model: ${i.status} ${i.statusText}`);this.vadModel=await i.blob()}catch(i){A.warn(`Failed to load VAD model, some features will be unavailable. ${i.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let i of this.config.knowledge||[])i.url&&i.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:i.id,searchToolName:i.mcpSearchToolName,baseURL:i.url}):i.url&&this.knowledgeBase.registerSourceFromURL(i.url);for(let i of this.config.knowledge||[])i.entries?.length&&this.knowledgeBase.registerSource(i.id,()=>i.entries||[]);if(this.config.mcpServers)for(let i of this.config.mcpServers)this.knowledgeBase.registerMCPSource(i);for(let i of this.config.subagents||[])this.subAgents.register(i);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(i){throw A.warn("Failed to load:",i),this.error=i,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:i}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:i}})),i}}setModel(e){let t=this.models.find(o=>o.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let i={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,r)=>{let s=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(s?.id||o,r)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(i):t.config.providerID==="anthropic"?this.currentModel=new Ee(i):this.currentModel=new Ce(i),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=b().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,disabled:!this.knowledgeBase.allowRagSearch,data:Se(`
35
35
  # RAG search
36
36
  Use the \`search\` tool proactively as much as possible to find missing information or tools.
37
37
  Use the \`search\` tool when you are unsure about specific details or actions to take.
@@ -39,20 +39,20 @@ ${n.extractions.map(i=>`- ${i.name} (${i.type}): ${i.description||"No descriptio
39
39
  If you're about to say "I don't have access..." or "I can't..." use the \`search\` tool first.
40
40
  `)}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,data:`# Knowledge Database${e.length==0?`
41
41
 
42
- (no items found)`:""}`});for(let i of e)if(i.type=="info"||i.type=="tour"||i.type=="input-event"){let o=ke(i.content),s=!0;if(i.attachments?.length)for(let r of i.attachments)r.url&&(s&&(o+=`
42
+ (no items found)`:""}`});for(let i of e)if(i.type=="info"||i.type=="tour"||i.type=="input-event"){let o=Se(i.content),r=!0;if(i.attachments?.length)for(let s of i.attachments)s.url&&(r&&(o+=`
43
43
 
44
44
  \`\`\`yaml
45
45
  attachments:
46
- `,s=!1),o+=`- name: "${r.name||""}"
47
- mimetype: "${r.mimeType||""}"
48
- url: "${r.url}"
49
- `);s||(o+="```\n"),this.currentModel.contextGroup.add({id:i.id,data:`## ${i.type}: ${i.name}
50
- ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="function"?i.disabled(this):i.disabled})}else if(i.type=="action"){let o={name:i._functionID,description:ke(i.content),params:ht(i.parameters||[{name:"value",type:"string",description:"Input"}]),callback:s=>this.toolRunKBAction(i,s),canRemove:!i.isContext,kbItem:i};this.currentModel.registerTool(o)}else continue;for(let i of this.lastKBItems)!i.isContext||!i.id||e.find(s=>s.id==i.id)||(this.currentModel.contextGroup.remove(i.id),i._functionID&&this.currentModel.toolGroup.remove(i._functionID));this.lastKBItems=e}processIncomingMessage(e,t){if(!t){let i=this.currentModel?.stats?.tokensUsed||0,o=e.reduce((s,r)=>s+(r.usage?.totalTokens||0),0);C(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:i}})}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(),wt.has(this.conversationID)||(wt.add(this.conversationID),C(this,{event_type:"session_start"})),C(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 i=Date.now(),o=await this.currentModel.sendMessage(e),s=new ee(o);(this._voiceTracker||A.debug.bind(A))(`LLM response took ${Date.now()-i}ms`);let l=this.currentModel.contextGroup.getAllAsString();l+=`
46
+ `,r=!1),o+=`- name: "${s.name||""}"
47
+ mimetype: "${s.mimeType||""}"
48
+ url: "${s.url}"
49
+ `);r||(o+="```\n"),this.currentModel.contextGroup.add({id:i.id,data:`## ${i.type}: ${i.name}
50
+ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="function"?i.disabled(this):i.disabled})}else if(i.type=="action"){let o={name:i._functionID,description:Se(i.content),params:ht(i.parameters||[{name:"value",type:"string",description:"Input"}]),callback:r=>this.toolRunKBAction(i,r),canRemove:!i.isContext,kbItem:i};this.currentModel.registerTool(o)}else continue;for(let i of this.lastKBItems)!i.isContext||!i.id||e.find(r=>r.id==i.id)||(this.currentModel.contextGroup.remove(i.id),i._functionID&&this.currentModel.toolGroup.remove(i._functionID));this.lastKBItems=e}processIncomingMessage(e,t){if(!t){let i=this.currentModel?.stats?.tokensUsed||0,o=e.reduce((r,s)=>r+(s.usage?.totalTokens||0),0);C(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:i}})}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(),wt.has(this.conversationID)||(wt.add(this.conversationID),C(this,{event_type:"session_start"})),C(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 i=Date.now(),o=await this.currentModel.sendMessage(e),r=new oe(o);(this._voiceTracker||A.debug.bind(A))(`LLM response took ${Date.now()-i}ms`);let l=this.currentModel.contextGroup.getAllAsString();l+=`
51
51
 
52
52
  === TOOLS ===
53
53
 
54
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 d of u.sections||[])if(d.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:d.text||""});else if(d.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:d.text||""});else if(d.type=="tool_call"){let c=s.toolResult(d.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:d.toolKbID||"",actionName:d.toolKbName||"",value:d.toolParameters,result:c?.toolErrorResponse||c?.toolSuccessResponse,isError:!!c?.toolErrorResponse})}else d.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let i=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()-i;return C(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()-i;throw C(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(b().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(i=>{A.debug("Failed to submit analytics event:",i)});this.activeAnalyticsPromises.push(t),t.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(i=>i!==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=yt(),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 $;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),e}get messages(){return this.currentModel?.messageGroup.items||[]}};$.version=O.version,$.builtInActionsVersion="1.2.0",A.debug(`Loaded: version=${O.version} builtInActionsVersion=${$.builtInActionsVersion}`);var Y=$;var L=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 i=document.createElement(this.tagName);for(let o in e)i.setAttribute(o,e[o]);return i.onBeforeCreate(),i.innerHTML=t,i}static add(e={},t=""){this.register();let i=o=>o.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;");return`<${this.tagName} ${Object.keys(e).map(o=>`${o}="${i(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,i){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,i)=>(this.getAttribute(t.toString())===i||(i?this.setAttribute(t.toString(),i):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,i)=>(this._state[t]=i,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}};L.observedAttributes=[],L.tagName="",L._isRegistered=!1;var vt='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 xt='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 Mt='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 fe=class extends L{constructor(){super(...arguments);this.html=()=>`
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=r.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 r}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let i=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:t,ai:this}}));let o=await e.action(t,this),r=Date.now()-i;return C(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:r,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,result:o}})),o}catch(o){let r=Date.now()-i;throw C(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:r,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,error:o}})),o}}submitAnalyticsEvent(e){if(b().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(i=>{A.debug("Failed to submit analytics event:",i)});this.activeAnalyticsPromises.push(t),t.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(i=>i!==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=yt(),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 Q;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),e}get messages(){return this.currentModel?.messageGroup.items||[]}};Q.version=Y.version,Q.builtInActionsVersion="1.2.0",A.debug(`Loaded: version=${Y.version} builtInActionsVersion=${Q.builtInActionsVersion}`);var U=Q;var L=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 i=document.createElement(this.tagName);for(let o in e)i.setAttribute(o,e[o]);return i.onBeforeCreate(),i.innerHTML=t,i}static add(e={},t=""){this.register();let i=o=>o.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;");return`<${this.tagName} ${Object.keys(e).map(o=>`${o}="${i(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,i){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,i)=>(this.getAttribute(t.toString())===i||(i?this.setAttribute(t.toString(),i):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,i)=>(this._state[t]=i,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}};L.observedAttributes=[],L.tagName="",L._isRegistered=!1;var vt='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 xt='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 Mt='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 fe=class extends L{constructor(){super(...arguments);this.html=()=>`
56
56
 
57
57
  <!-- Styling -->
58
58
  <style>
@@ -329,7 +329,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
329
329
  <!-- Loader bar -->
330
330
  <div id='loader'></div>
331
331
 
332
- `;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"),i=t.value?.trim();t.value="",i&&this.dispatchEvent(new CustomEvent("input-message",{detail:i}))}onLLMButtonClick(e){e.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onSendButtonClick(e){e.preventDefault();let t=this.child("input-field"),i=t.value?.trim();t.value="",i&&this.dispatchEvent(new CustomEvent("input-message",{detail:i}))}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,i=30,o=6,s=Math.round(t*(i-o)+o),r=document.createElement("div"),l=this.child("microphone-button"),u=l?l.offsetLeft+l.offsetWidth+8:62;r.posX=u,r.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(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)`;let i=this.offsetWidth||600;t.posX<i||(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()}};fe.observedAttributes=["loading","llmName","llmButtonVisible","textColor","layout"];var De='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 be=class extends L{constructor(){super(...arguments);this.html=()=>`
332
+ `;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"),i=t.value?.trim();t.value="",i&&this.dispatchEvent(new CustomEvent("input-message",{detail:i}))}onLLMButtonClick(e){e.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onSendButtonClick(e){e.preventDefault();let t=this.child("input-field"),i=t.value?.trim();t.value="",i&&this.dispatchEvent(new CustomEvent("input-message",{detail:i}))}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,i=30,o=6,r=Math.round(t*(i-o)+o),s=document.createElement("div"),l=this.child("microphone-button"),u=l?l.offsetLeft+l.offsetWidth+8:62;s.posX=u,s.style.cssText=`position: absolute; top: calc(50% - ${r}px/2); left: 0px; width: 6px; height: ${r}px; background-color: ${e}; border-radius: 3px; pointer-events: none; `,this.root?.appendChild(s),this.voiceAnimationPieces.push(s)}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)`;let i=this.offsetWidth||600;t.posX<i||(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()}};fe.observedAttributes=["loading","llmName","llmButtonVisible","textColor","layout"];var We='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 be=class extends L{constructor(){super(...arguments);this.html=()=>`
333
333
 
334
334
  <!-- Styling -->
335
335
  <style>
@@ -382,7 +382,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
382
382
  <!-- Logo -->
383
383
  <img id='root' />
384
384
 
385
- `;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||De;this._lastLogoSrc!=t&&(this._lastLogoSrc=t,e.src=t);let i=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(i){let o=window.visualViewport?.offsetTop||0,s=window.visualViewport?.offsetLeft||0,r=i.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+s)+"px",e.style.top=Math.round(r.y+r.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)}};be.observedAttributes=["logo","focusID"];import At from"rehype-external-links";import Lt from"rehype-format";import Nt from"rehype-stringify";import Dt from"remark-gfm";import Wt from"remark-parse";import Gt from"remark-rehype";var We=(function(a){if(a==null)return pi;if(typeof a=="function")return Ge(a);if(typeof a=="object")return Array.isArray(a)?ci(a):di(a);if(typeof a=="string")return ui(a);throw new Error("Expected function, string, or object as test")});function ci(a){let n=[],e=-1;for(;++e<a.length;)n[e]=We(a[e]);return Ge(t);function t(...i){let o=-1;for(;++o<n.length;)if(n[o].apply(this,i))return!0;return!1}}function di(a){let n=a;return Ge(e);function e(t){let i=t,o;for(o in a)if(i[o]!==n[o])return!1;return!0}}function ui(a){return Ge(n);function n(e){return e&&e.type===a}}function Ge(a){return n;function n(e,t,i){return!!(hi(e)&&a.call(this,e,typeof t=="number"?t:void 0,i||void 0))}}function pi(){return!0}function hi(a){return a!==null&&typeof a=="object"&&"type"in a}var It=[],tt=!0,Pe=!1,it="skip";function nt(a,n,e,t){let i;typeof n=="function"&&typeof e!="function"?(t=e,e=n):i=n;let o=We(i),s=t?-1:1;r(a,void 0,[])();function r(l,u,d){let c=l&&typeof l=="object"?l:{};if(typeof c.type=="string"){let p=typeof c.tagName=="string"?c.tagName:typeof c.name=="string"?c.name:void 0;Object.defineProperty(h,"name",{value:"node ("+(l.type+(p?"<"+p+">":""))+")"})}return h;function h(){let p=It,m,g,y;if((!n||o(l,u,d[d.length-1]||void 0))&&(p=mi(e(l,d)),p[0]===Pe))return p;if("children"in l&&l.children){let v=l;if(v.children&&p[0]!==it)for(g=(t?v.children.length:-1)+s,y=d.concat(v);g>-1&&g<v.children.length;){let M=v.children[g];if(m=r(M,g,y)(),m[0]===Pe)return m;g=typeof m[1]=="number"?m[1]:g+s}}return p}}}function mi(a){return Array.isArray(a)?a:typeof a=="number"?[tt,a]:a==null?It:[a]}function ot(a,n,e,t){let i,o,s;typeof n=="function"&&typeof e!="function"?(o=void 0,s=n,i=e):(o=n,s=e,i=t),nt(a,o,r,i);function r(l,u){let d=u[u.length-1],c=d?d.children.indexOf(l):void 0;return s(l,c,d)}}import{unified as Pt}from"unified";var ye=class extends L{constructor(){super(...arguments);this.html=()=>`
385
+ `;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||We;this._lastLogoSrc!=t&&(this._lastLogoSrc=t,e.src=t);let i=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(i){let o=window.visualViewport?.offsetTop||0,r=window.visualViewport?.offsetLeft||0,s=i.getBoundingClientRect();if(!s)return;e.classList.add("focused-mode"),e.style.width="128px",e.style.height="128px",e.style.left=Math.round(s.x+s.width/2-128/2+r)+"px",e.style.top=Math.round(s.y+s.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)}};be.observedAttributes=["logo","focusID"];import Nt from"rehype-external-links";import At from"rehype-format";import Lt from"rehype-stringify";import Dt from"remark-gfm";import Wt from"remark-parse";import Gt from"remark-rehype";var Ge=(function(a){if(a==null)return pi;if(typeof a=="function")return Pe(a);if(typeof a=="object")return Array.isArray(a)?di(a):ci(a);if(typeof a=="string")return ui(a);throw new Error("Expected function, string, or object as test")});function di(a){let n=[],e=-1;for(;++e<a.length;)n[e]=Ge(a[e]);return Pe(t);function t(...i){let o=-1;for(;++o<n.length;)if(n[o].apply(this,i))return!0;return!1}}function ci(a){let n=a;return Pe(e);function e(t){let i=t,o;for(o in a)if(i[o]!==n[o])return!1;return!0}}function ui(a){return Pe(n);function n(e){return e&&e.type===a}}function Pe(a){return n;function n(e,t,i){return!!(hi(e)&&a.call(this,e,typeof t=="number"?t:void 0,i||void 0))}}function pi(){return!0}function hi(a){return a!==null&&typeof a=="object"&&"type"in a}var It=[],et=!0,Ze=!1,tt="skip";function it(a,n,e,t){let i;typeof n=="function"&&typeof e!="function"?(t=e,e=n):i=n;let o=Ge(i),r=t?-1:1;s(a,void 0,[])();function s(l,u,c){let d=l&&typeof l=="object"?l:{};if(typeof d.type=="string"){let p=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(h,"name",{value:"node ("+(l.type+(p?"<"+p+">":""))+")"})}return h;function h(){let p=It,m,g,y;if((!n||o(l,u,c[c.length-1]||void 0))&&(p=mi(e(l,c)),p[0]===Ze))return p;if("children"in l&&l.children){let w=l;if(w.children&&p[0]!==tt)for(g=(t?w.children.length:-1)+r,y=c.concat(w);g>-1&&g<w.children.length;){let k=w.children[g];if(m=s(k,g,y)(),m[0]===Ze)return m;g=typeof m[1]=="number"?m[1]:g+r}}return p}}}function mi(a){return Array.isArray(a)?a:typeof a=="number"?[et,a]:a==null?It:[a]}function nt(a,n,e,t){let i,o,r;typeof n=="function"&&typeof e!="function"?(o=void 0,r=n,i=e):(o=n,r=e,i=t),it(a,o,s,i);function s(l,u){let c=u[u.length-1],d=c?c.children.indexOf(l):void 0;return r(l,d,c)}}import{unified as Pt}from"unified";var ye=class extends L{constructor(){super(...arguments);this.html=()=>`
386
386
 
387
387
  <!-- Styling -->
388
388
  <style>
@@ -469,7 +469,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
469
469
  <div class='llm-selector-item-icon' style="background-image: url('${t.icon}'); "></div>
470
470
  <div class='llm-selector-item-name'>${t.name}</div>
471
471
  <div class='llm-selector-item-provider'>${t.provider}</div>
472
- `,i.addEventListener("click",o=>{this.dispatchEvent(new CustomEvent("select",{detail:t.id}))}),e.appendChild(i)}}};ye.observedAttributes=["open"];var te=new f("ONNXModel"),R=class a{constructor(n){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=n,te.debug(`Model input parameters: ${n.inputNames.join(", ")}`),te.debug(`Model output parameters: ${n.outputNames.join(", ")}`)}static isSupported(){return!!a.lib}static async load(n){if(!a.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(te.debug("Loading ONNX runtime"),this.onnx=await a.lib()),te.debug(`Loading model: ${n}`);let e=await this.onnx.InferenceSession.create(n);return new a(e)}makeTensor(n,e,t=0){let i=1;for(let s of e)i*=s;let o;if(n=="float32")o=new a.onnx.Tensor(new Float32Array(i),e);else if(n=="int8")o=new a.onnx.Tensor(new Int8Array(i),e);else if(n=="int16")o=new a.onnx.Tensor(new Int16Array(i),e);else if(n=="int32")o=new a.onnx.Tensor(new Int32Array(i),e);else if(n=="int64")o=new a.onnx.Tensor(new BigInt64Array(i),e);else if(n=="uint8")o=new a.onnx.Tensor(new Uint8Array(i),e);else if(n=="uint16")o=new a.onnx.Tensor(new Uint16Array(i),e);else if(n=="uint32")o=new a.onnx.Tensor(new Uint32Array(i),e);else if(n=="uint64")o=new a.onnx.Tensor(new BigUint64Array(i),e);else throw new Error(`Invalid type: ${n}`);return t!==0&&(n=="int64"||n=="uint64")?o.data.fill(BigInt(t)):t!==0&&o.data.fill(t),o}registerConstant(n,e){if(!this.session.inputNames.includes(n))throw new Error(`Model does not have an input named: ${n}`);return this.constantTensors[n]=e,e}makeConstant(n,e,t,i=0){return this.registerConstant(n,this.makeTensor(e,t,i))}registerState(n,e,t){if(e||(e=n),!this.session.inputNames.includes(n))throw new Error(`Model does not have an input named: ${n}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[n]={outputName:e,tensor:t},t}makeState(n,e,t,i,o=0){return this.registerState(n,e,this.makeTensor(t,i,o))}async run(n={}){if(this._runActive&&this.ignoreIfBusy)return te.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)n[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)n[e]=this.constantTensors[e];try{let e=await this.session.run(n);for(let t in this.stateTensors){let i=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=i}return e}finally{this._runActive=!1}}resetState(){te.debug("Resetting state tensors");for(let n in this.stateTensors)this.stateTensors[n].tensor.data.fill(0)}};var kt="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZ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1hdDogJHt0aGlzLmZvcm1hdH1gKTtsZXQgYT10aGlzLnJlc2FtcGxlci5yZXNhbXBsZShyKTt0aGlzLmNodW5rcy5wdXNoKGEpfW5leHRGbG9hdCgpe2lmKCF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIDA7bGV0IHQ9dGhpcy5jaHVua3NbMF1bdGhpcy5jaHVua1Bvc2l0aW9uXTtyZXR1cm4gdGhpcy5jaHVua1Bvc2l0aW9uKyssdGhpcy5jaHVua1Bvc2l0aW9uPHRoaXMuY2h1bmtzWzBdLmxlbmd0aHx8KHRoaXMuY2h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var fi=new f("PCMPlayerNode"),ie=class extends AudioWorkletNode{constructor(e,t,i){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(!i||i!="int16"&&i!="float32")throw new Error(`Invalid format: ${i}`);this.sampleRate=t,this.format=i,this.port.onmessage=o=>this.onWorkletMessage(o),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:i})}static async registerModule(e){await e.audioWorklet.addModule(kt)}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:i,value:o}=await t.read();if(i||!o)break;this.feed(o)}}catch(t){fi.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 N=new f("ElevenLabs");function st(a,n,e="pcm_24000"){let t=[],i=Date.now(),o=!1,s,r;return{stream:new ReadableStream({start:c=>{s=c,r=new WebSocket(`wss://api.elevenlabs.io/v1/text-to-speech/${n}/stream-input?inactivity_timeout=120&output_format=${e}`),r.addEventListener("open",()=>{N.debug(`[at ${Date.now()-i}ms] WebSocket connected`),r.send(JSON.stringify({text:" ","xi-api-key":a}));for(let h of t)r.send(JSON.stringify({text:h}));t.length=0}),r.addEventListener("close",()=>{N.debug(`[at ${Date.now()-i}ms] WebSocket closed`),s?.close(),o=!0}),r.addEventListener("message",h=>{let p=JSON.parse(h.data);if(p.final){r.close(),s?.close();return}if(N.debug(`[at ${Date.now()-i}ms] Message received: ${p.audio?.length||0} bytes of audio data`),!p.audio)return;let m=Uint8Array.from(atob(p.audio),g=>g.charCodeAt(0));s?.enqueue(m)})},cancel:()=>{N.debug(`[at ${Date.now()-i}ms] Stream cancelled`),r?.close(),o=!0}}),sendText:c=>{c&&(N.debug(`[at ${Date.now()-i}ms] Sending text: "${c}"`),r?.readyState===WebSocket.OPEN?r.send(JSON.stringify({text:c})):t.push(c))},endText:()=>{r?.readyState===WebSocket.OPEN?r.send(JSON.stringify({text:""})):t.push("")},get isClosed(){return o}}}function St(a,n="pcm_16000",e=16e3,t="vad"){let i=[],o=Date.now(),s=!1,r,l;return{stream:new ReadableStream({start:async p=>{r=p;let m=await fetch("https://api.elevenlabs.io/v1/single-use-token/realtime_scribe",{method:"POST",headers:{"xi-api-key":a}});if(!m.ok)throw new Error(`Failed to generate single-use token: ${m.status} ${m.statusText}`);let g=await m.json(),y=g.token;if(!y)throw new Error(`No token found in response: ${JSON.stringify(g)}`);l=new WebSocket(`wss://api.elevenlabs.io/v1/speech-to-text/realtime?token=${encodeURIComponent(y)}&audio_format=${n}&commit_strategy=${t}`),l.addEventListener("open",()=>{N.debug(`[at ${Date.now()-o}ms] WebSocket connected`);for(let v of i)l.send(v);i.length=0}),l.addEventListener("close",()=>{N.debug(`[at ${Date.now()-o}ms] WebSocket closed`),r?.close(),s=!0}),l.addEventListener("message",v=>{let M=JSON.parse(v.data);M.message_type=="committed_transcript"?(N.debug(`[at ${Date.now()-o}ms] Committed transcript received: "${M.text}"`),r?.enqueue(M.text)):M.error&&(N.warn(`[at ${Date.now()-o}ms] Error received: ${M.error}`),r?.error(new Error(M.error)),l?.close(),s=!0)})},cancel:()=>{N.debug(`[at ${Date.now()-o}ms] Stream cancelled`),l?.close(),s=!0}}),sendAudio:p=>{let m=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:btoa(String.fromCharCode(...new Uint8Array(p))),commit:!1,sample_rate:e});N.debug(`[at ${Date.now()-o}ms] Sending audio: ${p.byteLength} bytes`),l?.readyState===WebSocket.OPEN?l.send(m):i.push(m)},commit:()=>{let p=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:e});l?.readyState===WebSocket.OPEN?l.send(p):i.push(p)},close:()=>{N.debug("Closing connection"),l?.close(),s=!0,setTimeout(()=>{r?.close()},1e3)},get isClosed(){return s}}}var Ze=new f("SpeechOutput"),Tt=.5,bi=.8,Re=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,i=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)}i||this.processedMessages.clear()}}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let i of this.analyserBuffer)e+=i*i;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 Ze.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-${yi++}`;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=st(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),this.preemptiveConnection&&(this._elevenLabsPrecachedConnection=st(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=bi);let i=this.ai?._voiceTracker||Ze.timer(`${this.ai.config.voice.providerID} voice`);i(`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 ie(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",l=>{let u=l;i(`PCM stream ${u.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!u.detail.interrupted&&(this.currentPlayer=void 0)});let s=Date.now(),r=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){Ze.warn(`Failed to generate voice sample: ${l.status} ${l.statusText}`);return}r=l.body}else if(this.ai.config.voice.providerID=="elevenlabs"){let l=this._getElevenLabsConnection();l.sendText(e),l.endText(),r=l.stream}else{Ze.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}i(`Received response in ${Date.now()-s}ms`),this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),i("Playing PCM stream"),await o.play(r),i("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=Tt);let i=400;e.gain.linearRampToValueAtTime(0,i/1e3),await new Promise(o=>setTimeout(o,i+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=Tt)}},yi=1;function Xe(a,n){let e=n.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 i=1,o=32,s=i*o/8,r=a*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,i,!0),t.setUint32(24,a,!0),t.setUint32(28,r,!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,...n],"audio.wav",{type:"audio/wav"})}var Ct="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwL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2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var ne=class extends AudioWorkletNode{constructor(e,t,i,o){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=i;let s=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!s.includes(i))throw new Error(`Invalid format ${i}, must be one of: ${s.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=r=>this.onWorkletMessage(r),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:i,bufferSize:o})}static async registerModule(e){await e.audioWorklet.addModule(Ct)}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 rt=16e3,Be=256,oe=8,we=new f("VoiceDetectionNode"),ve=class ve extends ne{constructor(e){super(e,rt,"float32",Be*oe);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(!ve.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 rt}get numberOfSamples(){return Be}get numberOfSampleChunks(){return oe}get outputBufferSize(){return Be*oe}get isModelLoaded(){return!!this.vad}async loadModel(){we.debug("Loading VAD model"),this.vad=await R.load(ve.vadModelURL),this.vad.ignoreIfBusy=!0,we.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],rt),this.vad.makeState("h","hn","float32",[2,oe,64]),this.vad.makeState("c","cn","float32",[2,oe,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new R.onnx.Tensor(e,[oe,Be])});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 i=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>i;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(),we.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(),we.debug("Stopped speaking after timeout")),!o){let s=Date.now();s>this.nextVadReset&&(this.nextVadReset=s+5e3,this.vad.resetState())}}catch(t){we.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};ve.vadModelURL="";var se=ve;var Et=new f("VoiceChunkOutputNode"),F=class extends se{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){Et.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((i,o)=>i+o.length,0);Et.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 je=new f("OpenAITranscriptionNode"),_e=class extends F{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=je.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let i=Xe(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let s=new FormData;s.append("file",i),s.append("model","whisper-1"),s.append("response_format","text");let r=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s,signal:this.lastRequestAbortController.signal});if(!r.ok)throw new Error(`Failed to generate voice sample: ${r.status} ${r.statusText}`);t("Response received"),o=await r.text(),t("Content received: "+o),this.lastRequestAbortController=void 0}catch(s){je.error(`Failed to transcribe speech: ${s.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return je.debug("Transcription complete, but no text was found");je.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(e){}};var ze=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 P=new f("IntelliWeaveTranscriptionNode"),vi="wss://speech.intelliweave.ai/api/v1/transcribe",Ve=class Ve extends F{constructor(e,t){super(e);this.apiAddress=vi;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(P.debug("Opening WebSocket connection"),this.ws=new ze(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=()=>{P.debug("WebSocket connection opened")},this.ws.addEventListener("message",i=>{let o=JSON.parse(i.data);if(o.error)return P.warn("Error: "+o.error);if(o.type!="transcription")return P.warn("Invalid response type",o);if(o.streaming&&!o.final)return P.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return P.warn(`Empty transcription (${o.processingTime}ms)`);P.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",i=>P.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{P.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),Ve.debugExportWav){let t=Xe(this.sampleRate,e),i=document.createElement("a");i.href=URL.createObjectURL(t),i.download="recording.wav",i.click()}}onVoiceTranscription(e){}onSocketClose(){P.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};Ve.debugExportWav=!1;var Oe=Ve;var re=new f("ElevenLabsTranscriptionNode"),Ye=class extends F{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,re.debug(`Opening connection. sampleRate: ${this.sampleRate} format=${this.format}`),this.connection=St(this.apiKey,"pcm_"+this.sampleRate,this.sampleRate,"manual"),this.startReading(this.connection),this.connection.sendAudio(t.buffer)):this.connection.sendAudio(t.buffer);let i=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{re.debug("Shutting down WebSocket connection"),this.connection?.close(),this.connection=void 0},i)}async startReading(e){let t=e.stream.getReader();try{for(;;){let{value:i,done:o}=await t.read();if(o){re.debug("Stream closed");break}if(!i?.trim()){re.warn("Empty transcription received");continue}this.isTranscribing=!1,re.debug(`Transcription: ${i}`),this.onVoiceTranscription(i),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:i}}))}}catch(i){re.error(`Failed to read transcription stream: ${i.message}`),this.connection==e&&(this.connection=void 0);return}}async onVoiceEnd(e){this.connection?.commit()}onVoiceTranscription(e){}};var at=new f("SpeechRecognition"),Fe=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e}get isSupported(){if(!R.lib||!this.ai?.vadModel||!z().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),se.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new _e(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 Oe(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",t=>{this.ai._voiceTracker=at.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),C(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 i=this.recordingStartTime?Date.now()-this.recordingStartTime:0;C(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:i}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),C(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){at.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 i of this.analyserBuffer)e+=i*i;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;at.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 Ue=new f("AudioSystem"),U=class a{constructor(n){this.locks=[];if(!n)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=n,this.ai.audio=this,this.speechRecognition=new Fe(this.ai),this.speechOutput=new Re(this.ai)}static get isSupported(){return!(!R.lib||!z().AudioWorkletNode)}static async registerModules(n){await Promise.all([ie.registerModule(n),ne.registerModule(n)])}async beginAccess(n){Ue.debug(`Began access for: ${n}`),this.locks.includes(n)||this.locks.push(n),!this.context&&(Ue.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await a.registerModules(this.context))}endAccess(n){Ue.debug(`Ended access for: ${n}`),this.locks=this.locks.filter(e=>e!=n),!this.locks.length&&(Ue.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var E=new f("Embed"),ae=class extends L{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this._handledEmbeddedActionBlocks=new Map;this._returnToCollapsedOnSwipeClose=!1;this._suppressNextContainerClick=!1;this._previousFullscreenState=!1;this.html=()=>`
472
+ `,i.addEventListener("click",o=>{this.dispatchEvent(new CustomEvent("select",{detail:t.id}))}),e.appendChild(i)}}};ye.observedAttributes=["open"];var re=new f("ONNXModel"),X=class a{constructor(n){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=n,re.debug(`Model input parameters: ${n.inputNames.join(", ")}`),re.debug(`Model output parameters: ${n.outputNames.join(", ")}`)}static isSupported(){return!!a.lib}static async load(n){if(!a.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(re.debug("Loading ONNX runtime"),this.onnx=await a.lib()),re.debug(`Loading model: ${n}`);let e=await this.onnx.InferenceSession.create(n);return new a(e)}makeTensor(n,e,t=0){let i=1;for(let r of e)i*=r;let o;if(n=="float32")o=new a.onnx.Tensor(new Float32Array(i),e);else if(n=="int8")o=new a.onnx.Tensor(new Int8Array(i),e);else if(n=="int16")o=new a.onnx.Tensor(new Int16Array(i),e);else if(n=="int32")o=new a.onnx.Tensor(new Int32Array(i),e);else if(n=="int64")o=new a.onnx.Tensor(new BigInt64Array(i),e);else if(n=="uint8")o=new a.onnx.Tensor(new Uint8Array(i),e);else if(n=="uint16")o=new a.onnx.Tensor(new Uint16Array(i),e);else if(n=="uint32")o=new a.onnx.Tensor(new Uint32Array(i),e);else if(n=="uint64")o=new a.onnx.Tensor(new BigUint64Array(i),e);else throw new Error(`Invalid type: ${n}`);return t!==0&&(n=="int64"||n=="uint64")?o.data.fill(BigInt(t)):t!==0&&o.data.fill(t),o}registerConstant(n,e){if(!this.session.inputNames.includes(n))throw new Error(`Model does not have an input named: ${n}`);return this.constantTensors[n]=e,e}makeConstant(n,e,t,i=0){return this.registerConstant(n,this.makeTensor(e,t,i))}registerState(n,e,t){if(e||(e=n),!this.session.inputNames.includes(n))throw new Error(`Model does not have an input named: ${n}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[n]={outputName:e,tensor:t},t}makeState(n,e,t,i,o=0){return this.registerState(n,e,this.makeTensor(t,i,o))}async run(n={}){if(this._runActive&&this.ignoreIfBusy)return re.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)n[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)n[e]=this.constantTensors[e];try{let e=await this.session.run(n);for(let t in this.stateTensors){let i=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=i}return e}finally{this._runActive=!1}}resetState(){re.debug("Resetting state tensors");for(let n in this.stateTensors)this.stateTensors[n].tensor.data.fill(0)}};var kt="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlb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YT10aGlzLnJlc2FtcGxlci5yZXNhbXBsZShyKTt0aGlzLmNodW5rcy5wdXNoKGEpfW5leHRGbG9hdCgpe2lmKCF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIDA7bGV0IHQ9dGhpcy5jaHVua3NbMF1bdGhpcy5jaHVua1Bvc2l0aW9uXTtyZXR1cm4gdGhpcy5jaHVua1Bvc2l0aW9uKyssdGhpcy5jaHVua1Bvc2l0aW9uPHRoaXMuY2h1bmtzWzBdLmxlbmd0aHx8KHRoaXMuY2h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var fi=new f("PCMPlayerNode"),se=class extends AudioWorkletNode{constructor(e,t,i){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(!i||i!="int16"&&i!="float32")throw new Error(`Invalid format: ${i}`);this.sampleRate=t,this.format=i,this.port.onmessage=o=>this.onWorkletMessage(o),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:i})}static async registerModule(e){await e.audioWorklet.addModule(kt)}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:i,value:o}=await t.read();if(i||!o)break;this.feed(o)}}catch(t){fi.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 D=new f("ElevenLabs");function ot(a,n,e="pcm_24000"){let t=[],i=Date.now(),o=!1,r,s;return{stream:new ReadableStream({start:d=>{r=d,s=new WebSocket(`wss://api.elevenlabs.io/v1/text-to-speech/${n}/stream-input?inactivity_timeout=120&output_format=${e}`),s.addEventListener("open",()=>{D.debug(`[at ${Date.now()-i}ms] WebSocket connected`),s.send(JSON.stringify({text:" ","xi-api-key":a}));for(let h of t)s.send(JSON.stringify({text:h}));t.length=0}),s.addEventListener("close",()=>{D.debug(`[at ${Date.now()-i}ms] WebSocket closed`),r?.close(),o=!0}),s.addEventListener("message",h=>{let p=JSON.parse(h.data);if(p.final){s.close(),r?.close();return}if(D.debug(`[at ${Date.now()-i}ms] Message received: ${p.audio?.length||0} bytes of audio data`),!p.audio)return;let m=Uint8Array.from(atob(p.audio),g=>g.charCodeAt(0));r?.enqueue(m)})},cancel:()=>{D.debug(`[at ${Date.now()-i}ms] Stream cancelled`),s?.close(),o=!0}}),sendText:d=>{d&&(D.debug(`[at ${Date.now()-i}ms] Sending text: "${d}"`),s?.readyState===WebSocket.OPEN?s.send(JSON.stringify({text:d})):t.push(d))},endText:()=>{s?.readyState===WebSocket.OPEN?s.send(JSON.stringify({text:""})):t.push("")},get isClosed(){return o}}}function St(a,n="pcm_16000",e=16e3,t="vad"){let i=[],o=Date.now(),r=!1,s,l;return{stream:new ReadableStream({start:async p=>{s=p;let m=await fetch("https://api.elevenlabs.io/v1/single-use-token/realtime_scribe",{method:"POST",headers:{"xi-api-key":a}});if(!m.ok)throw new Error(`Failed to generate single-use token: ${m.status} ${m.statusText}`);let g=await m.json(),y=g.token;if(!y)throw new Error(`No token found in response: ${JSON.stringify(g)}`);l=new WebSocket(`wss://api.elevenlabs.io/v1/speech-to-text/realtime?token=${encodeURIComponent(y)}&audio_format=${n}&commit_strategy=${t}`),l.addEventListener("open",()=>{D.debug(`[at ${Date.now()-o}ms] WebSocket connected`);for(let w of i)l.send(w);i.length=0}),l.addEventListener("close",()=>{D.debug(`[at ${Date.now()-o}ms] WebSocket closed`),s?.close(),r=!0}),l.addEventListener("message",w=>{let k=JSON.parse(w.data);k.message_type=="committed_transcript"?(D.debug(`[at ${Date.now()-o}ms] Committed transcript received: "${k.text}"`),s?.enqueue(k.text)):k.error&&(D.warn(`[at ${Date.now()-o}ms] Error received: ${k.error}`),s?.error(new Error(k.error)),l?.close(),r=!0)})},cancel:()=>{D.debug(`[at ${Date.now()-o}ms] Stream cancelled`),l?.close(),r=!0}}),sendAudio:p=>{let m=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:btoa(String.fromCharCode(...new Uint8Array(p))),commit:!1,sample_rate:e});D.debug(`[at ${Date.now()-o}ms] Sending audio: ${p.byteLength} bytes`),l?.readyState===WebSocket.OPEN?l.send(m):i.push(m)},commit:()=>{let p=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:e});l?.readyState===WebSocket.OPEN?l.send(p):i.push(p)},close:()=>{D.debug("Closing connection"),l?.close(),r=!0,setTimeout(()=>{s?.close()},1e3)},get isClosed(){return r}}}var Re=new f("SpeechOutput"),Tt=.5,bi=.8,Xe=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,i=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 r of o.sections||[])r.type=="text"&&r.text&&this.speak(r.text)}i||this.processedMessages.clear()}}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let i of this.analyserBuffer)e+=i*i;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 Re.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-${yi++}`;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=ot(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),this.preemptiveConnection&&(this._elevenLabsPrecachedConnection=ot(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=bi);let i=this.ai?._voiceTracker||Re.timer(`${this.ai.config.voice.providerID} voice`);i(`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 se(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",l=>{let u=l;i(`PCM stream ${u.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!u.detail.interrupted&&(this.currentPlayer=void 0)});let r=Date.now(),s=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){Re.warn(`Failed to generate voice sample: ${l.status} ${l.statusText}`);return}s=l.body}else if(this.ai.config.voice.providerID=="elevenlabs"){let l=this._getElevenLabsConnection();l.sendText(e),l.endText(),s=l.stream}else{Re.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}i(`Received response in ${Date.now()-r}ms`),this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),i("Playing PCM stream"),await o.play(s),i("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=Tt);let i=400;e.gain.linearRampToValueAtTime(0,i/1e3),await new Promise(o=>setTimeout(o,i+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=Tt)}},yi=1;function Be(a,n){let e=n.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 i=1,o=32,r=i*o/8,s=a*r;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,i,!0),t.setUint32(24,a,!0),t.setUint32(28,s,!0),t.setUint16(32,r,!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,...n],"audio.wav",{type:"audio/wav"})}var Ct="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5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3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var ae=class extends AudioWorkletNode{constructor(e,t,i,o){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=i;let r=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!r.includes(i))throw new Error(`Invalid format ${i}, must be one of: ${r.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=s=>this.onWorkletMessage(s),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:i,bufferSize:o})}static async registerModule(e){await e.audioWorklet.addModule(Ct)}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 rt=16e3,je=256,le=8,we=new f("VoiceDetectionNode"),ve=class ve extends ae{constructor(e){super(e,rt,"float32",je*le);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(!ve.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 rt}get numberOfSamples(){return je}get numberOfSampleChunks(){return le}get outputBufferSize(){return je*le}get isModelLoaded(){return!!this.vad}async loadModel(){we.debug("Loading VAD model"),this.vad=await X.load(ve.vadModelURL),this.vad.ignoreIfBusy=!0,we.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],rt),this.vad.makeState("h","hn","float32",[2,le,64]),this.vad.makeState("c","cn","float32",[2,le,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new X.onnx.Tensor(e,[le,je])});if(!t)return;this.currentProbability=0;for(let r=0;r<t.output.data.length;r++)t.output.data[r]>this.currentProbability&&(this.currentProbability=t.output.data[r]);let i=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>i;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(),we.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(),we.debug("Stopped speaking after timeout")),!o){let r=Date.now();r>this.nextVadReset&&(this.nextVadReset=r+5e3,this.vad.resetState())}}catch(t){we.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};ve.vadModelURL="";var de=ve;var Et=new f("VoiceChunkOutputNode"),K=class extends de{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){Et.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((i,o)=>i+o.length,0);Et.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 _e=new f("OpenAITranscriptionNode"),ze=class extends K{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=_e.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let i=Be(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let r=new FormData;r.append("file",i),r.append("model","whisper-1"),r.append("response_format","text");let s=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:r,signal:this.lastRequestAbortController.signal});if(!s.ok)throw new Error(`Failed to generate voice sample: ${s.status} ${s.statusText}`);t("Response received"),o=await s.text(),t("Content received: "+o),this.lastRequestAbortController=void 0}catch(r){_e.error(`Failed to transcribe speech: ${r.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return _e.debug("Transcription complete, but no text was found");_e.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(e){}};var Oe=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 P=new f("IntelliWeaveTranscriptionNode"),vi="wss://speech.intelliweave.ai/api/v1/transcribe",Ye=class Ye extends K{constructor(e,t){super(e);this.apiAddress=vi;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(P.debug("Opening WebSocket connection"),this.ws=new Oe(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=()=>{P.debug("WebSocket connection opened")},this.ws.addEventListener("message",i=>{let o=JSON.parse(i.data);if(o.error)return P.warn("Error: "+o.error);if(o.type!="transcription")return P.warn("Invalid response type",o);if(o.streaming&&!o.final)return P.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return P.warn(`Empty transcription (${o.processingTime}ms)`);P.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",i=>P.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{P.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),Ye.debugExportWav){let t=Be(this.sampleRate,e),i=document.createElement("a");i.href=URL.createObjectURL(t),i.download="recording.wav",i.click()}}onVoiceTranscription(e){}onSocketClose(){P.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};Ye.debugExportWav=!1;var Ve=Ye;var ce=new f("ElevenLabsTranscriptionNode"),Fe=class extends K{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,ce.debug(`Opening connection. sampleRate: ${this.sampleRate} format=${this.format}`),this.connection=St(this.apiKey,"pcm_"+this.sampleRate,this.sampleRate,"manual"),this.startReading(this.connection),this.connection.sendAudio(t.buffer)):this.connection.sendAudio(t.buffer);let i=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{ce.debug("Shutting down WebSocket connection"),this.connection?.close(),this.connection=void 0},i)}async startReading(e){let t=e.stream.getReader();try{for(;;){let{value:i,done:o}=await t.read();if(o){ce.debug("Stream closed");break}if(!i?.trim()){ce.warn("Empty transcription received");continue}this.isTranscribing=!1,ce.debug(`Transcription: ${i}`),this.onVoiceTranscription(i),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:i}}))}}catch(i){ce.error(`Failed to read transcription stream: ${i.message}`),this.connection==e&&(this.connection=void 0);return}}async onVoiceEnd(e){this.connection?.commit()}onVoiceTranscription(e){}};var st=new f("SpeechRecognition"),Ue=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e}get isSupported(){if(!X.lib||!this.ai?.vadModel||!V().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey)){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),de.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new ze(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):this.ai?.config?.transcription?.providerID=="elevenlabs"?(this.voiceDetection=new Fe(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new Ve(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=st.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),C(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 i=this.recordingStartTime?Date.now()-this.recordingStartTime:0;C(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:i}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),C(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){st.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 i of this.analyserBuffer)e+=i*i;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;st.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 Ke=new f("AudioSystem"),H=class a{constructor(n){this.locks=[];if(!n)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=n,this.ai.audio=this,this.speechRecognition=new Ue(this.ai),this.speechOutput=new Xe(this.ai)}static get isSupported(){return!(!X.lib||!V().AudioWorkletNode)}static async registerModules(n){await Promise.all([se.registerModule(n),ae.registerModule(n)])}async beginAccess(n){Ke.debug(`Began access for: ${n}`),this.locks.includes(n)||this.locks.push(n),!this.context&&(Ke.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await a.registerModules(this.context))}endAccess(n){Ke.debug(`Ended access for: ${n}`),this.locks=this.locks.filter(e=>e!=n),!this.locks.length&&(Ke.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var E=new f("Embed"),ue=class extends L{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this._handledEmbeddedActionBlocks=new Map;this._returnToCollapsedOnSwipeClose=!1;this._suppressNextContainerClick=!1;this._previousFullscreenState=!1;this.html=()=>`
473
473
 
474
474
  <!-- Styling -->
475
475
  <style>
@@ -1278,6 +1278,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
1278
1278
  flex-direction: unset;
1279
1279
  gap: 10px;
1280
1280
  }
1281
+
1281
1282
  #root.container-mode #web-weaver-embed-inner {
1282
1283
  flex: 1 1 auto;
1283
1284
  min-height: 0;
@@ -1549,6 +1550,21 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
1549
1550
  overflow: hidden;
1550
1551
  text-overflow: ellipsis;
1551
1552
  }
1553
+ #root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner {
1554
+ flex: 1 1 auto;
1555
+ min-height: 0;
1556
+ max-height: none;
1557
+ height: auto;
1558
+ overflow-x: hidden;
1559
+ overflow-y: auto;
1560
+ width: 100%;
1561
+ max-width: none;
1562
+ margin: 2px;
1563
+ padding: 12px;
1564
+ align-content: start;
1565
+ flex-direction: unset;
1566
+ gap: 10px;
1567
+ }
1552
1568
  }
1553
1569
 
1554
1570
  </style>
@@ -1621,7 +1637,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
1621
1637
 
1622
1638
  </div>
1623
1639
 
1624
- `;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastFontFamily="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._lastBrandName="";this._isProcessing=!1;this.ai=new Y,U.isSupported&&(this.ai.audio=new U(this.ai))}onCreate(){b().embed&&E.warn("Only one <web-weaver-embed> element should be on the page."),b().embed=this;let e=b();E.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(E.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.layout&&!this.attr.layout&&(E.debug("[WebWeaverEmbed] Setting layout from client config:",e.layout),this.attr.layout=e.layout),e.positioningMode&&!this.attr.positioningMode&&(E.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(E.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(E.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(E.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(E.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),E.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("dock-main").addEventListener("click",o=>this.onDockOpenClick(o)),this.child("dock-collapse").addEventListener("click",o=>this.onDockCollapseClick(o)),this.child("collapsed-tab").addEventListener("click",o=>this.onCollapsedOpenClick(o)),this.child("panel-fullscreen").addEventListener("click",o=>this.onPanelFullscreenClick(o)),this.child("panel-close").addEventListener("click",o=>this.onPanelCloseClick(o)),this.child("collapsed-tab").addEventListener("pointerdown",o=>this.onSwipePointerDown(o)),this.child("collapsed-tab").addEventListener("pointerup",o=>this.onCollapsedSwipePointerUp(o)),this.child("dock-main").addEventListener("pointerdown",o=>this.onSwipePointerDown(o)),this.child("dock-main").addEventListener("pointerup",o=>this.onDockSwipePointerUp(o)),this.child("root").addEventListener("pointerdown",o=>this.onSwipePointerDown(o)),this.child("root").addEventListener("pointerup",o=>this.onPanelSwipePointerUp(o)),this.child("root").addEventListener("pointercancel",o=>this.onSwipePointerCancel()),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:"_iw_image_instructions",type:"info",name:"Using Images",content:`
1640
+ `;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastFontFamily="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._lastBrandName="";this._lastBrandNameColor="";this._isProcessing=!1;this.ai=new U,H.isSupported&&(this.ai.audio=new H(this.ai))}onCreate(){b().embed&&E.warn("Only one <web-weaver-embed> element should be on the page."),b().embed=this;let e=b();E.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(E.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.layout&&!this.attr.layout&&(E.debug("[WebWeaverEmbed] Setting layout from client config:",e.layout),this.attr.layout=e.layout),e.positioningMode&&!this.attr.positioningMode&&(E.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(E.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(E.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(E.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(E.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),E.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("dock-main").addEventListener("click",o=>this.onDockOpenClick(o)),this.child("dock-collapse").addEventListener("click",o=>this.onDockCollapseClick(o)),this.child("collapsed-tab").addEventListener("click",o=>this.onCollapsedOpenClick(o)),this.child("panel-fullscreen").addEventListener("click",o=>this.onPanelFullscreenClick(o)),this.child("panel-close").addEventListener("click",o=>this.onPanelCloseClick(o)),this.child("collapsed-tab").addEventListener("pointerdown",o=>this.onSwipePointerDown(o)),this.child("collapsed-tab").addEventListener("pointerup",o=>this.onCollapsedSwipePointerUp(o)),this.child("dock-main").addEventListener("pointerdown",o=>this.onSwipePointerDown(o)),this.child("dock-main").addEventListener("pointerup",o=>this.onDockSwipePointerUp(o)),this.child("root").addEventListener("pointerdown",o=>this.onSwipePointerDown(o)),this.child("root").addEventListener("pointerup",o=>this.onPanelSwipePointerUp(o)),this.child("root").addEventListener("pointercancel",o=>this.onSwipePointerCancel()),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:"_iw_image_instructions",type:"info",name:"Using Images",content:`
1625
1641
  You can display images in Markdown format, example: ![filename](url)
1626
1642
  Image URLs must be absolute. When using an image URL from the knowledge base, include all parameters.`,isContext:!0});let i=this.attr.apiKey||b().apiKey;if(!i)return E.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(i).then(o=>{this.config=o.config,b().introductionMessage=this.config.introductionMessage,b().analytics=this.config.analytics!==void 0?!!this.config.analytics:b().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.updateBrandingFor(this.config.managedBy),this.ai.knowledgeBase.addEntry({id:"_iw_suggestion_action_instructions",type:"info",name:"Suggestion buttons",content:`
1627
1643
  Suggest follow-up responses by embedding standalone action blocks: <[[ {"action":"suggestion","text":"Show me pricing"} ]]>
@@ -1633,9 +1649,9 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
1633
1649
  The block is hidden from the user.
1634
1650
  Use this sparingly for celebration, confirmation, delight, or matching user emotion.
1635
1651
  Only use one emoji character or a short emoji sequence.
1636
- Continue writing normal visible text outside the block.`,isContext:!0,disabled:!this.ai.flags.allowEmojiActions}),this.resetConversation()}).catch(o=>{E.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");if(s){let r=o?.message||o?.toString()||"Unknown error";s.innerHTML=`<div class="output" style="padding: 20px;"><span style="display: inline-block; background-color: #fee; color: #c00; padding: 8px 12px; border-radius: 6px; border: 1px solid #fcc;">${r}</span></div>`}})}applyPersonaColorVariants(e,t,i){let o=this.parseColorToRGB(i),s=this.parseColorToRGB(t);if(!s&&!o){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.removeProperty("--intelliweave-assistant-bubble-border"),e.style.removeProperty("--intelliweave-user-bubble-bg"),e.style.removeProperty("--intelliweave-user-bubble-border"),e.style.removeProperty("--intelliweave-suggestion-button-bg"),e.style.removeProperty("--intelliweave-suggestion-button-hover-bg"),e.style.removeProperty("--intelliweave-suggestion-button-border"),e.style.removeProperty("--intelliweave-suggestion-button-hover-border"),e.style.removeProperty("--intelliweave-suggestion-button-text"),e.style.removeProperty("--intelliweave-interaction-bg"),e.style.removeProperty("--intelliweave-fullscreen-header-bg"),e.style.removeProperty("--intelliweave-fullscreen-input-section-bg"),e.style.removeProperty("--intelliweave-input-field-bg"),e.style.removeProperty("--intelliweave-input-highlight-color"),e.style.removeProperty("--intelliweave-poweredby-bg");return}let r=s||{r:32,g:38,b:44},{r:l,g:u,b:d}=r,c=o?(.2126*o.r+.7152*o.g+.0722*o.b)/255:1,h=c<.45,p=0,m=o?.r??l,g=o?.g??u,y=o?.b??d,v=h?0:255,M=.46,X=.24,W=.1,k=.22,B=.32,x=h?.07:.1,xe={r:Math.round(l+(p-l)*M),g:Math.round(u+(p-u)*M),b:Math.round(d+(p-d)*M)},j={r:Math.round((l+(p-l)*X)*.86+m*.14),g:Math.round((u+(p-u)*X)*.86+g*.14),b:Math.round((d+(p-d)*X)*.86+y*.14)},Me={r:Math.round((l+(p-l)*W)*.78+m*.22),g:Math.round((u+(p-u)*W)*.78+g*.22),b:Math.round((d+(p-d)*W)*.78+y*.22)},le=`rgba(${Me.r}, ${Me.g}, ${Me.b}, 0.84)`,Ie={r:Math.round(l+(p-l)*k),g:Math.round(u+(p-u)*k),b:Math.round(d+(p-d)*k)},K={r:Math.round(l+(p-l)*B),g:Math.round(u+(p-u)*B),b:Math.round(d+(p-d)*B)},G={r:Math.round(l+(v-l)*x),g:Math.round(u+(v-u)*x),b:Math.round(d+(v-d)*x)},D=o||{r:230,g:241,b:245},ce=o?c:.9,H=S=>{let T=S/255;return T<=.03928?T/12.92:Math.pow((T+.055)/1.055,2.4)},de=S=>.2126*H(S.r)+.7152*H(S.g)+.0722*H(S.b),ue=(S,T)=>{let me=de(S),dt=de(T),jt=Math.max(me,dt),_t=Math.min(me,dt);return(jt+.05)/(_t+.05)},pe=(S,T)=>({r:Math.round(S.r*(1-T)),g:Math.round(S.g*(1-T)),b:Math.round(S.b*(1-T))}),he=(S,T)=>{let me={r:Math.round(S.r*(1-T)+m*T),g:Math.round(S.g*(1-T)+g*T),b:Math.round(S.b*(1-T)+y*T)};return ue(me,D)>=4.5?me:S},w=pe(r,ce<.5?.08:.14),Z=r,J=pe(r,ce<.5?.14:.22),He=r,Je=he(J,ce<.5?.12:.08),ct=ce<.5?.22:.18;if(e.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${l}, ${u}, ${d}, 0.65)`),e.style.setProperty("--intelliweave-assistant-bubble-bg",`linear-gradient(135deg, rgba(${w.r}, ${w.g}, ${w.b}, 0.98), rgba(${Z.r}, ${Z.g}, ${Z.b}, 0.94))`),e.style.setProperty("--intelliweave-assistant-bubble-border",`rgba(${D.r}, ${D.g}, ${D.b}, ${ct})`),e.style.setProperty("--intelliweave-user-bubble-bg",`linear-gradient(135deg, rgba(${Je.r}, ${Je.g}, ${Je.b}, 0.98), rgba(${He.r}, ${He.g}, ${He.b}, 0.94))`),e.style.setProperty("--intelliweave-user-bubble-border",`rgba(${D.r}, ${D.g}, ${D.b}, ${ct+.18})`),!s){e.style.removeProperty("--intelliweave-suggestion-button-bg"),e.style.removeProperty("--intelliweave-suggestion-button-hover-bg"),e.style.removeProperty("--intelliweave-suggestion-button-border"),e.style.removeProperty("--intelliweave-suggestion-button-hover-border"),e.style.removeProperty("--intelliweave-suggestion-button-text"),e.style.removeProperty("--intelliweave-interaction-bg"),e.style.removeProperty("--intelliweave-fullscreen-header-bg"),e.style.removeProperty("--intelliweave-fullscreen-input-section-bg"),e.style.removeProperty("--intelliweave-input-field-bg"),e.style.removeProperty("--intelliweave-poweredby-bg"),o?e.style.setProperty("--intelliweave-input-highlight-color",`rgb(${o.r}, ${o.g}, ${o.b})`):e.style.removeProperty("--intelliweave-input-highlight-color");return}e.style.setProperty("--intelliweave-fullscreen-header-bg",`linear-gradient(135deg, rgba(${xe.r}, ${xe.g}, ${xe.b}, 0.98), rgba(${j.r}, ${j.g}, ${j.b}, 0.93) 54%, ${le})`),e.style.setProperty("--intelliweave-suggestion-button-bg","var(--intelliweave-assistant-bubble-bg)"),e.style.setProperty("--intelliweave-suggestion-button-hover-bg","var(--intelliweave-assistant-bubble-bg)"),e.style.setProperty("--intelliweave-suggestion-button-border","var(--intelliweave-assistant-bubble-border)"),e.style.setProperty("--intelliweave-suggestion-button-hover-border","var(--intelliweave-assistant-bubble-border)"),o?e.style.setProperty("--intelliweave-suggestion-button-text",`rgb(${o.r}, ${o.g}, ${o.b})`):e.style.removeProperty("--intelliweave-suggestion-button-text"),e.style.setProperty("--intelliweave-fullscreen-input-section-bg",`linear-gradient(180deg, rgba(${Ie.r}, ${Ie.g}, ${Ie.b}, 0.76), rgba(${K.r}, ${K.g}, ${K.b}, 0.84))`),e.style.setProperty("--intelliweave-input-field-bg",`linear-gradient(135deg, rgba(${G.r}, ${G.g}, ${G.b}, 0.46), rgba(${G.r}, ${G.g}, ${G.b}, 0.25))`),e.style.setProperty("--intelliweave-poweredby-bg",`linear-gradient(180deg, rgba(${Math.round(l*.34)}, ${Math.round(u*.34)}, ${Math.round(d*.34)}, 0.94), rgba(${Math.round(l*.22)}, ${Math.round(u*.22)}, ${Math.round(d*.22)}, 0.98))`),o?e.style.setProperty("--intelliweave-input-highlight-color",`rgb(${o.r}, ${o.g}, ${o.b})`):e.style.setProperty("--intelliweave-input-highlight-color",`rgb(${G.r}, ${G.g}, ${G.b})`),e.style.setProperty("--intelliweave-interaction-bg","var(--intelliweave-fullscreen-input-section-bg)")}parseColorToRGB(e){if(!e)return null;let t=e.trim();if(t.startsWith("#")){let i=t.slice(1);if(i.length===3){let o=parseInt(i[0]+i[0],16),s=parseInt(i[1]+i[1],16),r=parseInt(i[2]+i[2],16);return{r:o,g:s,b:r}}if(i.length===6){let o=parseInt(i.slice(0,2),16),s=parseInt(i.slice(2,4),16),r=parseInt(i.slice(4,6),16);return{r:o,g:s,b:r}}return null}if(t.startsWith("rgb")){let i=t.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return i?{r:Math.max(0,Math.min(255,Math.round(Number(i[1])))),g:Math.max(0,Math.min(255,Math.round(Number(i[2])))),b:Math.max(0,Math.min(255,Math.round(Number(i[3]))))}:null}if(typeof document<"u"){let i=document.createElement("span");if(i.style.color=t,!i.style.color)return null;document.body?.appendChild(i);let o=getComputedStyle(i).color;i.remove();let s=o.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return s?{r:Math.max(0,Math.min(255,Math.round(Number(s[1])))),g:Math.max(0,Math.min(255,Math.round(Number(s[2])))),b:Math.max(0,Math.min(255,Math.round(Number(s[3]))))}:null}return null}computeKickerColor(e){let t=this.parseColorToRGB(e);if(!t)return null;let i=t.r/255,o=t.g/255,s=t.b/255,r=Math.max(i,o,s),l=Math.min(i,o,s),u=(r+l)/2,d=0,c=0;if(r!==l){let k=r-l;switch(c=u>.5?k/(2-r-l):k/(r+l),r){case i:d=((o-s)/k+(o<s?6:0))/6;break;case o:d=((s-i)/k+2)/6;break;case s:d=((i-o)/k+4)/6;break}}let h=(d+1/3)%1,p=Math.min(1,Math.max(.5,c+.3)),m=u<.5?Math.min(.85,u+.45):Math.max(.55,u-.1),g=(k,B,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<1/6?k+(B-k)*6*x:x<1/2?B:x<2/3?k+(B-k)*(2/3-x)*6:k),y=m<.5?m*(1+p):m+p-m*p,v=2*m-y,M=Math.round(g(v,y,h+1/3)*255),X=Math.round(g(v,y,h)*255),W=Math.round(g(v,y,h-1/3)*255);return`rgb(${M}, ${X}, ${W})`}adjustLogoPadding(e){let t=new Image;t.onload=()=>{let l=t.naturalWidth/t.naturalHeight,u=l>1?96/l:96,d=l<=1?10:0,h=(96+u)/2-48,p=Math.max(h+15+d,40+d);this.style.setProperty("--logo-top-margin",`${Math.round(d)}px`);let m=this.child("web-weaver-embed-inner");m&&m.style.setProperty("--logo-bottom-padding",`${Math.round(p)}px`)},t.src=e}applyConfigStylesAndAttributes(){let e=this.config,t=this.child("root");if(!t)return;let i=!1,s=this.attr.logo||e.logo||De;if(s&&s!==this._lastLogo){this._lastLogo=s,i=!0;let w=this.child("web-weaver-logo");w&&(w.setAttribute("logo",s),this.adjustLogoPadding(s));let Z=this.root?.getElementById("dock-logo"),J=this.root?.getElementById("collapsed-logo");Z&&(Z.src=s),J&&(J.src=s)}let r=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),u=e.name||"IntelliWeave";u!==this._lastPersonaName&&(this._lastPersonaName=u,l&&(l.textContent=u),i=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",r&&(s?(r.src=s,r.style.display=""):r.style.display="none"),i=!0);let d=this.root?.getElementById("fullscreen-header"),c=(this.attr.header||"").toLowerCase();if(d){let w=c==="hidden"||c==="none"||c==="false";d.style.display=!w&&(s||u)?"":"none"}let p=this.attr.background||e.background,g=this.attr.textColor||e.textColor;if(p!==this._lastBackground)if(this._lastBackground=p,i=!0,p){t.style.background=p,t.style.setProperty("--intelliweave-persona-bg",p),t.style.setProperty("--intelliweave-panel-bg",p),this.applyPersonaColorVariants(t,p,g);let w=this.computeKickerColor(p);w?t.style.setProperty("--intelliweave-kicker-color",w):t.style.removeProperty("--intelliweave-kicker-color")}else t.style.background="",t.style.removeProperty("--intelliweave-persona-bg"),t.style.removeProperty("--intelliweave-panel-bg"),t.style.removeProperty("--intelliweave-kicker-color"),this.applyPersonaColorVariants(t,void 0,g);let y=this.attr.brandName,v=e.managedBy?.toLowerCase()==="chatterly"?"Chatterly":"IntelliWeave",M=y||e.brandName||v;if(M!==this._lastBrandName){this._lastBrandName=M,i=!0;let w=this.root?.getElementById("brand-name");w&&(w.textContent=M)}let X=this.child("interaction-bar");if(X){let w;e.managedBy?.toLowerCase()==="chatterly"?w=`linear-gradient(135deg, ${p||"#425570"}, 55%, #f3f1ee)`:p?w=`linear-gradient(135deg, ${p}, 55%, #f3f1ee)`:w="linear-gradient(135deg, #0b7aa1, 55%, #a34b0d)",X.style.setProperty("--iw-send-btn-gradient",w)}let W=this.child("interaction-bar");g!==this._lastTextColor&&(this._lastTextColor=g,i=!0,this.applyPersonaColorVariants(t,p,g),g?(t.style.color=g,t.style.setProperty("--intelliweave-user-bubble-text",g),t.style.setProperty("--intelliweave-assistant-bubble-text",g),t.style.setProperty("--intelliweave-fullscreen-input-text-color",g),W&&W.setAttribute("textColor",g)):(t.style.color="",t.style.removeProperty("--intelliweave-user-bubble-text"),t.style.removeProperty("--intelliweave-assistant-bubble-text"),t.style.removeProperty("--intelliweave-fullscreen-input-text-color"),W&&W.removeAttribute("textColor")));let k={Inter:"Inter:wght@300;400;500;600;700",Roboto:"Roboto:wght@300;400;500;700","Open Sans":"Open+Sans:wght@300;400;500;600;700",Poppins:"Poppins:wght@300;400;500;600;700",Lato:"Lato:wght@300;400;700","DM Sans":"DM+Sans:wght@300;400;500;600;700",Nunito:"Nunito:wght@300;400;500;600;700","Plus Jakarta Sans":"Plus+Jakarta+Sans:wght@300;400;500;600;700",Montserrat:"Montserrat:wght@300;400;500;600;700"},x=this.attr.fontFamily||e.fontFamily;if(x!==this._lastFontFamily){this._lastFontFamily=x,i=!0,x?t.style.setProperty("--intelliweave-font-family",x):t.style.removeProperty("--intelliweave-font-family");let w=this.root?.getElementById("google-font-link");if(w){let Z=(x||"Karla").replace(/['"]/g,"").split(",")[0].trim(),J=k[Z];J?w.href=`https://fonts.googleapis.com/css2?family=${J}&display=swap`:(!x||Z==="Karla")&&(w.href="https://fonts.googleapis.com/css2?family=Karla:ital,wght@0,200..800;1,200..800&display=swap")}}let j=this.attr.displayMode||e.displayMode||"closed";j!==this._lastDisplayMode&&(this._lastDisplayMode=j,i=!0,j==="open"&&!this.attr.open&&(this.attr.open=!0));let le=this.attr.layout||e.layout||"widget";le!==this._lastLayout&&(this._lastLayout=le,i=!0);let K=this.attr.positioningMode||e.positioningMode||"fixed";K!==this._lastPositioningMode&&(this._lastPositioningMode=K,i=!0);let D=this.attr.positionX||e.positionX||"right";D!==this._lastPositionX&&(this._lastPositionX=D,i=!0);let H=this.attr.positionY||e.positionY||"bottom";H!==this._lastPositionY&&(this._lastPositionY=H,i=!0);let de=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,ue=de!==void 0?de:e.offsetX!==void 0?e.offsetX:20;ue!==this._lastOffsetX&&(this._lastOffsetX=ue,i=!0);let pe=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,he=pe!==void 0?pe:e.offsetY!==void 0?e.offsetY:20;he!==this._lastOffsetY&&(this._lastOffsetY=he,i=!0),i&&E.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:t.style.background,finalTextColor:t.style.color,finalDisplayMode:j,finalLayout:le,finalPositioningMode:K,finalPositionX:D,finalPositionY:H,finalOffsetX:ue,finalOffsetY:he})}onUpdate(){this.applyConfigStylesAndAttributes();let e=this.child("root"),t=this._lastLayout||"widget",i=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",r=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20,d=(this._lastDisplayMode||"closed")==="open"||t==="fullscreen"||i==="container",c=t==="fullscreen"||i==="container";d&&!this.attr.open&&(this.attr.open=!0);let h=!!this.attr.open,p=!!this.attr.collapsed&&!h&&!d,m=h&&(c||!!this.state.panelFullscreen);if(this.child("web-weaver-embed-inner").style.display=h?"":"none",this.child("interaction-bar").style.display=h?"":"none",this.child("fullscreen-header").style.display=h?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display="none",this.child("poweredby").style.display=h?"flex":"none",this.child("interaction-bar").attr.layout=m?"fullscreen":"widget",this.child("panel-close").style.display=d?"none":"",this.child("panel-fullscreen").style.display=c?"none":"",h&&m!==this._previousFullscreenState&&this.refreshContentScrollability(),this._previousFullscreenState=m,h&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),C(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!h&&this._previousOpenState){let y=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;C(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:y}})}this._previousOpenState=h,e.classList.toggle("open",h),e.classList.toggle("is-collapsed",p),e.classList.toggle("layout-fullscreen",m),e.classList.toggle("position-left",o==="left"),e.classList.toggle("position-top",s==="top");let g=(this.attr.header||"").toLowerCase();if(e.classList.toggle("header-hidden",g==="hidden"||g==="none"||g==="false"),i==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),i!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",!m)){let y=p?l+56:l;p?o==="left"?e.style.left="0px":e.style.right="0px":o==="left"?e.style.left=r+"px":e.style.right=r+"px",s==="top"?e.style.top=y+"px":e.style.bottom=y+"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((y,v)=>(v.priority||0)-(y.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){b().embed==this&&(b().embed=void 0)}onContainerClick(e){if(this._suppressNextContainerClick){this._suppressNextContainerClick=!1,e.preventDefault(),e.stopPropagation();return}let t=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&t!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.collapsed="",this.attr.open=!0))}onDockOpenClick(e){e.preventDefault(),e.stopPropagation(),this.openFromDock()}onDockCollapseClick(e){e.preventDefault(),e.stopPropagation(),this.collapseDock()}onCollapsedOpenClick(e){e.preventDefault(),e.stopPropagation(),this.showDockFromCollapsed()}onPanelCollapseClick(e){e.preventDefault(),e.stopPropagation(),this.collapseDock()}onPanelFullscreenClick(e){e.preventDefault(),e.stopPropagation();let t=this._lastLayout||"widget",i=this._lastPositioningMode||"fixed";t==="fullscreen"||i==="container"||(this.state.panelFullscreen=!this.state.panelFullscreen)}onPanelCloseClick(e){e.preventDefault(),e.stopPropagation(),this.closePanel()}isForcedOpen(){let e=this._lastDisplayMode||"closed",t=this._lastLayout||"widget",i=this._lastPositioningMode||"fixed";return e==="open"||t==="fullscreen"||i==="container"}openFromDock(){this._returnToCollapsedOnSwipeClose=!1,this.attr.collapsed="",this.attr.open=!0}refreshContentScrollability(){let e=this.child("web-weaver-embed-inner");if(!e||typeof window>"u")return;let t=e.scrollTop;e.style.setProperty("-webkit-overflow-scrolling","auto"),e.style.overflowY="hidden",window.requestAnimationFrame(()=>{e.style.overflowY="auto",e.style.setProperty("-webkit-overflow-scrolling","touch"),e.scrollTop=Math.min(t,Math.max(0,e.scrollHeight-e.clientHeight))})}showDockFromCollapsed(){this._returnToCollapsedOnSwipeClose=!0,this.state.panelFullscreen=!1,this.attr.collapsed=""}openFromCollapsed(){this._returnToCollapsedOnSwipeClose=!0,this.state.panelFullscreen=!1,this.attr.collapsed="",this.attr.open=!0}closePanel(){if(this.isForcedOpen())return;let e=this._returnToCollapsedOnSwipeClose;this._returnToCollapsedOnSwipeClose=!1,this.state.panelFullscreen=!1,this.attr.open="",e&&(this.attr.collapsed=!0)}collapseDock(){this.isForcedOpen()||(this._returnToCollapsedOnSwipeClose=!1,this.state.panelFullscreen=!1,this.attr.open="",this.attr.collapsed=!0)}onSwipePointerDown(e){if(typeof window>"u"||window.innerWidth>768||e.pointerType==="mouse"&&e.button!==0)return;let t=e.currentTarget,i=e.target;if(!(!(t?.id==="collapsed-tab"||t?.id==="dock-main")&&i?.closest?.('input, textarea, select, [contenteditable="true"], button'))){this._swipeStart={x:e.clientX,y:e.clientY};try{t?.setPointerCapture?.(e.pointerId)}catch{}}}onSwipePointerCancel(){this._swipeStart=void 0}inwardSwipeDirection(){return(this._lastPositionX||"right")==="left"?"right":"left"}outwardSwipeDirection(){return this.inwardSwipeDirection()==="left"?"right":"left"}didSwipe(e,t){let i=this._swipeStart;if(this._swipeStart=void 0,!i||typeof window>"u"||window.innerWidth>768)return!1;let o=e.clientX-i.x,s=e.clientY-i.y;if(Math.abs(o)<48||Math.abs(s)>72||Math.abs(o)<Math.abs(s)*1.2||t==="left"&&o>=0||t==="right"&&o<=0)return!1;e.preventDefault();try{e.currentTarget.releasePointerCapture?.(e.pointerId)}catch{}return!0}onCollapsedSwipePointerUp(e){this.didSwipe(e,this.inwardSwipeDirection())&&this.openFromCollapsed()}onDockSwipePointerUp(e){this.didSwipe(e,this.inwardSwipeDirection())&&this.openFromDock()}onPanelSwipePointerUp(e){this.attr.open&&this.didSwipe(e,this.outwardSwipeDirection())&&(this._suppressNextContainerClick=!0,this.closePanel())}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.closePanel():this.openFromDock()}}open(){this.attr.collapsed="",this.attr.open=!0}close(){this.closePanel()}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=[],this._handledEmbeddedActionBlocks.clear();let t=document.createElement("div");t.className="introduction-message",t.innerHTML=b().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let i of b().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",s=>this.onSuggestionClick(s,i)),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 r of Array.from(t.querySelectorAll(".suggestion-button")))r.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=e,t.appendChild(i);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 r of this.suggestions){let l=document.createElement("div");l.className="suggestion-button",l.innerText=r,l.addEventListener("click",u=>this.onSuggestionClick(u,r)),this.currentOutputElement.appendChild(l)}}catch(i){E.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,t.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",r=>this.resetConversation()),t.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e,t){let i=[];for(let o of e)for(let s=0;s<(o.sections?.length||0);s++){let r=o.sections[s],l=`msgelem-${o.id||""}_${s}_${r.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),r.type=="thinking"){if(!r.text)continue;let u=r.text||"";u.includes(`
1652
+ Continue writing normal visible text outside the block.`,isContext:!0,disabled:!this.ai.flags.allowEmojiActions}),this.resetConversation()}).catch(o=>{E.error("Failed to load AI configuration:",o),this.state.loading=!1;let r=this.child("web-weaver-embed-inner");if(r){let s=o?.message||o?.toString()||"Unknown error";r.innerHTML=`<div class="output" style="padding: 20px;"><span style="display: inline-block; background-color: #fee; color: #c00; padding: 8px 12px; border-radius: 6px; border: 1px solid #fcc;">${s}</span></div>`}})}applyPersonaColorVariants(e,t,i){let o=this.parseColorToRGB(i),r=this.parseColorToRGB(t);if(!r&&!o){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.removeProperty("--intelliweave-assistant-bubble-border"),e.style.removeProperty("--intelliweave-user-bubble-bg"),e.style.removeProperty("--intelliweave-user-bubble-border"),e.style.removeProperty("--intelliweave-suggestion-button-bg"),e.style.removeProperty("--intelliweave-suggestion-button-hover-bg"),e.style.removeProperty("--intelliweave-suggestion-button-border"),e.style.removeProperty("--intelliweave-suggestion-button-hover-border"),e.style.removeProperty("--intelliweave-suggestion-button-text"),e.style.removeProperty("--intelliweave-interaction-bg"),e.style.removeProperty("--intelliweave-fullscreen-header-bg"),e.style.removeProperty("--intelliweave-fullscreen-input-section-bg"),e.style.removeProperty("--intelliweave-input-field-bg"),e.style.removeProperty("--intelliweave-input-highlight-color"),e.style.removeProperty("--intelliweave-poweredby-bg");return}let s=r||{r:32,g:38,b:44},{r:l,g:u,b:c}=s,d=o?(.2126*o.r+.7152*o.g+.0722*o.b)/255:1,h=d<.45,p=0,m=o?.r??l,g=o?.g??u,y=o?.b??c,w=h?0:255,k=.46,J=.24,Z=.1,v=.22,W=.32,M=h?.07:.1,pe={r:Math.round(l+(p-l)*k),g:Math.round(u+(p-u)*k),b:Math.round(c+(p-c)*k)},xe={r:Math.round((l+(p-l)*J)*.86+m*.14),g:Math.round((u+(p-u)*J)*.86+g*.14),b:Math.round((c+(p-c)*J)*.86+y*.14)},G={r:Math.round((l+(p-l)*Z)*.78+m*.22),g:Math.round((u+(p-u)*Z)*.78+g*.22),b:Math.round((c+(p-c)*Z)*.78+y*.22)},lt=`rgba(${G.r}, ${G.g}, ${G.b}, 0.84)`,B={r:Math.round(l+(p-l)*v),g:Math.round(u+(p-u)*v),b:Math.round(c+(p-c)*v)},Me={r:Math.round(l+(p-l)*W),g:Math.round(u+(p-u)*W),b:Math.round(c+(p-c)*W)},N={r:Math.round(l+(w-l)*M),g:Math.round(u+(w-u)*M),b:Math.round(c+(w-c)*M)},j=o||{r:230,g:241,b:245},_=o?d:.9,Ie=S=>{let T=S/255;return T<=.03928?T/12.92:Math.pow((T+.055)/1.055,2.4)},q=S=>.2126*Ie(S.r)+.7152*Ie(S.g)+.0722*Ie(S.b),dt=(S,T)=>{let me=q(S),ct=q(T),jt=Math.max(me,ct),_t=Math.min(me,ct);return(jt+.05)/(_t+.05)},ee=(S,T)=>({r:Math.round(S.r*(1-T)),g:Math.round(S.g*(1-T)),b:Math.round(S.b*(1-T))}),ke=(S,T)=>{let me={r:Math.round(S.r*(1-T)+m*T),g:Math.round(S.g*(1-T)+g*T),b:Math.round(S.b*(1-T)+y*T)};return dt(me,j)>=4.5?me:S},$=ee(s,_<.5?.08:.14),te=s,he=ee(s,_<.5?.14:.22),x=s,R=ke(he,_<.5?.12:.08),z=_<.5?.22:.18;if(e.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${l}, ${u}, ${c}, 0.65)`),e.style.setProperty("--intelliweave-assistant-bubble-bg",`linear-gradient(135deg, rgba(${$.r}, ${$.g}, ${$.b}, 0.98), rgba(${te.r}, ${te.g}, ${te.b}, 0.94))`),e.style.setProperty("--intelliweave-assistant-bubble-border",`rgba(${j.r}, ${j.g}, ${j.b}, ${z})`),e.style.setProperty("--intelliweave-user-bubble-bg",`linear-gradient(135deg, rgba(${R.r}, ${R.g}, ${R.b}, 0.98), rgba(${x.r}, ${x.g}, ${x.b}, 0.94))`),e.style.setProperty("--intelliweave-user-bubble-border",`rgba(${j.r}, ${j.g}, ${j.b}, ${z+.18})`),!r){e.style.removeProperty("--intelliweave-suggestion-button-bg"),e.style.removeProperty("--intelliweave-suggestion-button-hover-bg"),e.style.removeProperty("--intelliweave-suggestion-button-border"),e.style.removeProperty("--intelliweave-suggestion-button-hover-border"),e.style.removeProperty("--intelliweave-suggestion-button-text"),e.style.removeProperty("--intelliweave-interaction-bg"),e.style.removeProperty("--intelliweave-fullscreen-header-bg"),e.style.removeProperty("--intelliweave-fullscreen-input-section-bg"),e.style.removeProperty("--intelliweave-input-field-bg"),e.style.removeProperty("--intelliweave-poweredby-bg"),o?e.style.setProperty("--intelliweave-input-highlight-color",`rgb(${o.r}, ${o.g}, ${o.b})`):e.style.removeProperty("--intelliweave-input-highlight-color");return}e.style.setProperty("--intelliweave-fullscreen-header-bg",`linear-gradient(135deg, rgba(${pe.r}, ${pe.g}, ${pe.b}, 0.98), rgba(${xe.r}, ${xe.g}, ${xe.b}, 0.93) 54%, ${lt})`),e.style.setProperty("--intelliweave-suggestion-button-bg","var(--intelliweave-assistant-bubble-bg)"),e.style.setProperty("--intelliweave-suggestion-button-hover-bg","var(--intelliweave-assistant-bubble-bg)"),e.style.setProperty("--intelliweave-suggestion-button-border","var(--intelliweave-assistant-bubble-border)"),e.style.setProperty("--intelliweave-suggestion-button-hover-border","var(--intelliweave-assistant-bubble-border)"),o?e.style.setProperty("--intelliweave-suggestion-button-text",`rgb(${o.r}, ${o.g}, ${o.b})`):e.style.removeProperty("--intelliweave-suggestion-button-text"),e.style.setProperty("--intelliweave-fullscreen-input-section-bg",`linear-gradient(180deg, rgba(${B.r}, ${B.g}, ${B.b}, 0.76), rgba(${Me.r}, ${Me.g}, ${Me.b}, 0.84))`),e.style.setProperty("--intelliweave-input-field-bg",`linear-gradient(135deg, rgba(${N.r}, ${N.g}, ${N.b}, 0.46), rgba(${N.r}, ${N.g}, ${N.b}, 0.25))`),e.style.setProperty("--intelliweave-poweredby-bg",`linear-gradient(180deg, rgba(${Math.round(l*.34)}, ${Math.round(u*.34)}, ${Math.round(c*.34)}, 0.94), rgba(${Math.round(l*.22)}, ${Math.round(u*.22)}, ${Math.round(c*.22)}, 0.98))`),o?e.style.setProperty("--intelliweave-input-highlight-color",`rgb(${o.r}, ${o.g}, ${o.b})`):e.style.setProperty("--intelliweave-input-highlight-color",`rgb(${N.r}, ${N.g}, ${N.b})`),e.style.setProperty("--intelliweave-interaction-bg","var(--intelliweave-fullscreen-input-section-bg)")}parseColorToRGB(e){if(!e)return null;let t=e.trim();if(t.startsWith("#")){let i=t.slice(1);if(i.length===3){let o=parseInt(i[0]+i[0],16),r=parseInt(i[1]+i[1],16),s=parseInt(i[2]+i[2],16);return{r:o,g:r,b:s}}if(i.length===6){let o=parseInt(i.slice(0,2),16),r=parseInt(i.slice(2,4),16),s=parseInt(i.slice(4,6),16);return{r:o,g:r,b:s}}return null}if(t.startsWith("rgb")){let i=t.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return i?{r:Math.max(0,Math.min(255,Math.round(Number(i[1])))),g:Math.max(0,Math.min(255,Math.round(Number(i[2])))),b:Math.max(0,Math.min(255,Math.round(Number(i[3]))))}:null}if(typeof document<"u"){let i=document.createElement("span");if(i.style.color=t,!i.style.color)return null;document.body?.appendChild(i);let o=getComputedStyle(i).color;i.remove();let r=o.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return r?{r:Math.max(0,Math.min(255,Math.round(Number(r[1])))),g:Math.max(0,Math.min(255,Math.round(Number(r[2])))),b:Math.max(0,Math.min(255,Math.round(Number(r[3]))))}:null}return null}computeKickerColor(e){let t=this.parseColorToRGB(e);if(!t)return null;let i=t.r/255,o=t.g/255,r=t.b/255,s=Math.max(i,o,r),l=Math.min(i,o,r),u=(s+l)/2,c=0,d=0;if(s!==l){let v=s-l;switch(d=u>.5?v/(2-s-l):v/(s+l),s){case i:c=((o-r)/v+(o<r?6:0))/6;break;case o:c=((r-i)/v+2)/6;break;case r:c=((i-o)/v+4)/6;break}}let h=(c+1/3)%1,p=Math.min(1,Math.max(.5,d+.3)),m=u<.5?Math.min(.85,u+.45):Math.max(.55,u-.1),g=(v,W,M)=>(M<0&&(M+=1),M>1&&(M-=1),M<1/6?v+(W-v)*6*M:M<1/2?W:M<2/3?v+(W-v)*(2/3-M)*6:v),y=m<.5?m*(1+p):m+p-m*p,w=2*m-y,k=Math.round(g(w,y,h+1/3)*255),J=Math.round(g(w,y,h)*255),Z=Math.round(g(w,y,h-1/3)*255);return`rgb(${k}, ${J}, ${Z})`}adjustLogoPadding(e){let t=new Image;t.onload=()=>{let l=t.naturalWidth/t.naturalHeight,u=l>1?96/l:96,c=l<=1?10:0,h=(96+u)/2-48,p=Math.max(h+15+c,40+c);this.style.setProperty("--logo-top-margin",`${Math.round(c)}px`);let m=this.child("web-weaver-embed-inner");m&&m.style.setProperty("--logo-bottom-padding",`${Math.round(p)}px`)},t.src=e}applyConfigStylesAndAttributes(){let e=this.config,t=this.child("root");if(!t)return;let i=!1,r=this.attr.logo||e.logo||We;if(r&&r!==this._lastLogo){this._lastLogo=r,i=!0;let x=this.child("web-weaver-logo");x&&(x.setAttribute("logo",r),this.adjustLogoPadding(r));let R=this.root?.getElementById("dock-logo"),z=this.root?.getElementById("collapsed-logo");R&&(R.src=r),z&&(z.src=r)}let s=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),u=e.name||"IntelliWeave";u!==this._lastPersonaName&&(this._lastPersonaName=u,l&&(l.textContent=u),i=!0),r!==this._lastHeaderLogo&&(this._lastHeaderLogo=r||"",s&&(r?(s.src=r,s.style.display=""):s.style.display="none"),i=!0);let c=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(c){let x=d==="hidden"||d==="none"||d==="false";c.style.display=!x&&(r||u)?"":"none"}let p=this.attr.background||e.background,g=this.attr.textColor||e.textColor,w=this.attr.brandNameColor||e.brandNameColor;p!==this._lastBackground&&(this._lastBackground=p,i=!0,p?(t.style.background=p,t.style.setProperty("--intelliweave-persona-bg",p),t.style.setProperty("--intelliweave-panel-bg",p),this.applyPersonaColorVariants(t,p,g)):(t.style.background="",t.style.removeProperty("--intelliweave-persona-bg"),t.style.removeProperty("--intelliweave-panel-bg"),this.applyPersonaColorVariants(t,void 0,g)));let k=this.attr.brandName,J=e.managedBy?.toLowerCase()==="chatterly"?"Chatterly":"IntelliWeave",Z=k||e.brandName||J;if(Z!==this._lastBrandName){this._lastBrandName=Z,i=!0;let x=this.root?.getElementById("brand-name");x&&(x.textContent=Z)}let v=w||(p?this.computeKickerColor(p):void 0);v!==this._lastBrandNameColor&&(this._lastBrandNameColor=v,i=!0,v?t.style.setProperty("--intelliweave-kicker-color",v):t.style.removeProperty("--intelliweave-kicker-color"));let W=this.child("interaction-bar");if(W){let x;e.managedBy?.toLowerCase()==="chatterly"?x=`linear-gradient(135deg, ${p||"#425570"}, 55%, #f3f1ee)`:p?x=`linear-gradient(135deg, ${p}, 55%, #f3f1ee)`:x="linear-gradient(135deg, #0b7aa1, 55%, #a34b0d)",W.style.setProperty("--iw-send-btn-gradient",x)}let M=this.child("interaction-bar");g!==this._lastTextColor&&(this._lastTextColor=g,i=!0,this.applyPersonaColorVariants(t,p,g),g?(t.style.color=g,t.style.setProperty("--intelliweave-user-bubble-text",g),t.style.setProperty("--intelliweave-assistant-bubble-text",g),t.style.setProperty("--intelliweave-fullscreen-input-text-color",g),M&&M.setAttribute("textColor",g)):(t.style.color="",t.style.removeProperty("--intelliweave-user-bubble-text"),t.style.removeProperty("--intelliweave-assistant-bubble-text"),t.style.removeProperty("--intelliweave-fullscreen-input-text-color"),M&&M.removeAttribute("textColor")));let pe={Inter:"Inter:wght@300;400;500;600;700",Roboto:"Roboto:wght@300;400;500;700","Open Sans":"Open+Sans:wght@300;400;500;600;700",Poppins:"Poppins:wght@300;400;500;600;700",Lato:"Lato:wght@300;400;700","DM Sans":"DM+Sans:wght@300;400;500;600;700",Nunito:"Nunito:wght@300;400;500;600;700","Plus Jakarta Sans":"Plus+Jakarta+Sans:wght@300;400;500;600;700",Montserrat:"Montserrat:wght@300;400;500;600;700"},G=this.attr.fontFamily||e.fontFamily;if(G!==this._lastFontFamily){this._lastFontFamily=G,i=!0,G?t.style.setProperty("--intelliweave-font-family",G):t.style.removeProperty("--intelliweave-font-family");let x=this.root?.getElementById("google-font-link");if(x){let R=(G||"Karla").replace(/['"]/g,"").split(",")[0].trim(),z=pe[R];z?x.href=`https://fonts.googleapis.com/css2?family=${z}&display=swap`:(!G||R==="Karla")&&(x.href="https://fonts.googleapis.com/css2?family=Karla:ital,wght@0,200..800;1,200..800&display=swap")}}let B=this.attr.displayMode||e.displayMode||"closed";B!==this._lastDisplayMode&&(this._lastDisplayMode=B,i=!0,B==="open"&&!this.attr.open&&(this.attr.open=!0));let N=this.attr.layout||e.layout||"widget";N!==this._lastLayout&&(this._lastLayout=N,i=!0);let _=this.attr.positioningMode||e.positioningMode||"fixed";_!==this._lastPositioningMode&&(this._lastPositioningMode=_,i=!0);let q=this.attr.positionX||e.positionX||"right";q!==this._lastPositionX&&(this._lastPositionX=q,i=!0);let ee=this.attr.positionY||e.positionY||"bottom";ee!==this._lastPositionY&&(this._lastPositionY=ee,i=!0);let ke=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,$=ke!==void 0?ke:e.offsetX!==void 0?e.offsetX:20;$!==this._lastOffsetX&&(this._lastOffsetX=$,i=!0);let te=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,he=te!==void 0?te:e.offsetY!==void 0?e.offsetY:20;he!==this._lastOffsetY&&(this._lastOffsetY=he,i=!0),i&&E.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:r,finalBackground:t.style.background,finalTextColor:t.style.color,finalDisplayMode:B,finalLayout:N,finalPositioningMode:_,finalPositionX:q,finalPositionY:ee,finalOffsetX:$,finalOffsetY:he})}onUpdate(){this.applyConfigStylesAndAttributes();let e=this.child("root"),t=this._lastLayout||"widget",i=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",r=this._lastPositionY||"bottom",s=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20,c=(this._lastDisplayMode||"closed")==="open"||t==="fullscreen"||i==="container",d=t==="fullscreen"||i==="container";c&&!this.attr.open&&(this.attr.open=!0);let h=!!this.attr.open,p=!!this.attr.collapsed&&!h&&!c,m=h&&(d||!!this.state.panelFullscreen);if(this.child("web-weaver-embed-inner").style.display=h?"":"none",this.child("interaction-bar").style.display=h?"":"none",this.child("fullscreen-header").style.display=h?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display="none",this.child("poweredby").style.display=h&&!this.shouldHidePoweredBy()?"flex":"none",this.child("interaction-bar").attr.layout=m?"fullscreen":"widget",this.child("panel-close").style.display=c?"none":"",this.child("panel-fullscreen").style.display=d?"none":"",h&&m!==this._previousFullscreenState&&this.refreshContentScrollability(),this._previousFullscreenState=m,h&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),C(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!h&&this._previousOpenState){let y=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;C(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:y}})}this._previousOpenState=h,e.classList.toggle("open",h),e.classList.toggle("is-collapsed",p),e.classList.toggle("layout-fullscreen",m),e.classList.toggle("position-left",o==="left"),e.classList.toggle("position-top",r==="top");let g=(this.attr.header||"").toLowerCase();if(e.classList.toggle("header-hidden",g==="hidden"||g==="none"||g==="false"),i==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),i!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",!m)){let y=p?l+56:l;p?o==="left"?e.style.left="0px":e.style.right="0px":o==="left"?e.style.left=s+"px":e.style.right=s+"px",r==="top"?e.style.top=y+"px":e.style.bottom=y+"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((y,w)=>(w.priority||0)-(y.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}isTruthyFeatureFlag(e){return e===!0||typeof e=="string"&&["true","1","yes"].includes(e.toLowerCase())}shouldHidePoweredBy(){return this.isTruthyFeatureFlag(this.config.hidePoweredBy)?!0:this.isTruthyFeatureFlag(this.attr.hidePoweredBy)}onDestroy(){b().embed==this&&(b().embed=void 0)}onContainerClick(e){if(this._suppressNextContainerClick){this._suppressNextContainerClick=!1,e.preventDefault(),e.stopPropagation();return}let t=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&t!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.collapsed="",this.attr.open=!0))}onDockOpenClick(e){e.preventDefault(),e.stopPropagation(),this.openFromDock()}onDockCollapseClick(e){e.preventDefault(),e.stopPropagation(),this.collapseDock()}onCollapsedOpenClick(e){e.preventDefault(),e.stopPropagation(),this.showDockFromCollapsed()}onPanelCollapseClick(e){e.preventDefault(),e.stopPropagation(),this.collapseDock()}onPanelFullscreenClick(e){e.preventDefault(),e.stopPropagation();let t=this._lastLayout||"widget",i=this._lastPositioningMode||"fixed";t==="fullscreen"||i==="container"||(this.state.panelFullscreen=!this.state.panelFullscreen)}onPanelCloseClick(e){e.preventDefault(),e.stopPropagation(),this.closePanel()}isForcedOpen(){let e=this._lastDisplayMode||"closed",t=this._lastLayout||"widget",i=this._lastPositioningMode||"fixed";return e==="open"||t==="fullscreen"||i==="container"}openFromDock(){this._returnToCollapsedOnSwipeClose=!1,this.attr.collapsed="",this.attr.open=!0}refreshContentScrollability(){let e=this.child("web-weaver-embed-inner");if(!e||typeof window>"u")return;let t=e.scrollTop;e.style.setProperty("-webkit-overflow-scrolling","auto"),e.style.overflowY="hidden",window.requestAnimationFrame(()=>{e.style.overflowY="auto",e.style.setProperty("-webkit-overflow-scrolling","touch"),e.scrollTop=Math.min(t,Math.max(0,e.scrollHeight-e.clientHeight))})}showDockFromCollapsed(){this._returnToCollapsedOnSwipeClose=!0,this.state.panelFullscreen=!1,this.attr.collapsed=""}openFromCollapsed(){this._returnToCollapsedOnSwipeClose=!0,this.state.panelFullscreen=!1,this.attr.collapsed="",this.attr.open=!0}closePanel(){if(this.isForcedOpen())return;let e=this._returnToCollapsedOnSwipeClose;this._returnToCollapsedOnSwipeClose=!1,this.state.panelFullscreen=!1,this.attr.open="",e&&(this.attr.collapsed=!0)}collapseDock(){this.isForcedOpen()||(this._returnToCollapsedOnSwipeClose=!1,this.state.panelFullscreen=!1,this.attr.open="",this.attr.collapsed=!0)}onSwipePointerDown(e){if(typeof window>"u"||window.innerWidth>768||e.pointerType==="mouse"&&e.button!==0)return;let t=e.currentTarget,i=e.target;if(!(!(t?.id==="collapsed-tab"||t?.id==="dock-main")&&i?.closest?.('input, textarea, select, [contenteditable="true"], button'))){this._swipeStart={x:e.clientX,y:e.clientY};try{t?.setPointerCapture?.(e.pointerId)}catch{}}}onSwipePointerCancel(){this._swipeStart=void 0}inwardSwipeDirection(){return(this._lastPositionX||"right")==="left"?"right":"left"}outwardSwipeDirection(){return this.inwardSwipeDirection()==="left"?"right":"left"}didSwipe(e,t){let i=this._swipeStart;if(this._swipeStart=void 0,!i||typeof window>"u"||window.innerWidth>768)return!1;let o=e.clientX-i.x,r=e.clientY-i.y;if(Math.abs(o)<48||Math.abs(r)>72||Math.abs(o)<Math.abs(r)*1.2||t==="left"&&o>=0||t==="right"&&o<=0)return!1;e.preventDefault();try{e.currentTarget.releasePointerCapture?.(e.pointerId)}catch{}return!0}onCollapsedSwipePointerUp(e){this.didSwipe(e,this.inwardSwipeDirection())&&this.openFromCollapsed()}onDockSwipePointerUp(e){this.didSwipe(e,this.inwardSwipeDirection())&&this.openFromDock()}onPanelSwipePointerUp(e){this.attr.open&&this.didSwipe(e,this.outwardSwipeDirection())&&(this._suppressNextContainerClick=!0,this.closePanel())}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.closePanel():this.openFromDock()}}open(){this.attr.collapsed="",this.attr.open=!0}close(){this.closePanel()}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=[],this._handledEmbeddedActionBlocks.clear();let t=document.createElement("div");t.className="introduction-message",t.innerHTML=b().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let i of b().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",r=>this.onSuggestionClick(r,i)),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 s of Array.from(t.querySelectorAll(".suggestion-button")))s.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=e,t.appendChild(i);let o=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",t.appendChild(this.currentOutputElement);let r=Math.ceil(t.clientHeight-300);r<0&&(r=0),r>600&&(r=600),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=r+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"}),await this.ai.sendMessage(e);for(let s of this.suggestions){let l=document.createElement("div");l.className="suggestion-button",l.innerText=s,l.addEventListener("click",u=>this.onSuggestionClick(u,s)),this.currentOutputElement.appendChild(l)}}catch(i){E.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,t.appendChild(o);let r=document.createElement("div");r.className="suggestion-button",r.innerText="Reset conversation",r.addEventListener("click",s=>this.resetConversation()),t.appendChild(r)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e,t){let i=[];for(let o of e)for(let r=0;r<(o.sections?.length||0);r++){let s=o.sections[r],l=`msgelem-${o.id||""}_${r}_${s.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),s.type=="thinking"){if(!s.text)continue;let u=s.text||"";u.includes(`
1637
1653
  `)&&(u=u.split(`
1638
- `)[0]),this.updateInfoElement(l,u,"thinking-icon"),i.push(l)}else if(r.type=="tool_call"){let d=new ee(e).toolResult(r.toolCallInstanceID||"");if(r.toolCallHiddenInUI!="always"){if(d?.toolErrorResponse)this.updateInfoElement(l,"**Error:** "+d.toolErrorResponse||"","tool-icon"),i.push(l);else if(!(r.toolCallHiddenInUI=="after-complete"&&d))if(r.toolKbID=="search"){let c=r.toolParameters?.query?`**Search:** ${r.toolParameters.query}`:"**Search**";this.updateInfoElement(l,c,"tool-icon"),i.push(l)}else if(r.toolKbID?.startsWith("ask:")&&r.toolParameters?.query){let c=r.toolKbID.substring(4),p=`**Ask ${this.ai.subAgents.subagents.find(m=>m.id===c)?.name||"agent"}:** ${r.toolParameters.query}`;this.updateInfoElement(l,p,"tool-icon"),i.push(l)}else this.updateInfoElement(l,r.toolKbName||"","tool-icon"),i.push(l)}}else if(r.type!="tool_result"){if(!r.text)continue;this.updateTextElement(l,r.text||"")&&i.push(l)}}for(let o of Array.from(this.currentOutputElement.children))i.includes(o.id)||o.remove()}updateTextElement(e,t){let i=et(t||""),o=this._handledEmbeddedActionBlocks.get(e)||new Set;this._handledEmbeddedActionBlocks.set(e,o);for(let l of i.blocks)o.has(l.raw)||(o.add(l.raw),l.action&&this.runEmbeddedAction(l.action));let s=this.currentOutputElement.querySelector(`#${e}`);if(!i.visibleText.trim())return s?.remove(),!1;s||(s=document.createElement("div"),s.id=e,s.className="output",this.currentOutputElement.appendChild(s));let r=Pt().use(Wt).use(Dt).use(Gt).use(Zt).use(At,{target:"_blank",rel:["noopener","noreferrer"]}).use(Lt).use(Nt).processSync(i.visibleText||"");return s.innerHTML=r.toString("utf-8"),!0}runEmbeddedAction(e){if(e.action==="suggestion"){if(!this.ai.flags.allowSuggestionButtons)return;let s=this.normalizeSuggestionActionValue(e.text);if(!s)return;this.suggestions.includes(s)||this.suggestions.push(s);return}if(e.action!=="emoji"||!this.ai.flags.allowEmojiActions)return;let t=this.normalizeEmojiActionValue(e.emoji);if(!t)return;let i=this.clampNumber(e.count,1,24,14),o=this.clampNumber(e.duration,800,2200,1300);this.showEmojiBurst(t,i,o)}clampNumber(e,t,i,o){let s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?Math.max(t,Math.min(i,Math.round(s))):o}normalizeEmojiActionValue(e){return typeof e!="string"?"":Array.from(e.trim()).slice(0,8).join("")}normalizeSuggestionActionValue(e){return typeof e!="string"?"":Array.from(e.trim().replace(/\s+/g," ")).slice(0,160).join("")}showEmojiBurst(e,t,i){let o=this.child("emoji-action-overlay");if(o)for(let s=0;s<t;s++){let r=document.createElement("span");r.className="emoji-action-particle",r.textContent=e;let l=Math.floor(Math.random()*220),u=i+Math.floor(Math.random()*360);r.style.setProperty("--emoji-x",`${12+Math.random()*76}%`),r.style.setProperty("--emoji-bottom",`${54+Math.random()*52}px`),r.style.setProperty("--emoji-size",`${26+Math.random()*20}px`),r.style.setProperty("--emoji-drift",`${Math.round((Math.random()-.5)*180)}px`),r.style.setProperty("--emoji-rise",`${Math.round(-130-Math.random()*170)}px`),r.style.setProperty("--emoji-scale",`${(.9+Math.random()*.7).toFixed(2)}`),r.style.setProperty("--emoji-rotate-start",`${Math.round((Math.random()-.5)*28)}deg`),r.style.setProperty("--emoji-rotate-end",`${Math.round((Math.random()-.5)*120)}deg`),r.style.setProperty("--emoji-duration",`${u}ms`),r.style.animationDelay=`${l}ms`,o.appendChild(r),window.setTimeout(()=>r.remove(),u+l+250)}}updateInfoElement(e,t,i){let o=this.currentOutputElement.querySelector(`#${e}`);o||(o=document.createElement("div"),o.id=e,o.className="info-block",o.innerHTML=`
1654
+ `)[0]),this.updateInfoElement(l,u,"thinking-icon"),i.push(l)}else if(s.type=="tool_call"){let c=new oe(e).toolResult(s.toolCallInstanceID||"");if(s.toolCallHiddenInUI!="always"){if(c?.toolErrorResponse)this.updateInfoElement(l,"**Error:** "+c.toolErrorResponse||"","tool-icon"),i.push(l);else if(!(s.toolCallHiddenInUI=="after-complete"&&c))if(s.toolKbID=="search"){let d=s.toolParameters?.query?`**Search:** ${s.toolParameters.query}`:"**Search**";this.updateInfoElement(l,d,"tool-icon"),i.push(l)}else if(s.toolKbID?.startsWith("ask:")&&s.toolParameters?.query){let d=s.toolKbID.substring(4),p=`**Ask ${this.ai.subAgents.subagents.find(m=>m.id===d)?.name||"agent"}:** ${s.toolParameters.query}`;this.updateInfoElement(l,p,"tool-icon"),i.push(l)}else this.updateInfoElement(l,s.toolKbName||"","tool-icon"),i.push(l)}}else if(s.type!="tool_result"){if(!s.text)continue;this.updateTextElement(l,s.text||"")&&i.push(l)}}for(let o of Array.from(this.currentOutputElement.children))i.includes(o.id)||o.remove()}updateTextElement(e,t){let i=qe(t||""),o=this._handledEmbeddedActionBlocks.get(e)||new Set;this._handledEmbeddedActionBlocks.set(e,o);for(let l of i.blocks)o.has(l.raw)||(o.add(l.raw),l.action&&this.runEmbeddedAction(l.action));let r=this.currentOutputElement.querySelector(`#${e}`);if(!i.visibleText.trim())return r?.remove(),!1;r||(r=document.createElement("div"),r.id=e,r.className="output",this.currentOutputElement.appendChild(r));let s=Pt().use(Wt).use(Dt).use(Gt).use(Zt).use(Nt,{target:"_blank",rel:["noopener","noreferrer"]}).use(At).use(Lt).processSync(i.visibleText||"");return r.innerHTML=s.toString("utf-8"),!0}runEmbeddedAction(e){if(e.action==="suggestion"){if(!this.ai.flags.allowSuggestionButtons)return;let r=this.normalizeSuggestionActionValue(e.text);if(!r)return;this.suggestions.includes(r)||this.suggestions.push(r);return}if(e.action!=="emoji"||!this.ai.flags.allowEmojiActions)return;let t=this.normalizeEmojiActionValue(e.emoji);if(!t)return;let i=this.clampNumber(e.count,1,24,14),o=this.clampNumber(e.duration,800,2200,1300);this.showEmojiBurst(t,i,o)}clampNumber(e,t,i,o){let r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.max(t,Math.min(i,Math.round(r))):o}normalizeEmojiActionValue(e){return typeof e!="string"?"":Array.from(e.trim()).slice(0,8).join("")}normalizeSuggestionActionValue(e){return typeof e!="string"?"":Array.from(e.trim().replace(/\s+/g," ")).slice(0,160).join("")}showEmojiBurst(e,t,i){let o=this.child("emoji-action-overlay");if(o)for(let r=0;r<t;r++){let s=document.createElement("span");s.className="emoji-action-particle",s.textContent=e;let l=Math.floor(Math.random()*220),u=i+Math.floor(Math.random()*360);s.style.setProperty("--emoji-x",`${12+Math.random()*76}%`),s.style.setProperty("--emoji-bottom",`${54+Math.random()*52}px`),s.style.setProperty("--emoji-size",`${26+Math.random()*20}px`),s.style.setProperty("--emoji-drift",`${Math.round((Math.random()-.5)*180)}px`),s.style.setProperty("--emoji-rise",`${Math.round(-130-Math.random()*170)}px`),s.style.setProperty("--emoji-scale",`${(.9+Math.random()*.7).toFixed(2)}`),s.style.setProperty("--emoji-rotate-start",`${Math.round((Math.random()-.5)*28)}deg`),s.style.setProperty("--emoji-rotate-end",`${Math.round((Math.random()-.5)*120)}deg`),s.style.setProperty("--emoji-duration",`${u}ms`),s.style.animationDelay=`${l}ms`,o.appendChild(s),window.setTimeout(()=>s.remove(),u+l+250)}}updateInfoElement(e,t,i){let o=this.currentOutputElement.querySelector(`#${e}`);o||(o=document.createElement("div"),o.id=e,o.className="info-block",o.innerHTML=`
1639
1655
  <div class='info-block-icon'></div>
1640
1656
  <div class='info-block-text'></div>
1641
- `,this.currentOutputElement.appendChild(o));let s=Pt().use(Wt).use(Dt).use(Gt).use(Zt).use(At,{target:"_blank",rel:["noopener","noreferrer"]}).use(Lt).use(Nt).processSync(t||"");o.querySelector(".info-block-icon").className="info-block-icon "+i,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){}updateBrandingFor(e){this.updateBrandingText(e)}updateBrandingText(e){let t=this.root?.querySelector("#poweredby");if(!t){console.warn("Powered by element not found for branding update.");return}e?.toLowerCase()==="chatterly"?t.innerHTML="<span>powered by <strong><i class='green-accent'>Chatterly</i></strong></span>":t.innerHTML="<span>powered by <strong>IntelliWeave <i class='green-accent'>AI</i></strong></span>"}};ae.tagName="intelliweave-embed",ae.observedAttributes=["logo","focusID","open","collapsed","background","textColor","fontFamily","displayMode","layout","header","positioningMode","positionX","positionY","offsetX","offsetY","brandName"];function Zt(){return a=>{ot(a,"element",(n,e,t)=>{!t||e==null||n.tagName==="table"&&(t.children[e]={type:"element",tagName:"div",properties:{className:["table-scroll-wrapper"]},children:[n]})})}}var Xt=new f("React"),Er=a=>typeof window>"u"?null:(ae.register(),b().analytics=a.analytics??b().analytics,b().debug=a.debug??b().debug,a.context&&(b().pageSummary=a.context),a.introductionMessage&&(b().introductionMessage=a.introductionMessage),a.introductionSuggestions&&(b().introductionSuggestions=a.introductionSuggestions),a.userID&&(b().userID=a.userID),Ke(()=>{let n=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",n),()=>document.removeEventListener("webweaver_kb_search",n)},[a.knowledgeBase]),Rt.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,layout:a.layout,header:a.header,positioningMode:a.positioningMode,positionX:a.positionX,positionY:a.positionY})),Bt=xi(void 0);function Ar(a){function n(){Xt.debug("Creating new IntelliWeave instance for <IntelliWeaveProvider />");let t=new Y;return U.isSupported&&(t.audio=new U(t)),t.load(a.apiKey),t}b().analytics=a.analytics??b().analytics,b().debug=a.debug??b().debug;let e=Ii(()=>a.ai||n(),[a.ai,a.apiKey]);return Ke(()=>{let t=i=>{let o=i;o.detail.isFinal&&e.sendMessage(o.detail.transcript)};return e.audio?.speechRecognition.addEventListener("speech",t),()=>{e.audio?.speechRecognition.removeEventListener("speech",t)}}),Rt.createElement(Bt.Provider,{value:e},a.children)}function Lr(){let[a,n]=lt(0),e=Mi(Bt)||b().embed?.ai;e||Xt.warn("Couldn't find IntelliWeave instance. Make sure you have <IntelliWeaveProvider /> somewhere in your scene graph, or use the <WebWeaverUI /> component.");let[,t]=lt(!!e?.loaded),[,i]=lt(e?.error);return Ke(()=>{let o=l=>t(l.detail.ai.loaded),s=l=>i(l.detail.ai.error),r=()=>n(l=>l+1);return e?.addEventListener("load",o),e?.addEventListener("error",s),e?.addEventListener("input",r),e?.addEventListener("output",r),e?.addEventListener("toolstart",r),e?.addEventListener("tool",r),()=>{e?.removeEventListener("load",o),e?.removeEventListener("error",s),e?.removeEventListener("input",r),e?.removeEventListener("output",r),e?.removeEventListener("toolstart",r),e?.removeEventListener("tool",r)}},[e]),e}function Nr(a,n=[]){Ke(()=>{let e=t=>t.sources.push({query:a});return document.addEventListener("webweaver_kb_search",e),()=>document.removeEventListener("webweaver_kb_search",e)},n)}export{Ar as IntelliWeaveProvider,Er as WebWeaverUI,Lr as useIntelliWeave,Nr as useIntelliWeaveKnowledge};
1657
+ `,this.currentOutputElement.appendChild(o));let r=Pt().use(Wt).use(Dt).use(Gt).use(Zt).use(Nt,{target:"_blank",rel:["noopener","noreferrer"]}).use(At).use(Lt).processSync(t||"");o.querySelector(".info-block-icon").className="info-block-icon "+i,o.querySelector(".info-block-text").innerHTML=r.toString("utf-8")}onSuggestionClick(e,t){this.processInput(t)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}onContentScroll(e){}updateBrandingFor(e){this.updateBrandingText(e)}updateBrandingText(e){let t=this.root?.querySelector("#poweredby");if(!t){console.warn("Powered by element not found for branding update.");return}e?.toLowerCase()==="chatterly"?t.innerHTML="<span>powered by <strong><i class='green-accent'>Chatterly</i></strong></span>":t.innerHTML="<span>powered by <strong>IntelliWeave <i class='green-accent'>AI</i></strong></span>"}};ue.tagName="intelliweave-embed",ue.observedAttributes=["logo","focusID","open","collapsed","background","textColor","fontFamily","displayMode","layout","header","positioningMode","positionX","positionY","offsetX","offsetY","brandName","brandNameColor","hidePoweredBy"];function Zt(){return a=>{nt(a,"element",(n,e,t)=>{!t||e==null||n.tagName==="table"&&(t.children[e]={type:"element",tagName:"div",properties:{className:["table-scroll-wrapper"]},children:[n]})})}}var Xt=new f("React"),Es=a=>typeof window>"u"?null:(ue.register(),b().analytics=a.analytics??b().analytics,b().debug=a.debug??b().debug,a.context&&(b().pageSummary=a.context),a.introductionMessage&&(b().introductionMessage=a.introductionMessage),a.introductionSuggestions&&(b().introductionSuggestions=a.introductionSuggestions),a.userID&&(b().userID=a.userID),He(()=>{let n=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",n),()=>document.removeEventListener("webweaver_kb_search",n)},[a.knowledgeBase]),Rt.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,layout:a.layout,header:a.header,positioningMode:a.positioningMode,positionX:a.positionX,positionY:a.positionY,brandName:a.brandName,brandNameColor:a.brandNameColor,hidePoweredBy:a.hidePoweredBy?"true":void 0})),Bt=xi(void 0);function Ns(a){function n(){Xt.debug("Creating new IntelliWeave instance for <IntelliWeaveProvider />");let t=new U;return H.isSupported&&(t.audio=new H(t)),t.load(a.apiKey),t}b().analytics=a.analytics??b().analytics,b().debug=a.debug??b().debug;let e=Ii(()=>a.ai||n(),[a.ai,a.apiKey]);return He(()=>{let t=i=>{let o=i;o.detail.isFinal&&e.sendMessage(o.detail.transcript)};return e.audio?.speechRecognition.addEventListener("speech",t),()=>{e.audio?.speechRecognition.removeEventListener("speech",t)}}),Rt.createElement(Bt.Provider,{value:e},a.children)}function As(){let[a,n]=at(0),e=Mi(Bt)||b().embed?.ai;e||Xt.warn("Couldn't find IntelliWeave instance. Make sure you have <IntelliWeaveProvider /> somewhere in your scene graph, or use the <WebWeaverUI /> component.");let[,t]=at(!!e?.loaded),[,i]=at(e?.error);return He(()=>{let o=l=>t(l.detail.ai.loaded),r=l=>i(l.detail.ai.error),s=()=>n(l=>l+1);return e?.addEventListener("load",o),e?.addEventListener("error",r),e?.addEventListener("input",s),e?.addEventListener("output",s),e?.addEventListener("toolstart",s),e?.addEventListener("tool",s),()=>{e?.removeEventListener("load",o),e?.removeEventListener("error",r),e?.removeEventListener("input",s),e?.removeEventListener("output",s),e?.removeEventListener("toolstart",s),e?.removeEventListener("tool",s)}},[e]),e}function Ls(a,n=[]){He(()=>{let e=t=>t.sources.push({query:a});return document.addEventListener("webweaver_kb_search",e),()=>document.removeEventListener("webweaver_kb_search",e)},n)}export{Ns as IntelliWeaveProvider,Es as WebWeaverUI,As as useIntelliWeave,Ls as useIntelliWeaveKnowledge};