@intelliweave/embedded 2.0.72-beta.12 → 2.0.72-beta.13
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.
- package/dist/component/component.d.ts +4 -0
- package/dist/component/component.js +4 -4
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.d.ts +4 -0
- package/dist/node/node.js +5 -5
- package/dist/react/react.d.ts +4 -0
- package/dist/react/react.js +9 -9
- package/dist/script-tag/script-tag.js +4 -4
- package/dist/webpack/index.d.ts +4 -0
- package/dist/webpack/index.js +4 -4
- package/package.json +1 -1
package/dist/react/react.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import st,{createContext as Zt,useContext as Dt,useEffect as ve,useMemo as Xt,useState as Ge}from"react";import ut from"openai";import{v4 as lt}from"uuid";var L=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new Ce;return e.id=i,this.groups.push(e),e}group(i){return this.groups.find(e=>e.id===i)}static countTokensInText(i){return i==null?i="":typeof i=="number"?i=i+"":typeof i!="string"&&(i=JSON.stringify(i)),Math.ceil(i.length/3)}countTokens(){return this.groups.reduce((i,e)=>i+e.tokenCount,0)}removeOverflow(){let i=this.countTokens(),e=this.groups.reduce((t,n)=>t+n.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((o,s)=>{let a=Math.floor(o.weight/e*this.size),l=Math.floor(s.weight/e*this.size),u=o.tokenCount-a;return s.tokenCount-l-u}),n=this.removeOneItem(t);if(!n)throw new Error("Too many items in the token window that cannot be removed.");i-=n.tokenCount}}removeOneItem(i){for(let e of i){let t=e.items.findIndex(o=>!o.cannotRemove);if(t===-1)continue;let n=e.items[t];return e.items.splice(t,1),e.tokenCount-=n.tokenCount,n}return null}},Ce=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
2
2
|
`;this.itemPadding=0;this.sortFunction=(i,e)=>i.sortOrder!==e.sortOrder?i.sortOrder-e.sortOrder:i.dateAdded!==e.dateAdded?i.dateAdded-e.dateAdded:0}setItemPadding(i){return this.itemPadding=i,this.recalculateTokens(),this}sortBy(i){return this.sortFunction=i,this.items.sort(this.sortFunction),this}setSeparator(i){return this.separator==i?this:(this.separator=i,this.recalculateTokens(),this)}setWeight(i){return this.weight=i,this}recalculateTokens(){this.tokenCount=this.items.reduce((i,e)=>(e.tokenCount=L.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+L.countTokensInText(this.separator)+this.itemPadding,i+e.tokenCount),0)}add(i){typeof i=="string"&&(i={source:"user",data:i});let e=i;e.id===void 0&&(e.id=lt()),!e.sections?.length&&typeof e.data=="string"?e.text=e.data:e.text=e.sections?.map(n=>{if(n.type==="text")return n.text||"";if(n.type==="tool_call")return`[Tool Call: ${n.toolKbName||n.toolName}] `;if(n.type==="tool_result"&&n.toolErrorResponse)return`[Tool Error: ${n.toolErrorResponse}] `}).filter(n=>!!n).join(`
|
|
3
3
|
|
|
4
|
-
`)||"";let t=this.items.find(n=>n.id===e.id);return t?(this.tokenCount-=t.tokenCount,Object.assign(t,e),e=t):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.source===void 0&&(e.source="user"),e.sections===void 0&&(e.sections=[]),e.tokenCount=e.disabled?0:L.countTokensInText(typeof i.data=="string"?i.data:JSON.stringify(i.data))+L.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}getAllAsString(){return this.getAll().map(i=>i.text).join(this.separator)}getAll(){return this.items.filter(i=>!i.disabled)}empty(){this.items=[],this.tokenCount=0}};import{v4 as dt}from"uuid";import{v4 as Xe}from"uuid";function ee(r){let i=(r||"").split(`
|
|
4
|
+
`)||"";let t=this.items.find(n=>n.id===e.id);return t?(this.tokenCount-=t.tokenCount,Object.assign(t,e),e=t):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.source===void 0&&(e.source="user"),e.sections===void 0&&(e.sections=[]),e.tokenCount=e.disabled?0:L.countTokensInText(typeof i.data=="string"?i.data:JSON.stringify(i.data))+L.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}remove(i){let e=this.items.findIndex(t=>t.id===i);return e===-1?!1:(this.tokenCount-=this.items[e].tokenCount||0,this.items.splice(e,1),!0)}getAllAsString(){return this.getAll().map(i=>i.text).join(this.separator)}getAll(){return this.items.filter(i=>!i.disabled)}empty(){this.items=[],this.tokenCount=0}};import{v4 as dt}from"uuid";import{v4 as Xe}from"uuid";function ee(r){let i=(r||"").split(`
|
|
5
5
|
`);for(;i.length>0&&i[0].trim()=="";)i.shift();for(;i.length>0&&i[i.length-1].trim()=="";)i.pop();let e=1/0;for(let t of i){let n=t.match(/^\s*/)?.[0].length||0;e=Math.min(e,n)}return e>0&&e<1/0&&(i=i.map(t=>t.substring(e))),i.join(`
|
|
6
6
|
`)}var ct={};function A(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:ct}function h(){return A().intelliweave=A().intelliweave||A().webWeaver||{},A().intelliweave}function Re(){if(h().userID)return h().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let r=localStorage.getItem("intelliweave.uid")||"";return r||(r=Xe(),localStorage.setItem("intelliweave.uid",r),r)}else return Xe()}function Pe(r){let i=r;if(i?.type=="object"&&i.properties)return r;let e={type:"object",properties:{},required:[]};if(r&&Array.isArray(r)){let t=r;for(let n of t)e.properties[n.name]={type:n.type||"string",description:n.description||""}}return e}var te=class te{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return te.debug?!0:typeof window<"u"&&h().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...n)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...n)}};te.debug=!1;var p=te;var Ve=new p("ChatBase"),X=class{constructor(i){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let i=new L;return i.createGroup("context").setSeparator(`
|
|
7
7
|
|
|
@@ -12,7 +12,7 @@ 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"||!r?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),n=encodeURIComponent(i.subject),o=encodeURIComponent(i.body),s=`mailto:${t}?subject=${n}&body=${o}`;try{window.location.href=s}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as ft}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as yt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var E={name:"@intelliweave/embedded",version:"2.0.72-beta.12",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.95","@types/lodash":"^4.17.23","@types/react":"^18.3.12",bestzip:"^2.2.1","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.17",vitest:"^4.0.18"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.74.0","@modelcontextprotocol/sdk":"^1.26.0","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.22.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{LoggingMessageNotificationSchema as bt,ToolListChangedNotificationSchema as wt}from"@modelcontextprotocol/sdk/types.js";var y=new p("MCPKnowledgeClient"),vt="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",oe=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){y.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new URL(this.config.baseURL),t={};this.config.headers&&(t={...t,...this.config.headers}),this.config.proxy?.enabled&&(t["Mcp-Target-Url"]=e.toString(),t["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",e=new URL(this.config.proxy.url||vt));let n=new ft({name:E.name,version:E.version}),o=new yt(e,{requestInit:{headers:t}});return await n.connect(o),y.debug("Connected with HTTP streaming mode"),n});return await this.disconnect(),this.client=i,i.onerror=e=>{y.error(`MCP client error: ${e.message}`)},i.onclose=()=>{y.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(bt,e=>{e.params.level=="critical"?y.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?y.error(`[Server] ${e.params.data}`):e.params.level=="error"?y.error(`[Server] ${e.params.data}`):e.params.level=="warning"?y.warn(`[Server] ${e.params.data}`):e.params.level=="info"?y.info(`[Server] ${e.params.data}`):e.params.level=="debug"?y.debug(`[Server] ${e.params.data}`):y.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(wt,e=>{y.debug("Tool list changed",e),this.fetchTools()}),y.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let o of n.tools||[])i.push(o);if(!n?.tools?.length||!e)break}let t=[];for(let n of i){let o=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:s=>this.performToolCall(n.name,s),disabled:o})}y.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,y.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(o=>o.name==this.config.searchToolName);if(!t)return y.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(t.inputSchema.required?.length==1){let o=t.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let o=Object.keys(t.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let o=0;o<n.length;o++){let s=n[o];e.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(i,e){await this.connect(),y.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let n=t.content?.[0]?.text||"Unknown error";throw y.error(`Error calling tool ${i}: ${n}`),new Error(`Error calling tool ${i}: ${n}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};import{v4 as xt}from"uuid";var Mt=new p("Statistics"),U=[];async function w(r,i){let e={...i,event_id:xt(),event_date:new Date().toISOString(),sdk_version:E.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(U.push(e),!r||(await new Promise(n=>setTimeout(n,5e3)),U.length===0))return;let t=U.slice();U.length=0;try{let n=await fetch(r.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){Mt.warn("Failed to submit analytics event:",n),U.push(...t);return}}var Z=new p("KnowledgeBase"),Ae=1,se=class r{constructor(i){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=i,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(i=>i.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>ze(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${Ae++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return this.allowGlobalConfigSources&&h().knowledgeBaseSources&&(i=i.concat(h().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(i=i.concat(this._windowSources)),i=i.filter(e=>!e.disabled),i}async search(i){Z.debug(`Searching knowledge base for: ${i}`);let e=Date.now(),t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(t),this._windowSources=t.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async u=>{try{let c=Date.now(),d=await u.query(i);return Z.debug(`Source '${u.id}' took ${Date.now()-c}ms`),d||[]}catch(c){return Z.warn(`Knowledge source '${u.id}' failed:`,c),[]}}))).flat();o=o.concat(t.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&h().knowledgeBase&&(o=o.concat(h().knowledgeBase)),o=o.filter(u=>u&&!u.disabled);for(let u=0;u<o.length;u++){let c=o[u];c.id=c.id||`temp.${u}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new It({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(i).map(u=>o.find(c=>c.id==u.id));for(let u of o)u.isContext&&(l.find(c=>c.id===u.id)||l.push(u));return this.lastResults=l,w(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),Z.debug("Found results:",l),l}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${Ae++}`),Z.debug(`Registering remote knowledge base source: ${i}`);let t=[],n=[],o=!0,s=async(l,u)=>{Z.debug(`Calling remote knowledge base action: ${l.id}`);let c={type:"action",userID:this.ai.userID,actionID:l.id,parameters:u},d=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let g=await d.json();return a(g.updateItems||[]),g.response},a=l=>{for(let u of l){if(!u.id){Z.warn("KB item skipped since it has no ID.",u);continue}let c=t.find(d=>d.id==u.id);if(c){c.name=u.name||c.name||"",c.content=u.content||c.content||"",c.disabled=u.disabled??c.disabled,c.isContext=u.isContext??c.isContext,c.parameters=u.parameters||c.parameters||[],c.tags=u.tags||c.tags,c.type=u.type||c.type;continue}t.push({...u,action:d=>s(u,d)})}};this.registerSource(e,async l=>{if(o&&n.includes(l))return t;let u={type:"search",userID:this.ai?.userID||"",query:l},c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let d=await c.json();return o=!d.noCache,n.includes(l)||n.push(l),a(d.items),t})}clone(i){let e=new r(i);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(i){i.id||(i.id=`external.${Ae++}`);let e=new oe(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ae=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
15
|
+
${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),n=encodeURIComponent(i.subject),o=encodeURIComponent(i.body),s=`mailto:${t}?subject=${n}&body=${o}`;try{window.location.href=s}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as ft}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as yt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var E={name:"@intelliweave/embedded",version:"2.0.72-beta.13",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.95","@types/lodash":"^4.17.23","@types/react":"^18.3.12",bestzip:"^2.2.1","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.17",vitest:"^4.0.18"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.74.0","@modelcontextprotocol/sdk":"^1.26.0","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.22.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{LoggingMessageNotificationSchema as bt,ToolListChangedNotificationSchema as wt}from"@modelcontextprotocol/sdk/types.js";var y=new p("MCPKnowledgeClient"),vt="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",oe=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){y.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new URL(this.config.baseURL),t={};this.config.headers&&(t={...t,...this.config.headers}),this.config.proxy?.enabled&&(t["Mcp-Target-Url"]=e.toString(),t["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",e=new URL(this.config.proxy.url||vt));let n=new ft({name:E.name,version:E.version}),o=new yt(e,{requestInit:{headers:t}});return await n.connect(o),y.debug("Connected with HTTP streaming mode"),n});return await this.disconnect(),this.client=i,i.onerror=e=>{y.error(`MCP client error: ${e.message}`)},i.onclose=()=>{y.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(bt,e=>{e.params.level=="critical"?y.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?y.error(`[Server] ${e.params.data}`):e.params.level=="error"?y.error(`[Server] ${e.params.data}`):e.params.level=="warning"?y.warn(`[Server] ${e.params.data}`):e.params.level=="info"?y.info(`[Server] ${e.params.data}`):e.params.level=="debug"?y.debug(`[Server] ${e.params.data}`):y.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(wt,e=>{y.debug("Tool list changed",e),this.fetchTools()}),y.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let o of n.tools||[])i.push(o);if(!n?.tools?.length||!e)break}let t=[];for(let n of i){let o=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:s=>this.performToolCall(n.name,s),disabled:o})}y.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,y.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(o=>o.name==this.config.searchToolName);if(!t)return y.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(t.inputSchema.required?.length==1){let o=t.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let o=Object.keys(t.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let o=0;o<n.length;o++){let s=n[o];e.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(i,e){await this.connect(),y.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let n=t.content?.[0]?.text||"Unknown error";throw y.error(`Error calling tool ${i}: ${n}`),new Error(`Error calling tool ${i}: ${n}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};import{v4 as xt}from"uuid";var Mt=new p("Statistics"),K=[];async function w(r,i){let e={...i,event_id:xt(),event_date:new Date().toISOString(),sdk_version:E.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(K.push(e),!r||(await new Promise(n=>setTimeout(n,5e3)),K.length===0))return;let t=K.slice();K.length=0;try{let n=await fetch(r.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){Mt.warn("Failed to submit analytics event:",n),K.push(...t);return}}var Z=new p("KnowledgeBase"),Ae=1,se=class r{constructor(i){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=i,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(i=>i.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>ze(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${Ae++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return this.allowGlobalConfigSources&&h().knowledgeBaseSources&&(i=i.concat(h().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(i=i.concat(this._windowSources)),i=i.filter(e=>!e.disabled),i}async search(i){Z.debug(`Searching knowledge base for: ${i}`);let e=Date.now(),t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(t),this._windowSources=t.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async u=>{try{let c=Date.now(),d=await u.query(i);return Z.debug(`Source '${u.id}' took ${Date.now()-c}ms`),d||[]}catch(c){return Z.warn(`Knowledge source '${u.id}' failed:`,c),[]}}))).flat();o=o.concat(t.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&h().knowledgeBase&&(o=o.concat(h().knowledgeBase)),o=o.filter(u=>u&&!u.disabled);for(let u=0;u<o.length;u++){let c=o[u];c.id=c.id||`temp.${u}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new It({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(i).map(u=>o.find(c=>c.id==u.id));for(let u of o)u.isContext&&(l.find(c=>c.id===u.id)||l.push(u));return this.lastResults=l,w(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),Z.debug("Found results:",l),l}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${Ae++}`),Z.debug(`Registering remote knowledge base source: ${i}`);let t=[],n=[],o=!0,s=async(l,u)=>{Z.debug(`Calling remote knowledge base action: ${l.id}`);let c={type:"action",userID:this.ai.userID,actionID:l.id,parameters:u},d=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let g=await d.json();return a(g.updateItems||[]),g.response},a=l=>{for(let u of l){if(!u.id){Z.warn("KB item skipped since it has no ID.",u);continue}let c=t.find(d=>d.id==u.id);if(c){c.name=u.name||c.name||"",c.content=u.content||c.content||"",c.disabled=u.disabled??c.disabled,c.isContext=u.isContext??c.isContext,c.parameters=u.parameters||c.parameters||[],c.tags=u.tags||c.tags,c.type=u.type||c.type;continue}t.push({...u,action:d=>s(u,d)})}};this.registerSource(e,async l=>{if(o&&n.includes(l))return t;let u={type:"search",userID:this.ai?.userID||"",query:l},c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let d=await c.json();return o=!d.noCache,n.includes(l)||n.push(l),a(d.items),t})}clone(i){let e=new r(i);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(i){i.id||(i.id=`external.${Ae++}`);let e=new oe(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ae=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
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(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
18
18
|
|
|
@@ -31,7 +31,7 @@ ${i.extractions.map(n=>`- ${n.name} (${n.type}): ${n.description||"No descriptio
|
|
|
31
31
|
`,t=await this.instruct({...i,instruction:e});if(t=t.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),i.allowMultiple){let n=t.split(`
|
|
32
32
|
`).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of n)try{o.push(JSON.parse(s))}catch(a){console.error("Failed to parse line as JSON:",s,a.message)}return o}else return[JSON.parse(t.trim())]}async generateMarkdown(i){return this.instruct({...i,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(i){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>i.instruction,i.callback&&e.addEventListener("output",t=>{i.callback(t.detail.message)}),i.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof i.data=="string"?i.data:JSON.stringify(i.data)).then(t=>t.text())}};var P=class{constructor(i){this.messages=i}text(){return this.messages?.flatMap(i=>i.sections)?.filter(i=>i?.type=="text")?.map(i=>i?.text||"")?.filter(i=>!!i)?.join(`
|
|
33
33
|
|
|
34
|
-
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((i,e)=>i+(e.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(i=>i.sections||[])||[]}toolCalls(){return this.messages?.flatMap(i=>i.sections?.filter(e=>e.type=="tool_call")||[])||[]}toolResult(i){return this.messages?.map(e=>e.sections?.find(t=>t.type=="tool_result"&&t.toolCallInstanceID==i)).filter(e=>!!e)[0]||null}};var re=class{constructor(i){this.subagents=[];this.cachedSubagents={};this.ai=i}register(i){if(this.subagents.find(e=>e.id==i.id))throw new Error(`Sub-agent with ID ${i.id} already exists`);this.subagents.push(i),this.ai.knowledgeBase.registerSource("subagent:"+i.id,e=>[{type:"action",id:"ask:"+i.id,name:`Ask ${i.name||"subagent"}`,content:i.usageInstructions||`Use this tool to ask ${i.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(t,n)=>await this.runQuery(i,t.query)}])}remove(i){this.subagents=this.subagents.filter(e=>e.id!=i),this.ai.knowledgeBase.removeSource("subagent:"+i)}async runQuery(i,e){let t=i.apiKey||this.ai.apiKey,n=this.cachedSubagents[t];return n||(n=new N,await n.load(t,i.config),this.cachedSubagents[t]=n),n=n.clone(),n.knowledgeBase.allowGlobalConfigSources=!1,n.knowledgeBase.allowWindowSources=!1,i.clearExistingKnowledge&&n.knowledgeBase.reset(),n.knowledgeBase.allowRagSearch=!i.disableRagSearch,i.knowledge&&n.knowledgeBase.registerSource(i.knowledge),i.onAgentLoaded&&await i.onAgentLoaded(n),(await n.sendMessage(e)).text()}};var M=new p("Main"),je=new Set,D=class D extends EventTarget{constructor(){super(...arguments);this.conversationID=_e();this.knowledgeBase=new se(this);this.subAgents=new re(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new ae(this);this.userID=Re();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:D.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(e,t){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{M.debug("Loading configuration...");let n=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!n.ok)throw new Error(`Failed to load configuration: ${n.status} ${n.statusText}`);try{this.config=await n.json(),M.debug("Config loaded successfully:",this.config),t&&(this.config={...this.config,...t}),this.config&&M.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){M.error("Failed to parse JSON response:",o);try{let s=await n.clone().text();M.error("Raw response that failed parsing:",s)}catch{M.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let n=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!n.ok)throw new Error(`Failed to load VAD model: ${n.status} ${n.statusText}`);this.vadModel=await n.blob()}catch(n){M.warn(`Failed to load VAD model, some features will be unavailable. ${n.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let n of this.config.knowledge||[])n.url&&n.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:n.id,searchToolName:n.mcpSearchToolName,baseURL:n.url}):n.url&&this.knowledgeBase.registerSourceFromURL(n.url);for(let n of this.config.knowledge||[])n.entries?.length&&this.knowledgeBase.registerSource(n.id,()=>n.entries||[]);if(this.config.mcpServers)for(let n of this.config.mcpServers)this.knowledgeBase.registerMCPSource(n);for(let n of this.config.subagents||[])this.subAgents.register(n);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(n){throw M.warn("Failed to load:",n),this.error=n,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:n}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:n}})),n}}setModel(e){let t=this.models.find(o=>o.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let n={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(n):t.config.providerID==="anthropic"?this.currentModel=new ne(n):this.currentModel=new ie(n),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=h().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let t=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:t}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:ee(`
|
|
34
|
+
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((i,e)=>i+(e.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(i=>i.sections||[])||[]}toolCalls(){return this.messages?.flatMap(i=>i.sections?.filter(e=>e.type=="tool_call")||[])||[]}toolResult(i){return this.messages?.map(e=>e.sections?.find(t=>t.type=="tool_result"&&t.toolCallInstanceID==i)).filter(e=>!!e)[0]||null}};var re=class{constructor(i){this.subagents=[];this.cachedSubagents={};this.ai=i}register(i){if(this.subagents.find(e=>e.id==i.id))throw new Error(`Sub-agent with ID ${i.id} already exists`);this.subagents.push(i),this.ai.knowledgeBase.registerSource("subagent:"+i.id,e=>[{type:"action",id:"ask:"+i.id,name:`Ask ${i.name||"subagent"}`,content:i.usageInstructions||`Use this tool to ask ${i.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(t,n)=>await this.runQuery(i,t.query)}])}remove(i){this.subagents=this.subagents.filter(e=>e.id!=i),this.ai.knowledgeBase.removeSource("subagent:"+i)}async runQuery(i,e){let t=i.apiKey||this.ai.apiKey,n=this.cachedSubagents[t];return n||(n=new N,await n.load(t,i.config),this.cachedSubagents[t]=n),n=n.clone(),n.knowledgeBase.allowGlobalConfigSources=!1,n.knowledgeBase.allowWindowSources=!1,i.clearExistingKnowledge&&n.knowledgeBase.reset(),n.knowledgeBase.allowRagSearch=!i.disableRagSearch,i.knowledge&&n.knowledgeBase.registerSource(i.knowledge),i.onAgentLoaded&&await i.onAgentLoaded(n),(await n.sendMessage(e)).text()}};var M=new p("Main"),je=new Set,D=class D extends EventTarget{constructor(){super(...arguments);this.conversationID=_e();this.knowledgeBase=new se(this);this.subAgents=new re(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new ae(this);this.userID=Re();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:D.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(e,t){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{M.debug("Loading configuration...");let n=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!n.ok)throw new Error(`Failed to load configuration: ${n.status} ${n.statusText}`);try{this.config=await n.json(),M.debug("Config loaded successfully:",this.config),t&&(this.config={...this.config,...t}),this.config&&M.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){M.error("Failed to parse JSON response:",o);try{let s=await n.clone().text();M.error("Raw response that failed parsing:",s)}catch{M.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let n=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!n.ok)throw new Error(`Failed to load VAD model: ${n.status} ${n.statusText}`);this.vadModel=await n.blob()}catch(n){M.warn(`Failed to load VAD model, some features will be unavailable. ${n.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let n of this.config.knowledge||[])n.url&&n.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:n.id,searchToolName:n.mcpSearchToolName,baseURL:n.url}):n.url&&this.knowledgeBase.registerSourceFromURL(n.url);for(let n of this.config.knowledge||[])n.entries?.length&&this.knowledgeBase.registerSource(n.id,()=>n.entries||[]);if(this.config.mcpServers)for(let n of this.config.mcpServers)this.knowledgeBase.registerMCPSource(n);for(let n of this.config.subagents||[])this.subAgents.register(n);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(n){throw M.warn("Failed to load:",n),this.error=n,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:n}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:n}})),n}}setModel(e){let t=this.models.find(o=>o.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let n={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(n):t.config.providerID==="anthropic"?this.currentModel=new ne(n):this.currentModel=new ie(n),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=h().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let t=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:t}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:ee(`
|
|
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.
|
|
@@ -47,12 +47,12 @@ attachments:
|
|
|
47
47
|
mimetype: "${a.mimeType||""}"
|
|
48
48
|
url: "${a.url}"
|
|
49
49
|
`);s||(o+="```\n"),this.currentModel.contextGroup.add({id:n.id,data:`## ${n.type}: ${n.name}
|
|
50
|
-
${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="function"?n.disabled(this):n.disabled})}else if(n.type=="action"){let o={name:n._functionID,description:ee(n.content),params:Pe(n.parameters||[{name:"value",type:"string",description:"Input"}]),callback:s=>this.toolRunKBAction(n,s),canRemove:!n.isContext,kbItem:n};this.currentModel.registerTool(o)}else continue}processIncomingMessage(e,t){if(!t){let n=this.currentModel?.stats?.tokensUsed||0,o=e.reduce((s,a)=>s+(a.usage?.totalTokens||0),0);w(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:n}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:t,messages:e}})),this.onAIMessage?.(e,!!t)}async sendMessage(e,t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),je.has(this.conversationID)||(je.add(this.conversationID),w(this,{event_type:"session_start"})),w(this,{event_type:"message_send",value_str:"",event_properties:{message_length:e.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),this.submitAnalyticsEvent({type:"message",role:"user",message:e});let n=Date.now(),o=await this.currentModel.sendMessage(e),s=new P(o);(this._voiceTracker||M.debug.bind(M))(`LLM response took ${Date.now()-n}ms`);let l=this.currentModel.contextGroup.getAllAsString();l+=`
|
|
50
|
+
${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="function"?n.disabled(this):n.disabled})}else if(n.type=="action"){let o={name:n._functionID,description:ee(n.content),params:Pe(n.parameters||[{name:"value",type:"string",description:"Input"}]),callback:s=>this.toolRunKBAction(n,s),canRemove:!n.isContext,kbItem:n};this.currentModel.registerTool(o)}else continue;for(let n of this.lastKBItems)!n.isContext||!n.id||e.find(s=>s.id==n.id)||(this.currentModel.contextGroup.remove(n.id),n._functionID&&this.currentModel.toolGroup.remove(n._functionID));this.lastKBItems=e}processIncomingMessage(e,t){if(!t){let n=this.currentModel?.stats?.tokensUsed||0,o=e.reduce((s,a)=>s+(a.usage?.totalTokens||0),0);w(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:n}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:t,messages:e}})),this.onAIMessage?.(e,!!t)}async sendMessage(e,t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),je.has(this.conversationID)||(je.add(this.conversationID),w(this,{event_type:"session_start"})),w(this,{event_type:"message_send",value_str:"",event_properties:{message_length:e.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),this.submitAnalyticsEvent({type:"message",role:"user",message:e});let n=Date.now(),o=await this.currentModel.sendMessage(e),s=new P(o);(this._voiceTracker||M.debug.bind(M))(`LLM response took ${Date.now()-n}ms`);let l=this.currentModel.contextGroup.getAllAsString();l+=`
|
|
51
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 c of u.sections||[])if(c.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:c.text||""});else if(c.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:c.text||""});else if(c.type=="tool_call"){let d=s.toolResult(c.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:c.toolKbID||"",actionName:c.toolKbName||"",value:c.toolParameters,result:d?.toolErrorResponse||d?.toolSuccessResponse,isError:!!d?.toolErrorResponse})}else c.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let n=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:t,ai:this}}));let o=await e.action(t,this),s=Date.now()-n;return w(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:s,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,result:o}})),o}catch(o){let s=Date.now()-n;throw w(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:s,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,error:o}})),o}}submitAnalyticsEvent(e){if(h().analytics===!1||this.config?.analytics===!1)return;let t=fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(n=>{M.debug("Failed to submit analytics event:",n)});this.activeAnalyticsPromises.push(t),t.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(n=>n!==t)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=_e(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(e)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let t of e.messages)this.currentModel.messageGroup.add(t)}clone(){let e=new D;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.knowledgeBase=this.knowledgeBase.clone(e),e}get messages(){return this.currentModel?.messageGroup.items||[]}};D.version=E.version,D.builtInActionsVersion="1.0.0",M.debug(`Loaded: version=${E.version} builtInActionsVersion=${D.builtInActionsVersion}`);var N=D;var x=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(e={},t=""){this.register();let n=document.createElement(this.tagName);for(let o in e)n.setAttribute(o,e[o]);return n.onBeforeCreate(),n.innerHTML=t,n}static add(e={},t=""){this.register();let n=o=>o.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">");return`<${this.tagName} ${Object.keys(e).map(o=>`${o}="${n(e[o]+"")}"`).join(" ")}>${t}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(e,t,n){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(e,t)=>this.getAttribute(t.toString())||"",set:(e,t,n)=>(this.getAttribute(t.toString())===n||(n?this.setAttribute(t.toString(),n):this.removeAttribute(t.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(e,t)=>this._state[t],set:(e,t,n)=>(this._state[t]=n,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(e){return!!this.root?.getElementById(e)}child(e){let t=this.root?.getElementById(e);if(!t)throw new Error(`Child with ID ${e} not found`);return t}};x.observedAttributes=[],x.tagName="",x._isRegistered=!1;var Oe='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var Ye='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Ue='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var K=class extends x{constructor(){super(...arguments);this.html=()=>`
|
|
55
|
+
`),this._lastSystemMsg!=l&&(this._lastSystemMsg=l,this.submitAnalyticsEvent({type:"system-msg",txt:l}));for(let u of o)for(let c of u.sections||[])if(c.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:c.text||""});else if(c.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:c.text||""});else if(c.type=="tool_call"){let d=s.toolResult(c.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:c.toolKbID||"",actionName:c.toolKbName||"",value:c.toolParameters,result:d?.toolErrorResponse||d?.toolSuccessResponse,isError:!!d?.toolErrorResponse})}else c.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let n=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:t,ai:this}}));let o=await e.action(t,this),s=Date.now()-n;return w(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:s,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,result:o}})),o}catch(o){let s=Date.now()-n;throw w(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:s,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,error:o}})),o}}submitAnalyticsEvent(e){if(h().analytics===!1||this.config?.analytics===!1)return;let t=fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(n=>{M.debug("Failed to submit analytics event:",n)});this.activeAnalyticsPromises.push(t),t.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(n=>n!==t)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=_e(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(e)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let t of e.messages)this.currentModel.messageGroup.add(t)}clone(){let e=new D;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.knowledgeBase=this.knowledgeBase.clone(e),e}get messages(){return this.currentModel?.messageGroup.items||[]}};D.version=E.version,D.builtInActionsVersion="1.0.0",M.debug(`Loaded: version=${E.version} builtInActionsVersion=${D.builtInActionsVersion}`);var N=D;var x=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(e={},t=""){this.register();let n=document.createElement(this.tagName);for(let o in e)n.setAttribute(o,e[o]);return n.onBeforeCreate(),n.innerHTML=t,n}static add(e={},t=""){this.register();let n=o=>o.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">");return`<${this.tagName} ${Object.keys(e).map(o=>`${o}="${n(e[o]+"")}"`).join(" ")}>${t}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(e,t,n){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(e,t)=>this.getAttribute(t.toString())||"",set:(e,t,n)=>(this.getAttribute(t.toString())===n||(n?this.setAttribute(t.toString(),n):this.removeAttribute(t.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(e,t)=>this._state[t],set:(e,t,n)=>(this._state[t]=n,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(e){return!!this.root?.getElementById(e)}child(e){let t=this.root?.getElementById(e);if(!t)throw new Error(`Child with ID ${e} not found`);return t}};x.observedAttributes=[],x.tagName="",x._isRegistered=!1;var Oe='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var Ye='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Ke='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 U=class extends x{constructor(){super(...arguments);this.html=()=>`
|
|
56
56
|
|
|
57
57
|
<!-- Styling -->
|
|
58
58
|
<style>
|
|
@@ -179,7 +179,7 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
179
179
|
}
|
|
180
180
|
|
|
181
181
|
:host #cancel-speech-button {
|
|
182
|
-
background-image: url('${
|
|
182
|
+
background-image: url('${Ke}');
|
|
183
183
|
z-index: 2;
|
|
184
184
|
}
|
|
185
185
|
|
|
@@ -210,7 +210,7 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
210
210
|
<!-- Loader bar -->
|
|
211
211
|
<div id='loader'></div>
|
|
212
212
|
|
|
213
|
-
`;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",e=>this.onInputKeyPress(e),{capture:!0}),this.child("input-field").addEventListener("keydown",e=>e.stopPropagation(),{capture:!0}),this.child("llm-button").addEventListener("click",e=>this.onLLMButtonClick(e)),this.child("send-button").addEventListener("click",e=>this.onSendButtonClick(e)),this.child("microphone-button").addEventListener("click",e=>this.onMicButtonClick(e)),this.child("cancel-speech-button").addEventListener("click",e=>this.onCancelSpeechButtonClick(e))}connectAI(e){this.ai=e,this.ai.audio?.speechRecognition.addEventListener("speech",t=>this.onSpeechEvent(t)),this.ai.audio?.speechRecognition.addEventListener("start",t=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",t=>this.onUpdate()),this.onUpdate()}onUpdate(){this.attr.textColor&&document.documentElement.style.setProperty("--intelliweave-text-color",this.attr.textColor),this.child("input-field").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("llm-button").style.display=this.attr.loading||!this.attr.llmButtonVisible||this.state.micActiv?"none":"",this.child("llm-button").innerText=this.attr.llmName||"LLM",this.child("send-button").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("loader").style.display=this.attr.loading?"block":"",this.child("microphone-button").style.display=!this.ai?.audio?.speechRecognition?.isSupported||this.attr.loading&&!this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("cancel-speech-button").style.display="none",this.ai?.audio?.speechRecognition.isRunning&&this.ai?.audio?.speechOutput.isSpeaking&&(this.child("microphone-button").style.display="none",this.child("cancel-speech-button").style.display=""),!this.attr.loading&&this._wasLoading&&this.child("input-field").focus(),this._wasLoading=this.attr.loading,this.child("microphone-button-bg").classList.toggle("active",!!this.ai?.audio?.speechRecognition.isRunning);let e=this.ai?.audio?.speechRecognition.isRunning&&!this.attr.loading;e&&!this.micStateAnimationTimer?this.micStateAnimationTimer=setInterval(()=>this.onMicAnimation(),1e3/60):!e&&this.micStateAnimationTimer&&(this.voiceAnimationPieces.forEach(t=>t.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(e){if(e.stopPropagation(),e.key!="Enter")return;let t=this.child("input-field"),n=t.value?.trim();t.value="",n&&this.dispatchEvent(new CustomEvent("input-message",{detail:n}))}onLLMButtonClick(e){e.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onSendButtonClick(e){e.preventDefault();let t=this.child("input-field"),n=t.value?.trim();t.value="",n&&this.dispatchEvent(new CustomEvent("input-message",{detail:n}))}onMicButtonClick(e){e.preventDefault(),this.ai.audio?.speechRecognition.isRunning?this.ai.audio?.speechRecognition.stop():this.ai.audio?.speechRecognition.start()}onMicAnimation(){if(!this.attr.loading){if(this._micAnimFrameCounter++,this._micAnimFrameCounter%5==0){let e="rgba(140, 170, 200, 0.5)";this.ai?.audio?.speechRecognition.voiceDetection?.isModelLoaded||(e="rgba(255, 0, 0, 0.5)"),this.ai?.audio?.speechRecognition.voiceDetection?.isTranscribing&&(e="rgba(96, 66, 245, 0.9)"),this.ai?.audio?.speechRecognition.wordsCurrentlyBeingSpoken&&(e="rgba(0, 128, 255, 0.9)"),this.ai?.audio?.speechRecognition.voiceDetection?.isVoicePossiblyEnding&&(e="rgba(0, 128, 255, 0.5)"),this.ai?.isProcessing&&(e="rgba(255, 255, 0, 0.5)"),this.ai?.audio?.speechOutput.isSpeaking&&(e="rgba(0, 255, 0, 0.5)");let t=this.ai?.audio?.speechRecognition.volumeLevel||0,n=30,o=6,s=Math.round(t*(n-o)+o),a=document.createElement("div");a.posX=50,a.style.cssText=`position: absolute; top: calc(50% - ${s}px/2); left: 0px; width: 6px; height: ${s}px; background-color: ${e}; border-radius: 3px; pointer-events: none; `,this.root?.appendChild(a),this.voiceAnimationPieces.push(a)}for(let e=0;e<this.voiceAnimationPieces.length;e++){let t=this.voiceAnimationPieces[e];t.posX+=2,t.style.transform=`translate(${t.posX}px, 0px)`,!(t.posX<400)&&(this.voiceAnimationPieces.splice(e--,1),t.remove())}}}onSpeechEvent(e){this.attr.loading||e.detail.isFinal&&this.dispatchEvent(new CustomEvent("input-message",{detail:e.detail.transcript}))}onCancelSpeechButtonClick(e){this.ai.audio?.speechOutput.interrupt(),this.onUpdate()}};
|
|
213
|
+
`;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",e=>this.onInputKeyPress(e),{capture:!0}),this.child("input-field").addEventListener("keydown",e=>e.stopPropagation(),{capture:!0}),this.child("llm-button").addEventListener("click",e=>this.onLLMButtonClick(e)),this.child("send-button").addEventListener("click",e=>this.onSendButtonClick(e)),this.child("microphone-button").addEventListener("click",e=>this.onMicButtonClick(e)),this.child("cancel-speech-button").addEventListener("click",e=>this.onCancelSpeechButtonClick(e))}connectAI(e){this.ai=e,this.ai.audio?.speechRecognition.addEventListener("speech",t=>this.onSpeechEvent(t)),this.ai.audio?.speechRecognition.addEventListener("start",t=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",t=>this.onUpdate()),this.onUpdate()}onUpdate(){this.attr.textColor&&document.documentElement.style.setProperty("--intelliweave-text-color",this.attr.textColor),this.child("input-field").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("llm-button").style.display=this.attr.loading||!this.attr.llmButtonVisible||this.state.micActiv?"none":"",this.child("llm-button").innerText=this.attr.llmName||"LLM",this.child("send-button").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("loader").style.display=this.attr.loading?"block":"",this.child("microphone-button").style.display=!this.ai?.audio?.speechRecognition?.isSupported||this.attr.loading&&!this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("cancel-speech-button").style.display="none",this.ai?.audio?.speechRecognition.isRunning&&this.ai?.audio?.speechOutput.isSpeaking&&(this.child("microphone-button").style.display="none",this.child("cancel-speech-button").style.display=""),!this.attr.loading&&this._wasLoading&&this.child("input-field").focus(),this._wasLoading=this.attr.loading,this.child("microphone-button-bg").classList.toggle("active",!!this.ai?.audio?.speechRecognition.isRunning);let e=this.ai?.audio?.speechRecognition.isRunning&&!this.attr.loading;e&&!this.micStateAnimationTimer?this.micStateAnimationTimer=setInterval(()=>this.onMicAnimation(),1e3/60):!e&&this.micStateAnimationTimer&&(this.voiceAnimationPieces.forEach(t=>t.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(e){if(e.stopPropagation(),e.key!="Enter")return;let t=this.child("input-field"),n=t.value?.trim();t.value="",n&&this.dispatchEvent(new CustomEvent("input-message",{detail:n}))}onLLMButtonClick(e){e.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onSendButtonClick(e){e.preventDefault();let t=this.child("input-field"),n=t.value?.trim();t.value="",n&&this.dispatchEvent(new CustomEvent("input-message",{detail:n}))}onMicButtonClick(e){e.preventDefault(),this.ai.audio?.speechRecognition.isRunning?this.ai.audio?.speechRecognition.stop():this.ai.audio?.speechRecognition.start()}onMicAnimation(){if(!this.attr.loading){if(this._micAnimFrameCounter++,this._micAnimFrameCounter%5==0){let e="rgba(140, 170, 200, 0.5)";this.ai?.audio?.speechRecognition.voiceDetection?.isModelLoaded||(e="rgba(255, 0, 0, 0.5)"),this.ai?.audio?.speechRecognition.voiceDetection?.isTranscribing&&(e="rgba(96, 66, 245, 0.9)"),this.ai?.audio?.speechRecognition.wordsCurrentlyBeingSpoken&&(e="rgba(0, 128, 255, 0.9)"),this.ai?.audio?.speechRecognition.voiceDetection?.isVoicePossiblyEnding&&(e="rgba(0, 128, 255, 0.5)"),this.ai?.isProcessing&&(e="rgba(255, 255, 0, 0.5)"),this.ai?.audio?.speechOutput.isSpeaking&&(e="rgba(0, 255, 0, 0.5)");let t=this.ai?.audio?.speechRecognition.volumeLevel||0,n=30,o=6,s=Math.round(t*(n-o)+o),a=document.createElement("div");a.posX=50,a.style.cssText=`position: absolute; top: calc(50% - ${s}px/2); left: 0px; width: 6px; height: ${s}px; background-color: ${e}; border-radius: 3px; pointer-events: none; `,this.root?.appendChild(a),this.voiceAnimationPieces.push(a)}for(let e=0;e<this.voiceAnimationPieces.length;e++){let t=this.voiceAnimationPieces[e];t.posX+=2,t.style.transform=`translate(${t.posX}px, 0px)`,!(t.posX<400)&&(this.voiceAnimationPieces.splice(e--,1),t.remove())}}}onSpeechEvent(e){this.attr.loading||e.detail.isFinal&&this.dispatchEvent(new CustomEvent("input-message",{detail:e.detail.transcript}))}onCancelSpeechButtonClick(e){this.ai.audio?.speechOutput.interrupt(),this.onUpdate()}};U.observedAttributes=["loading","llmName","llmButtonVisible","textColor","layout"];var Ue='data:image/svg+xml,<svg id="eLjt8NmVnoY1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 300 300" shape-rendering="geometricPrecision" text-rendering="geometricPrecision" project-id="defaf4a7213e40159eb368f9622a2af1" export-id="e0405e7e1d4a45c0a08fbbedb06a02a8" cached="false"><defs><radialGradient id="eLjt8NmVnoY6-fill" cx="0" cy="0" r="1" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-58.520001 292.985 -172.197 -34.394001 203.907 57.158)"><stop id="eLjt8NmVnoY6-fill-0" offset="0%" stop-color="%232b3d43"/><stop id="eLjt8NmVnoY6-fill-1" offset="33%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-2" offset="58%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-3" offset="100%" stop-color="%237ebf96"/></radialGradient><radialGradient id="eLjt8NmVnoY7-fill" cx="0" cy="0" r="1.112049" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(182.129 -94.016999 94.016999 182.129 43.4553 184.626)"><stop id="eLjt8NmVnoY7-fill-0" offset="0%" stop-color="%233f2d2d"/><stop id="eLjt8NmVnoY7-fill-1" offset="28%" stop-color="%23c83b35"/><stop id="eLjt8NmVnoY7-fill-2" offset="81%" stop-color="%23f69153"/><stop id="eLjt8NmVnoY7-fill-3" offset="100%" stop-color="%23ffe388"/></radialGradient><radialGradient id="eLjt8NmVnoY9-fill" cx="0" cy="0" r="593.59" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-0.196117 0.98058 -0.578542 -0.115709 406.499077 117.274778)"><stop id="eLjt8NmVnoY9-fill-0" offset="0%" stop-color="%23252d3a"/><stop id="eLjt8NmVnoY9-fill-1" offset="60%" stop-color="%23c50"/><stop id="eLjt8NmVnoY9-fill-2" offset="100%" stop-color="%23fddc85"/></radialGradient><radialGradient id="eLjt8NmVnoY10-fill" cx="0" cy="0" r="454.77" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="translate(87.33 340.7)"><stop id="eLjt8NmVnoY10-fill-0" offset="0%" stop-color="%23002936"/><stop id="eLjt8NmVnoY10-fill-1" offset="44%" stop-color="%23007aa1"/><stop id="eLjt8NmVnoY10-fill-2" offset="67%" stop-color="%2326ab7f"/><stop id="eLjt8NmVnoY10-fill-3" offset="100%" stop-color="%2395e0c8"/></radialGradient></defs><g transform="matrix(.339855 0 0 0.339855 65.056641 64.89012)"><path d="M337.93,111.85c17.31-4.12,30.6-2.15,38.55,5.96c12.9,13.16,10.13,41.58-7.64,77.95-34.66,70.98-116.01,153.37-181.35,183.6-4.15,1.92-8.16,3.6-12.02,5.03l.05.18C83.95,418.36,13.7,365.53,1.49,278.27C15.34,403.24,121.28,500.43,249.94,500.43c138.07,0,250-111.93,250-250c0-9.8-.58-19.46-1.68-28.96-12-82.27-75.81-133.5-160.33-109.62Z" fill="url(%23eLjt8NmVnoY9-fill)"/><path d="M249.94,0.43c-138.07,0-250,111.93-250,250c0,9.41.54,18.69,1.55,27.84C13.7,365.54,83.95,418.36,175.52,384.58l-.05-.18c-11.22,4.17-21.17,6.24-29.61,6.24-9.59,0-17.18-2.67-22.44-8.03-12.9-13.19-10.13-41.61,7.64-77.98c18.26-37.41,49.51-77.98,84.51-112.41c31.45-32.33,62.2-54.66,91.14-68.47.16-.08.34-.16.49-.23c1.74-.85,3.47-1.68,5.18-2.49c9.22-4.27,17.77-7.33,25.54-9.17c84.52-23.88,148.33,27.35,160.33,109.62C483.91,97.04,378.22,0.43,249.94,0.43Z" fill="url(%23eLjt8NmVnoY10-fill)"/><path d="M337.93,111.85c-7.77,1.84-16.32,4.9-25.54,9.17-1.71.8-3.45,1.63-5.18,2.49-.16.08-.34.16-.49.23-28.94,13.81-59.69,36.14-91.14,68.47-35,34.43-66.24,75-84.51,112.41-17.77,36.37-20.54,64.79-7.64,77.98c5.26,5.36,12.85,8.03,22.44,8.03c8.45,0,18.39-2.07,29.61-6.24c3.86-1.42,7.88-3.11,12.02-5.03c65.34-30.23,146.68-112.62,181.35-183.6c17.77-36.37,20.54-64.79,7.64-77.95-7.95-8.11-21.24-10.08-38.55-5.96h-.01Z" fill="%23252d3a"/></g></svg>%0D%0A';var F=class extends x{constructor(){super(...arguments);this.html=()=>`
|
|
214
214
|
|
|
215
215
|
<!-- Styling -->
|
|
216
216
|
<style>
|
|
@@ -263,7 +263,7 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
263
263
|
<!-- Logo -->
|
|
264
264
|
<img id='root' />
|
|
265
265
|
|
|
266
|
-
`;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let t=this.attr.logo||
|
|
266
|
+
`;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let t=this.attr.logo||Ue;this._lastLogoSrc!=t&&(this._lastLogoSrc=t,e.src=t);let n=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(n){let o=window.visualViewport?.offsetTop||0,s=window.visualViewport?.offsetLeft||0,a=n.getBoundingClientRect();if(!a)return;e.classList.add("focused-mode"),e.style.width="128px",e.style.height="128px",e.style.left=Math.round(a.x+a.width/2-128/2+s)+"px",e.style.top=Math.round(a.y+a.height/2-128/2+o)+"px"}else e.classList.remove("focused-mode"),e.style.width="",e.style.height="",e.style.left="",e.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};F.observedAttributes=["logo","focusID"];import qe from"rehype-external-links";import et from"rehype-format";import tt from"rehype-stringify";import it from"remark-parse";import nt from"remark-rehype";import{unified as ot}from"unified";var H=class extends x{constructor(){super(...arguments);this.html=()=>`
|
|
267
267
|
|
|
268
268
|
<!-- Styling -->
|
|
269
269
|
<style>
|
|
@@ -756,7 +756,7 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
756
756
|
${H.add({id:"llm-selector-panel"})}
|
|
757
757
|
|
|
758
758
|
<!-- Interaction panel -->
|
|
759
|
-
${
|
|
759
|
+
${U.add({id:"interaction-bar"})}
|
|
760
760
|
|
|
761
761
|
|
|
762
762
|
<!-- Powered by IW banner -->
|
|
@@ -37,7 +37,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
|
37
37
|
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Wb.DEFAULT_TIMEOUT,this.logger=a.logger??console;let c="warn";this.logLevel=c,this.logLevel=wb(a.logLevel,"ClientOptions.logLevel",this)??wb(Zo("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??CE(),se(this,oh,RE,"f"),this._options=a,this.apiKey=typeof r=="string"?r:"Missing Key",this.organization=n,this.project=i,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){}async authHeaders(e){return U([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return bb(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Ro}`}defaultIdempotencyKey(){return`stainless-node-retry-${lb()}`}makeStatusError(e,r,n,i){return Bt.generate(e,r,n,i)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof X?n:new X(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new X(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let i=!I(this,Bb,"m",$1).call(this)&&n||this.baseURL,o=kE(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return $E(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new Us(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,o=i.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(i);let{req:s,url:a,timeout:c}=await this.buildRequest(i,{retryCount:o-r});await this.prepareRequest(s,{url:a,options:i});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Ot(this).debug(`[${l}] sending request`,qi({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:s.headers})),i.signal?.aborted)throw new qt;let f=new AbortController,p=await this.fetchWithTimeout(a,s,c,f).catch(ed),h=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new qt;let b=Qu(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Ot(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${y}`),Ot(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${y})`,qi({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),this.retryRequest(i,r,n??l);throw Ot(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),Ot(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,qi({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),b?new Oo:new Co({cause:p})}let m=[...p.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,b])=>", "+y+": "+JSON.stringify(b)).join(""),g=`[${l}${u}${m}] ${s.method} ${a} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${h-d}ms`;if(!p.ok){let y=await this.shouldRetry(p);if(r&&y){let F=`retrying, ${r} attempts remaining`;return await OE(p.body),Ot(this).info(`${g} - ${F}`),Ot(this).debug(`[${l}] response error (${F})`,qi({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),this.retryRequest(i,r,n??l,p.headers)}let b=y?"error; no more retries left":"error; not retryable";Ot(this).info(`${g} - ${b}`);let $=await p.text().catch(F=>ed(F).message),R=EE($),T=R?void 0:$;throw Ot(this).debug(`[${l}] response error (${b})`,qi({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:T,durationMs:Date.now()-d})),this.makeStatusError(p.status,R,T,p.headers)}return Ot(this).info(g),Ot(this).debug(`[${l}] response start`,qi({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),{response:p,options:i,controller:f,requestLogID:l,retryOfRequestLogID:n,startTime:d}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new sd(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:o,method:s,...a}=r||{},c=this._makeAbort(i);o&&o.addEventListener("abort",c,{once:!0});let l=setTimeout(c,n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...a};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let o,s=i?.get("retry-after-ms");if(s){let c=parseFloat(s);Number.isNaN(c)||(o=c)}let a=i?.get("retry-after");if(a&&!o){let c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(!(o&&0<=o&&o<60*1e3)){let c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,c)}return await gi(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:o,query:s,defaultBaseURL:a}=n,c=this.buildURL(o,s,a);"timeout"in n&&IE("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:l,retryCount:r});return{req:{method:i,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let s=U([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...NE(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=U([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:zm(e)}:I(this,oh,"f").call(this,{body:e,headers:n})}};Wb=be,oh=new WeakMap,Bb=new WeakSet,$1=function(){return this.baseURL!=="https://api.openai.com/v1"};be.OpenAI=Wb;be.DEFAULT_TIMEOUT=6e5;be.OpenAIError=X;be.APIError=Bt;be.APIConnectionError=Co;be.APIConnectionTimeoutError=Oo;be.APIUserAbortError=qt;be.NotFoundError=gc;be.ConflictError=yc;be.RateLimitError=bc;be.BadRequestError=fc;be.AuthenticationError=mc;be.InternalServerError=vc;be.PermissionDeniedError=hc;be.UnprocessableEntityError=_c;be.InvalidWebhookSignatureError=hi;be.toFile=Um;be.Completions=Xs;be.Chat=Do;be.Embeddings=Js;be.Files=Qs;be.Images=na;be.Audio=vi;be.Moderations=oa;be.Models=ia;be.FineTuning=Xn;be.Graders=Wo;be.VectorStores=eo;be.Webhooks=ca;be.Beta=Hn;be.Batches=qs;be.Uploads=Ho;be.Responses=Yi;be.Realtime=Ji;be.Conversations=qo;be.Evals=Bo;be.Containers=Vo;be.Skills=Qi;be.Videos=aa;var or=[];for(let t=0;t<256;++t)or.push((t+256).toString(16).slice(1));function S1(t,e=0){return(or[t[e+0]]+or[t[e+1]]+or[t[e+2]]+or[t[e+3]]+"-"+or[t[e+4]]+or[t[e+5]]+"-"+or[t[e+6]]+or[t[e+7]]+"-"+or[t[e+8]]+or[t[e+9]]+"-"+or[t[e+10]]+or[t[e+11]]+or[t[e+12]]+or[t[e+13]]+or[t[e+14]]+or[t[e+15]]).toLowerCase()}var Gb,U2=new Uint8Array(16);function Hb(){if(!Gb){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Gb=crypto.getRandomValues.bind(crypto)}return Gb(U2)}var Z2=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Xb={randomUUID:Z2};function F2(t,e,r){t=t||{};let n=t.random??t.rng?.()??Hb();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[r+i]=n[i];return e}return S1(n)}function V2(t,e,r){return Xb.randomUUID&&!e&&!t?Xb.randomUUID():F2(t,e,r)}var sr=V2;var Xo=class{constructor(){this.size=4096;this.groups=[]}createGroup(e){let r=new Kb;return r.id=e,this.groups.push(r),r}group(e){return this.groups.find(r=>r.id===e)}static countTokensInText(e){return e==null?e="":typeof e=="number"?e=e+"":typeof e!="string"&&(e=JSON.stringify(e)),Math.ceil(e.length/3)}countTokens(){return this.groups.reduce((e,r)=>e+r.tokenCount,0)}removeOverflow(){let e=this.countTokens(),r=this.groups.reduce((n,i)=>n+i.weight,0);for(;e>this.size;){let n=this.groups.slice().sort((o,s)=>{let a=Math.floor(o.weight/r*this.size),c=Math.floor(s.weight/r*this.size),l=o.tokenCount-a;return s.tokenCount-c-l}),i=this.removeOneItem(n);if(!i)throw new Error("Too many items in the token window that cannot be removed.");e-=i.tokenCount}}removeOneItem(e){for(let r of e){let n=r.items.findIndex(o=>!o.cannotRemove);if(n===-1)continue;let i=r.items[n];return r.items.splice(n,1),r.tokenCount-=i.tokenCount,i}return null}},Kb=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
38
38
|
`;this.itemPadding=0;this.sortFunction=(e,r)=>e.sortOrder!==r.sortOrder?e.sortOrder-r.sortOrder:e.dateAdded!==r.dateAdded?e.dateAdded-r.dateAdded:0}setItemPadding(e){return this.itemPadding=e,this.recalculateTokens(),this}sortBy(e){return this.sortFunction=e,this.items.sort(this.sortFunction),this}setSeparator(e){return this.separator==e?this:(this.separator=e,this.recalculateTokens(),this)}setWeight(e){return this.weight=e,this}recalculateTokens(){this.tokenCount=this.items.reduce((e,r)=>(r.tokenCount=Xo.countTokensInText(typeof r.data=="string"?r.data:JSON.stringify(r.data))+Xo.countTokensInText(this.separator)+this.itemPadding,e+r.tokenCount),0)}add(e){typeof e=="string"&&(e={source:"user",data:e});let r=e;r.id===void 0&&(r.id=sr()),!r.sections?.length&&typeof r.data=="string"?r.text=r.data:r.text=r.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(`
|
|
39
39
|
|
|
40
|
-
`)||"";let n=this.items.find(i=>i.id===r.id);return n?(this.tokenCount-=n.tokenCount,Object.assign(n,r),r=n):this.items.push(r),r.dateAdded===void 0&&(r.dateAdded=Date.now()),r.sortOrder===void 0&&(r.sortOrder=0),r.disabled===void 0&&(r.disabled=!1),r.source===void 0&&(r.source="user"),r.sections===void 0&&(r.sections=[]),r.tokenCount=r.disabled?0:Xo.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+Xo.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=r.tokenCount,this.items.sort(this.sortFunction),r}getAllAsString(){return this.getAll().map(e=>e.text).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}};function sh(t){let e=(t||"").split(`
|
|
40
|
+
`)||"";let n=this.items.find(i=>i.id===r.id);return n?(this.tokenCount-=n.tokenCount,Object.assign(n,r),r=n):this.items.push(r),r.dateAdded===void 0&&(r.dateAdded=Date.now()),r.sortOrder===void 0&&(r.sortOrder=0),r.disabled===void 0&&(r.disabled=!1),r.source===void 0&&(r.source="user"),r.sections===void 0&&(r.sections=[]),r.tokenCount=r.disabled?0:Xo.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+Xo.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=r.tokenCount,this.items.sort(this.sortFunction),r}remove(e){let r=this.items.findIndex(n=>n.id===e);return r===-1?!1:(this.tokenCount-=this.items[r].tokenCount||0,this.items.splice(r,1),!0)}getAllAsString(){return this.getAll().map(e=>e.text).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}};function sh(t){let e=(t||"").split(`
|
|
41
41
|
`);for(;e.length>0&&e[0].trim()=="";)e.shift();for(;e.length>0&&e[e.length-1].trim()=="";)e.pop();let r=1/0;for(let n of e){let i=n.match(/^\s*/)?.[0].length||0;r=Math.min(r,i)}return r>0&&r<1/0&&(e=e.map(n=>n.substring(r))),e.join(`
|
|
42
42
|
`)}var q2={};function Ko(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:q2}function ht(){return Ko().intelliweave=Ko().intelliweave||Ko().webWeaver||{},Ko().intelliweave}function I1(){if(ht().userID)return ht().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let t=localStorage.getItem("intelliweave.uid")||"";return t||(t=sr(),localStorage.setItem("intelliweave.uid",t),t)}else return sr()}function E1(t){let e=t;if(e?.type=="object"&&e.properties)return t;let r={type:"object",properties:{},required:[]};if(t&&Array.isArray(t)){let n=t;for(let i of n)r.properties[i.name]={type:i.type||"string",description:i.description||""}}return r}var ah=class ah{constructor(e){this.module="IntelliWeave";this.module=e}get debugEnabled(){return ah.debug?!0:typeof window<"u"&&ht().debug}log(...e){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...e)}debug(...e){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...e)}info(...e){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...e)}warn(...e){console.warn(`[IntelliWeave > ${this.module}]`,...e)}error(...e){console.error(`[IntelliWeave > ${this.module}]`,...e)}timer(e,...r){let n=Date.now();return this.debug(`[${e} 0ms] Started`,...r),(...i)=>this.debug(`[${e} ${Math.floor(Date.now()-n)}ms]`,...i)}};ah.debug=!1;var Ce=ah;var P1=new Ce("ChatBase"),ol=class{constructor(e){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let e=new Xo;return e.createGroup("context").setSeparator(`
|
|
43
43
|
|
|
@@ -110,7 +110,7 @@ ${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"ope
|
|
|
110
110
|
`;break;case"id":a=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?n(parseInt(g,10)):r(new n_(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:y}));break;default:r(new n_(`Unknown field "${m.length>20?`${m.slice(0,20)}\u2026`:m}"`,{type:"unknown-field",field:m,value:g,line:y}));break}}function p(){c.length>0&&e({id:a,event:l||void 0,data:c.endsWith(`
|
|
111
111
|
`)?c.slice(0,-1):c}),a=void 0,c="",l=""}function h(m={}){o&&m.consume&&d(o),s=!0,a=void 0,c="",l="",o=""}return{feed:u,reset:h}}function $J(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
|
|
112
112
|
`,n),s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?s=i:o!==-1&&(s=o),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
|
|
113
|
-
`&&n++}}return[e,r]}var i_=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=NM({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var SJ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Is=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},o_=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=bM(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??SJ}async _authThenStart(){if(!this._authProvider)throw new Eo("No auth provider");let e;try{e=await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Eo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=r_(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let i=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Is(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},i)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,c=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new i_({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:h}=await u.read();if(h)break;if(p.id&&(s=p.id,a=!0,i?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let m=Pg.parse(JSON.parse(p.data));Sa(m)&&(c=!0,o!==void 0&&(m.id=o)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Eo("No auth provider");if(await qf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Eo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:i}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:_p(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,s),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Is(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:p,scope:h}=nI(a);if(this._resourceMetadataUrl=p,this._scope=h,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Eo;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:p,scope:h,error:m}=nI(a);if(m==="insufficient_scope"){let g=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===g)throw new Is(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=g??void 0,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Eo;return this.send(e)}}throw new Is(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),iz(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let u=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:i},!1);else if(d?.includes("application/json")){let f=await a.json(),p=Array.isArray(f)?f.map(h=>Pg.parse(h)):[Pg.parse(f)];for(let h of p)this.onmessage?.(h)}else throw await a.body?.cancel(),new Is(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Is(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Es={name:"@intelliweave/embedded",version:"2.0.72-beta.12",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.95","@types/lodash":"^4.17.23","@types/react":"^18.3.12",bestzip:"^2.2.1","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.17",vitest:"^4.0.18"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.74.0","@modelcontextprotocol/sdk":"^1.26.0","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.22.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};var er=new Ce("MCPKnowledgeClient"),EJ="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",s_=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}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(){er.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=r.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",r=new URL(this.config.proxy.url||EJ));let i=new t_({name:Es.name,version:Es.version}),o=new o_(r,{requestInit:{headers:n}});return await i.connect(o),er.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=e,e.onerror=r=>{er.error(`MCP client error: ${r.message}`)},e.onclose=()=>{er.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(b0,r=>{r.params.level=="critical"?er.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?er.error(`[Server] ${r.params.data}`):r.params.level=="error"?er.error(`[Server] ${r.params.data}`):r.params.level=="warning"?er.warn(`[Server] ${r.params.data}`):r.params.level=="info"?er.info(`[Server] ${r.params.data}`):r.params.level=="debug"?er.debug(`[Server] ${r.params.data}`):er.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Sp,r=>{er.debug("Tool list changed",r),this.fetchTools()}),er.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let i=await this.client.listTools({cursor:r});r=i.nextCursor;for(let o of i.tools||[])e.push(o);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let o=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:s=>this.performToolCall(i.name,s),disabled:o})}er.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,er.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return er.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.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 r.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 r}async performToolCall(e,r){await this.connect(),er.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw er.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var PJ=new Ce("Statistics"),Bf=[];async function Dr(t,e){let r={...e,event_id:sr(),event_date:new Date().toISOString(),sdk_version:Es.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Bf.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Bf.length===0))return;let n=Bf.slice();Bf.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){PJ.warn("Failed to submit analytics event:",i),Bf.push(...n);return}}var Ya=new Ce("KnowledgeBase"),sI=1,a_=class t{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>AP(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${sI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&ht().knowledgeBaseSources&&(e=e.concat(ht().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Ya.debug(`Searching knowledge base for: ${e}`);let r=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async l=>{try{let u=Date.now(),d=await l.query(e);return Ya.debug(`Source '${l.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Ya.warn(`Knowledge source '${l.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&ht().knowledgeBase&&(o=o.concat(ht().knowledgeBase)),o=o.filter(l=>l&&!l.disabled);for(let l=0;l<o.length;l++){let u=o[l];u.id=u.id||`temp.${l}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new Gd({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let c=s.search(e).map(l=>o.find(u=>u.id==l.id));for(let l of o)l.isContext&&(c.find(u=>u.id===l.id)||c.push(l));return this.lastResults=c,Dr(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Ya.debug("Found results:",c),c}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${sI++}`),Ya.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(c,l)=>{Ya.debug(`Calling remote knowledge base action: ${c.id}`);let u={type:"action",userID:this.ai.userID,actionID:c.id,parameters:l},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let f=await d.json();return a(f.updateItems||[]),f.response},a=c=>{for(let l of c){if(!l.id){Ya.warn("KB item skipped since it has no ID.",l);continue}let u=n.find(d=>d.id==l.id);if(u){u.name=l.name||u.name||"",u.content=l.content||u.content||"",u.disabled=l.disabled??u.disabled,u.isContext=l.isContext??u.isContext,u.parameters=l.parameters||u.parameters||[],u.tags=l.tags||u.tags,u.type=l.type||u.type;continue}n.push({...l,action:d=>s(l,d)})}};this.registerSource(r,async c=>{if(o&&i.includes(c))return n;let l={type:"search",userID:this.ai?.userID||"",query:c},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(c)||i.push(c),a(d.items),n})}clone(e){let r=new t(e);return r._sources=this._sources.slice(),r._windowSources=this._windowSources.slice(),r.manualEntries=this.manualEntries.slice(),r.allowGlobalConfigSources=this.allowGlobalConfigSources,r.allowWindowSources=this.allowWindowSources,r.allowRagSearch=this.allowRagSearch,r.ensureInternalKnowledge(),r}registerMCPSource(e){e.id||(e.id=`external.${sI++}`);let r=new s_(e);return this.registerSource(e.id,n=>r.search(n)),r}};var c_=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
113
|
+
`&&n++}}return[e,r]}var i_=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=NM({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var SJ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Is=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},o_=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=bM(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??SJ}async _authThenStart(){if(!this._authProvider)throw new Eo("No auth provider");let e;try{e=await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Eo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=r_(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let i=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Is(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},i)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,c=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new i_({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:h}=await u.read();if(h)break;if(p.id&&(s=p.id,a=!0,i?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let m=Pg.parse(JSON.parse(p.data));Sa(m)&&(c=!0,o!==void 0&&(m.id=o)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Eo("No auth provider");if(await qf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Eo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:i}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:_p(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,s),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Is(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:p,scope:h}=nI(a);if(this._resourceMetadataUrl=p,this._scope=h,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Eo;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:p,scope:h,error:m}=nI(a);if(m==="insufficient_scope"){let g=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===g)throw new Is(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=g??void 0,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Eo;return this.send(e)}}throw new Is(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),iz(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let u=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:i},!1);else if(d?.includes("application/json")){let f=await a.json(),p=Array.isArray(f)?f.map(h=>Pg.parse(h)):[Pg.parse(f)];for(let h of p)this.onmessage?.(h)}else throw await a.body?.cancel(),new Is(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Is(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Es={name:"@intelliweave/embedded",version:"2.0.72-beta.13",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.95","@types/lodash":"^4.17.23","@types/react":"^18.3.12",bestzip:"^2.2.1","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.17",vitest:"^4.0.18"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.74.0","@modelcontextprotocol/sdk":"^1.26.0","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.22.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};var er=new Ce("MCPKnowledgeClient"),EJ="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",s_=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}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(){er.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=r.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",r=new URL(this.config.proxy.url||EJ));let i=new t_({name:Es.name,version:Es.version}),o=new o_(r,{requestInit:{headers:n}});return await i.connect(o),er.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=e,e.onerror=r=>{er.error(`MCP client error: ${r.message}`)},e.onclose=()=>{er.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(b0,r=>{r.params.level=="critical"?er.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?er.error(`[Server] ${r.params.data}`):r.params.level=="error"?er.error(`[Server] ${r.params.data}`):r.params.level=="warning"?er.warn(`[Server] ${r.params.data}`):r.params.level=="info"?er.info(`[Server] ${r.params.data}`):r.params.level=="debug"?er.debug(`[Server] ${r.params.data}`):er.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Sp,r=>{er.debug("Tool list changed",r),this.fetchTools()}),er.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let i=await this.client.listTools({cursor:r});r=i.nextCursor;for(let o of i.tools||[])e.push(o);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let o=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:s=>this.performToolCall(i.name,s),disabled:o})}er.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,er.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return er.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.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 r.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 r}async performToolCall(e,r){await this.connect(),er.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw er.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var PJ=new Ce("Statistics"),Bf=[];async function Dr(t,e){let r={...e,event_id:sr(),event_date:new Date().toISOString(),sdk_version:Es.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Bf.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Bf.length===0))return;let n=Bf.slice();Bf.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){PJ.warn("Failed to submit analytics event:",i),Bf.push(...n);return}}var Ya=new Ce("KnowledgeBase"),sI=1,a_=class t{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>AP(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${sI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&ht().knowledgeBaseSources&&(e=e.concat(ht().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Ya.debug(`Searching knowledge base for: ${e}`);let r=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async l=>{try{let u=Date.now(),d=await l.query(e);return Ya.debug(`Source '${l.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Ya.warn(`Knowledge source '${l.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&ht().knowledgeBase&&(o=o.concat(ht().knowledgeBase)),o=o.filter(l=>l&&!l.disabled);for(let l=0;l<o.length;l++){let u=o[l];u.id=u.id||`temp.${l}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new Gd({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let c=s.search(e).map(l=>o.find(u=>u.id==l.id));for(let l of o)l.isContext&&(c.find(u=>u.id===l.id)||c.push(l));return this.lastResults=c,Dr(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Ya.debug("Found results:",c),c}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${sI++}`),Ya.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(c,l)=>{Ya.debug(`Calling remote knowledge base action: ${c.id}`);let u={type:"action",userID:this.ai.userID,actionID:c.id,parameters:l},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let f=await d.json();return a(f.updateItems||[]),f.response},a=c=>{for(let l of c){if(!l.id){Ya.warn("KB item skipped since it has no ID.",l);continue}let u=n.find(d=>d.id==l.id);if(u){u.name=l.name||u.name||"",u.content=l.content||u.content||"",u.disabled=l.disabled??u.disabled,u.isContext=l.isContext??u.isContext,u.parameters=l.parameters||u.parameters||[],u.tags=l.tags||u.tags,u.type=l.type||u.type;continue}n.push({...l,action:d=>s(l,d)})}};this.registerSource(r,async c=>{if(o&&i.includes(c))return n;let l={type:"search",userID:this.ai?.userID||"",query:c},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(c)||i.push(c),a(d.items),n})}clone(e){let r=new t(e);return r._sources=this._sources.slice(),r._windowSources=this._windowSources.slice(),r.manualEntries=this.manualEntries.slice(),r.allowGlobalConfigSources=this.allowGlobalConfigSources,r.allowWindowSources=this.allowWindowSources,r.allowRagSearch=this.allowRagSearch,r.ensureInternalKnowledge(),r}registerMCPSource(e){e.id||(e.id=`external.${sI++}`);let r=new s_(e);return this.registerSource(e.id,n=>r.search(n)),r}};var c_=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
114
114
|
|
|
115
115
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(r.toLowerCase().includes("true"))return!0;if(r.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+r)}async choose(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
116
116
|
|
|
@@ -129,7 +129,7 @@ ${e.extractions.map(i=>`- ${i.name} (${i.type}): ${i.description||"No descriptio
|
|
|
129
129
|
`,n=await this.instruct({...e,instruction:r});if(n=n.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),e.allowMultiple){let i=n.split(`
|
|
130
130
|
`).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of i)try{o.push(JSON.parse(s))}catch(a){console.error("Failed to parse line as JSON:",s,a.message)}return o}else return[JSON.parse(n.trim())]}async generateMarkdown(e){return this.instruct({...e,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(e){let r=this.ai.clone();return r.resetConversation(),r.getContextPrefix=async()=>e.instruction,e.callback&&r.addEventListener("output",n=>{e.callback(n.detail.message)}),e.allowKB||(r.knowledgeBase._sources=[]),await r.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(n=>n.text())}};var Au=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>e?.text||"")?.filter(e=>!!e)?.join(`
|
|
131
131
|
|
|
132
|
-
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,r)=>e+(r.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(r=>r.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(r=>r.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(r=>!!r)[0]||null}};var l_=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(r=>r.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,r=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(n,i)=>await this.runQuery(e,n.query)}])}remove(e){this.subagents=this.subagents.filter(r=>r.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,r){let n=e.apiKey||this.ai.apiKey,i=this.cachedSubagents[n];return i||(i=new zu,await i.load(n,e.config),this.cachedSubagents[n]=i),i=i.clone(),i.knowledgeBase.allowGlobalConfigSources=!1,i.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&i.knowledgeBase.reset(),i.knowledgeBase.allowRagSearch=!e.disableRagSearch,e.knowledge&&i.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(i),(await i.sendMessage(r)).text()}};var Ln=new Ce("Main"),CM=new Set,Qa=class Qa extends EventTarget{constructor(){super(...arguments);this.conversationID=sr();this.knowledgeBase=new a_(this);this.subAgents=new l_(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new c_(this);this.userID=I1();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:Qa.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(r,n){if(this.apiKey=r,!r)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{Ln.debug("Loading configuration...");let i=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r})});if(!i.ok)throw new Error(`Failed to load configuration: ${i.status} ${i.statusText}`);try{this.config=await i.json(),Ln.debug("Config loaded successfully:",this.config),n&&(this.config={...this.config,...n}),this.config&&Ln.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){Ln.error("Failed to parse JSON response:",o);try{let s=await i.clone().text();Ln.error("Raw response that failed parsing:",s)}catch{Ln.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){Ln.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 Ln.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(r){let n=this.models.find(o=>o.id==r);if(!n)throw new Error(`Model with ID "${r}" not found.`);let i={...n.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(i):n.config.providerID==="anthropic"?this.currentModel=new Dh(i):this.currentModel=new ch(i),this.currentModel.id=n.id,this.currentModel.metadata=n}async getContextPrefix(){let r=ht().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof r=="function"&&(r=await r()),r}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let r=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let n=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:n}),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:sh(`
|
|
132
|
+
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,r)=>e+(r.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(r=>r.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(r=>r.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(r=>!!r)[0]||null}};var l_=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(r=>r.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,r=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(n,i)=>await this.runQuery(e,n.query)}])}remove(e){this.subagents=this.subagents.filter(r=>r.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,r){let n=e.apiKey||this.ai.apiKey,i=this.cachedSubagents[n];return i||(i=new zu,await i.load(n,e.config),this.cachedSubagents[n]=i),i=i.clone(),i.knowledgeBase.allowGlobalConfigSources=!1,i.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&i.knowledgeBase.reset(),i.knowledgeBase.allowRagSearch=!e.disableRagSearch,e.knowledge&&i.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(i),(await i.sendMessage(r)).text()}};var Ln=new Ce("Main"),CM=new Set,Qa=class Qa extends EventTarget{constructor(){super(...arguments);this.conversationID=sr();this.knowledgeBase=new a_(this);this.subAgents=new l_(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new c_(this);this.userID=I1();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:Qa.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(r,n){if(this.apiKey=r,!r)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{Ln.debug("Loading configuration...");let i=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r})});if(!i.ok)throw new Error(`Failed to load configuration: ${i.status} ${i.statusText}`);try{this.config=await i.json(),Ln.debug("Config loaded successfully:",this.config),n&&(this.config={...this.config,...n}),this.config&&Ln.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){Ln.error("Failed to parse JSON response:",o);try{let s=await i.clone().text();Ln.error("Raw response that failed parsing:",s)}catch{Ln.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){Ln.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 Ln.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(r){let n=this.models.find(o=>o.id==r);if(!n)throw new Error(`Model with ID "${r}" not found.`);let i={...n.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(i):n.config.providerID==="anthropic"?this.currentModel=new Dh(i):this.currentModel=new ch(i),this.currentModel.id=n.id,this.currentModel.metadata=n}async getContextPrefix(){let r=ht().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof r=="function"&&(r=await r()),r}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let r=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let n=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:n}),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:sh(`
|
|
133
133
|
# RAG search
|
|
134
134
|
Use the \`search\` tool proactively as much as possible to find missing information or tools.
|
|
135
135
|
Use the \`search\` tool when you are unsure about specific details or actions to take.
|
|
@@ -145,7 +145,7 @@ attachments:
|
|
|
145
145
|
mimetype: "${a.mimeType||""}"
|
|
146
146
|
url: "${a.url}"
|
|
147
147
|
`);s||(o+="```\n"),this.currentModel.contextGroup.add({id:i.id,data:`## ${i.type}: ${i.name}
|
|
148
|
-
${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:sh(i.content),params:E1(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}processIncomingMessage(r,n){if(!n){let i=this.currentModel?.stats?.tokensUsed||0,o=r.reduce((s,a)=>s+(a.usage?.totalTokens||0),0);Dr(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:n,messages:r}})),this.onAIMessage?.(r,!!n)}async sendMessage(r,n){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(),CM.has(this.conversationID)||(CM.add(this.conversationID),Dr(this,{event_type:"session_start"})),Dr(this,{event_type:"message_send",value_str:"",event_properties:{message_length:r.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:r}})),this.submitAnalyticsEvent({type:"message",role:"user",message:r});let i=Date.now(),o=await this.currentModel.sendMessage(r),s=new Au(o);(this._voiceTracker||Ln.debug.bind(Ln))(`LLM response took ${Date.now()-i}ms`);let c=this.currentModel.contextGroup.getAllAsString();c+=`
|
|
148
|
+
${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:sh(i.content),params:E1(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||r.find(s=>s.id==i.id)||(this.currentModel.contextGroup.remove(i.id),i._functionID&&this.currentModel.toolGroup.remove(i._functionID));this.lastKBItems=r}processIncomingMessage(r,n){if(!n){let i=this.currentModel?.stats?.tokensUsed||0,o=r.reduce((s,a)=>s+(a.usage?.totalTokens||0),0);Dr(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:n,messages:r}})),this.onAIMessage?.(r,!!n)}async sendMessage(r,n){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(),CM.has(this.conversationID)||(CM.add(this.conversationID),Dr(this,{event_type:"session_start"})),Dr(this,{event_type:"message_send",value_str:"",event_properties:{message_length:r.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:r}})),this.submitAnalyticsEvent({type:"message",role:"user",message:r});let i=Date.now(),o=await this.currentModel.sendMessage(r),s=new Au(o);(this._voiceTracker||Ln.debug.bind(Ln))(`LLM response took ${Date.now()-i}ms`);let c=this.currentModel.contextGroup.getAllAsString();c+=`
|
|
149
149
|
|
|
150
150
|
=== TOOLS ===
|
|
151
151
|
|
package/dist/webpack/index.d.ts
CHANGED
|
@@ -65,6 +65,8 @@ declare class TokenWindowGroup<DataType> {
|
|
|
65
65
|
recalculateTokens(): void;
|
|
66
66
|
/** Add an item to the group */
|
|
67
67
|
add(item: string | TokenWindowGroupItemParams<DataType>): TokenWindowGroupItem<DataType>;
|
|
68
|
+
/** Manually remove an item */
|
|
69
|
+
remove(itemId: string): boolean;
|
|
68
70
|
/** Get all items as a string */
|
|
69
71
|
getAllAsString(): string;
|
|
70
72
|
/** Get all items. Doesn't return disabled items. */
|
|
@@ -993,6 +995,8 @@ declare class IntelliWeave extends EventTarget {
|
|
|
993
995
|
private _lastSystemMsg;
|
|
994
996
|
/** Get the system message prefix, before the KB entries are added */
|
|
995
997
|
getContextPrefix(): Promise<string>;
|
|
998
|
+
/** KB items added in the last run */
|
|
999
|
+
private lastKBItems;
|
|
996
1000
|
/** Get system message to send to the AI */
|
|
997
1001
|
onBeforeMessageProcessing(): Promise<void>;
|
|
998
1002
|
/** @private Process incoming message(s) from the AI. Can be used to respond to encoded actions in the text response. */
|