@intelliweave/embedded 2.0.72-beta.3 → 2.0.72-beta.4
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/node/node.js
CHANGED
|
@@ -18,7 +18,7 @@ New information found:
|
|
|
18
18
|
${o}
|
|
19
19
|
|
|
20
20
|
New tools available:
|
|
21
|
-
${a}`}},{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"||!d?.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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.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"||!d?.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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let n=new URL(e.path,window.location.origin).pathname;return window.location.href=n,`Changed route to: ${n}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!d?.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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let n=encodeURIComponent(e.email_address),s=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),a=`mailto:${n}?subject=${s}&body=${o}`;try{window.location.href=a}catch(u){throw new Error(`Failed to open email client: ${u instanceof Error?u.message:String(u)}`)}return`Email opened in default mail client. Recipient: ${e.email_address}, Subject: ${e.subject}`}}];import{Client as Y}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as ue}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as de}from"@modelcontextprotocol/sdk/client/sse.js";var b={name:"@intelliweave/embedded",version:"2.0.72-beta.3",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.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as pe,ToolListChangedNotificationSchema as he}from"@modelcontextprotocol/sdk/types.js";var h=new g("MCPKnowledgeClient"),W=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(){h.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new Y({name:b.name,version:b.version}),n=new ue(new URL(this.config.baseURL));return await t.connect(n),h.debug("Connected with HTTP streaming mode"),t}).catch(async t=>{let n=new Y({name:b.name,version:b.version}),s=new de(new URL(this.config.baseURL));return await n.connect(s),h.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=t=>{h.error(`MCP client error: ${t.message}`)},e.onclose=()=>{h.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(pe,t=>{t.params.level=="critical"?h.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?h.error(`[Server] ${t.params.data}`):t.params.level=="error"?h.error(`[Server] ${t.params.data}`):t.params.level=="warning"?h.warn(`[Server] ${t.params.data}`):t.params.level=="info"?h.info(`[Server] ${t.params.data}`):t.params.level=="debug"?h.debug(`[Server] ${t.params.data}`):h.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(he,t=>{h.debug("Tool list changed",t),this.fetchTools()}),h.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=[],t;for(;;){let s=await this.client.listTools({cursor:t});t=s.nextCursor;for(let o of s.tools||[])e.push(o);if(!s?.tools?.length||!t)break}let n=[];for(let s of e){let o=!!(this.config.searchToolName&&s.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:s.name,name:s.name,content:s.description||"",type:"action",isContext:!0,parameters:s.inputSchema,action:a=>this.performToolCall(s.name,a),disabled:o})}h.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 t=this.iwActions.slice(),n=await this.performSearchCall(e);return t=t.concat(n),this.lastSearchQuery=e,this.lastSearchResults=t,h.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return h.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let s;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];s=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];s=await this.performToolCall(this.config.searchToolName,{[o]:e})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let o=0;o<s.length;o++){let a=s[o];t.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof a=="string"?a:JSON.stringify(a)})}else t.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return t}async performToolCall(e,t){await this.connect(),h.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:t});if(n.isError){let s=n.content?.[0]?.text||"Unknown error";throw h.error(`Error calling tool ${e}: ${s}`),new Error(`Error calling tool ${e}: ${s}`)}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||[]}};import{v4 as me}from"uuid";var ge=new g("Statistics"),_=[];async function I(d,e){let t={...e,event_id:me(),event_date:new Date().toISOString(),sdk_version:b.version,conversation_id:d?.conversationID||"",api_key:d?.apiKey||"",user_id:d?.userID||""};if(_.push(t),!d||(await new Promise(s=>setTimeout(s,5e3)),_.length===0))return;let n=_.slice();_.length=0;try{let s=await fetch(d.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){ge.warn("Failed to submit analytics event:",s),_.push(...n);return}}var T=new g("KnowledgeBase"),G=1,O=class d{constructor(e){this._sources=[{id:"core.internal",query:async()=>X(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,t){let n=e;return typeof e=="function"&&(t=e,n=`source.${G++}`),this._sources.push({id:n,query:t}),n}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return w().knowledgeBaseSources&&(e=e.concat(w().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(t=>!t.disabled),e}async search(e){let t=Date.now();T.debug(`Searching knowledge base for: ${e}`);let n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],typeof document<"u"&&document.dispatchEvent(n),this._windowSources=n.sources;let o=(await Promise.all(this.sources.map(async l=>{try{let i=Date.now(),c=await l.query(e);return T.debug(`Source '${l.id}' took ${Date.now()-i}ms`),c||[]}catch(i){return T.warn(`Knowledge source '${l.id}' failed:`,i),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),w().knowledgeBase&&(o=o.concat(w().knowledgeBase)),o=o.filter(l=>l&&!l.disabled);for(let l=0;l<o.length;l++){let i=o[l];i.id=i.id||`temp.${l}`,i._functionID=i.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let a=new fe({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});a.addAll(o);let r=a.search(e).map(l=>o.find(i=>i.id==l.id));for(let l of o)l.isContext&&(r.find(i=>i.id===l.id)||r.push(l));return this.lastResults=r,I(this.ai,{event_type:"kb_search",value:r.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),T.debug("Found results:",r),r}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${G++}`),T.debug(`Registering remote knowledge base source: ${e}`);let n=[],s=[],o=!0,a=async(r,l)=>{T.debug(`Calling remote knowledge base action: ${r.id}`);let i={type:"action",userID:this.ai.userID,actionID:r.id,parameters:l},c=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let p=await c.json();return u(p.updateItems||[]),p.response},u=r=>{for(let l of r){if(!l.id){T.warn("KB item skipped since it has no ID.",l);continue}let i=n.find(c=>c.id==l.id);if(i){i.name=l.name||i.name||"",i.content=l.content||i.content||"",i.disabled=l.disabled??i.disabled,i.isContext=l.isContext??i.isContext,i.parameters=l.parameters||i.parameters||[],i.tags=l.tags||i.tags,i.type=l.type||i.type;continue}n.push({...l,action:c=>a(l,c)})}};this.registerSource(t,async r=>{if(o&&s.includes(r))return n;let l={type:"search",userID:this.ai?.userID||"",query:r},i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let c=await i.json();return o=!c.noCache,s.includes(r)||s.push(r),u(c.items),n})}clone(){let e=new d(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${G++}`);let t=new W(e);return this.registerSource(e.id,n=>t.search(n)),t}};var D=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(`
|
|
21
|
+
${a}`}},{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"||!d?.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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.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"||!d?.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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let n=new URL(e.path,window.location.origin).pathname;return window.location.href=n,`Changed route to: ${n}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!d?.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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let n=encodeURIComponent(e.email_address),s=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),a=`mailto:${n}?subject=${s}&body=${o}`;try{window.location.href=a}catch(u){throw new Error(`Failed to open email client: ${u instanceof Error?u.message:String(u)}`)}return`Email opened in default mail client. Recipient: ${e.email_address}, Subject: ${e.subject}`}}];import{Client as Y}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as ue}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as de}from"@modelcontextprotocol/sdk/client/sse.js";var b={name:"@intelliweave/embedded",version:"2.0.72-beta.4",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.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as pe,ToolListChangedNotificationSchema as he}from"@modelcontextprotocol/sdk/types.js";var h=new g("MCPKnowledgeClient"),W=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(){h.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new Y({name:b.name,version:b.version}),n=new ue(new URL(this.config.baseURL));return await t.connect(n),h.debug("Connected with HTTP streaming mode"),t}).catch(async t=>{let n=new Y({name:b.name,version:b.version}),s=new de(new URL(this.config.baseURL));return await n.connect(s),h.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=t=>{h.error(`MCP client error: ${t.message}`)},e.onclose=()=>{h.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(pe,t=>{t.params.level=="critical"?h.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?h.error(`[Server] ${t.params.data}`):t.params.level=="error"?h.error(`[Server] ${t.params.data}`):t.params.level=="warning"?h.warn(`[Server] ${t.params.data}`):t.params.level=="info"?h.info(`[Server] ${t.params.data}`):t.params.level=="debug"?h.debug(`[Server] ${t.params.data}`):h.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(he,t=>{h.debug("Tool list changed",t),this.fetchTools()}),h.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=[],t;for(;;){let s=await this.client.listTools({cursor:t});t=s.nextCursor;for(let o of s.tools||[])e.push(o);if(!s?.tools?.length||!t)break}let n=[];for(let s of e){let o=!!(this.config.searchToolName&&s.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:s.name,name:s.name,content:s.description||"",type:"action",isContext:!0,parameters:s.inputSchema,action:a=>this.performToolCall(s.name,a),disabled:o})}h.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 t=this.iwActions.slice(),n=await this.performSearchCall(e);return t=t.concat(n),this.lastSearchQuery=e,this.lastSearchResults=t,h.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return h.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let s;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];s=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];s=await this.performToolCall(this.config.searchToolName,{[o]:e})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let o=0;o<s.length;o++){let a=s[o];t.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof a=="string"?a:JSON.stringify(a)})}else t.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return t}async performToolCall(e,t){await this.connect(),h.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:t});if(n.isError){let s=n.content?.[0]?.text||"Unknown error";throw h.error(`Error calling tool ${e}: ${s}`),new Error(`Error calling tool ${e}: ${s}`)}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||[]}};import{v4 as me}from"uuid";var ge=new g("Statistics"),_=[];async function I(d,e){let t={...e,event_id:me(),event_date:new Date().toISOString(),sdk_version:b.version,conversation_id:d?.conversationID||"",api_key:d?.apiKey||"",user_id:d?.userID||""};if(_.push(t),!d||(await new Promise(s=>setTimeout(s,5e3)),_.length===0))return;let n=_.slice();_.length=0;try{let s=await fetch(d.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){ge.warn("Failed to submit analytics event:",s),_.push(...n);return}}var T=new g("KnowledgeBase"),G=1,O=class d{constructor(e){this._sources=[{id:"core.internal",query:async()=>X(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,t){let n=e;return typeof e=="function"&&(t=e,n=`source.${G++}`),this._sources.push({id:n,query:t}),n}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return w().knowledgeBaseSources&&(e=e.concat(w().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(t=>!t.disabled),e}async search(e){let t=Date.now();T.debug(`Searching knowledge base for: ${e}`);let n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],typeof document<"u"&&document.dispatchEvent(n),this._windowSources=n.sources;let o=(await Promise.all(this.sources.map(async l=>{try{let i=Date.now(),c=await l.query(e);return T.debug(`Source '${l.id}' took ${Date.now()-i}ms`),c||[]}catch(i){return T.warn(`Knowledge source '${l.id}' failed:`,i),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),w().knowledgeBase&&(o=o.concat(w().knowledgeBase)),o=o.filter(l=>l&&!l.disabled);for(let l=0;l<o.length;l++){let i=o[l];i.id=i.id||`temp.${l}`,i._functionID=i.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let a=new fe({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});a.addAll(o);let r=a.search(e).map(l=>o.find(i=>i.id==l.id));for(let l of o)l.isContext&&(r.find(i=>i.id===l.id)||r.push(l));return this.lastResults=r,I(this.ai,{event_type:"kb_search",value:r.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),T.debug("Found results:",r),r}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${G++}`),T.debug(`Registering remote knowledge base source: ${e}`);let n=[],s=[],o=!0,a=async(r,l)=>{T.debug(`Calling remote knowledge base action: ${r.id}`);let i={type:"action",userID:this.ai.userID,actionID:r.id,parameters:l},c=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let p=await c.json();return u(p.updateItems||[]),p.response},u=r=>{for(let l of r){if(!l.id){T.warn("KB item skipped since it has no ID.",l);continue}let i=n.find(c=>c.id==l.id);if(i){i.name=l.name||i.name||"",i.content=l.content||i.content||"",i.disabled=l.disabled??i.disabled,i.isContext=l.isContext??i.isContext,i.parameters=l.parameters||i.parameters||[],i.tags=l.tags||i.tags,i.type=l.type||i.type;continue}n.push({...l,action:c=>a(l,c)})}};this.registerSource(t,async r=>{if(o&&s.includes(r))return n;let l={type:"search",userID:this.ai?.userID||"",query:r},i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let c=await i.json();return o=!c.noCache,s.includes(r)||s.push(r),u(c.items),n})}clone(){let e=new d(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${G++}`);let t=new W(e);return this.registerSource(e.id,n=>t.search(n)),t}};var D=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(`
|
|
22
22
|
|
|
23
23
|
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,t)=>e+(t.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(t=>t.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(t=>t.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(t=>!!t)[0]||null}};import{v4 as Z}from"uuid";var R=class{constructor(e){this.ai=e}async boolean(e){let t=await this.instruct({...e,instruction:`${e.instruction}
|
|
24
24
|
|
package/dist/react/react.js
CHANGED
|
@@ -12,7 +12,7 @@ New information found:
|
|
|
12
12
|
${n}
|
|
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),o=encodeURIComponent(i.subject),n=encodeURIComponent(i.body),s=`mailto:${t}?subject=${o}&body=${n}`;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 Xe}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as dt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as ut}from"@modelcontextprotocol/sdk/client/sse.js";var x={name:"@intelliweave/embedded",version:"2.0.72-beta.3",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.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as pt,ToolListChangedNotificationSchema as ht}from"@modelcontextprotocol/sdk/types.js";var f=new h("MCPKnowledgeClient"),te=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(){f.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Xe({name:x.name,version:x.version}),t=new dt(new URL(this.config.baseURL));return await e.connect(t),f.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Xe({name:x.name,version:x.version}),o=new ut(new URL(this.config.baseURL));return await t.connect(o),f.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{f.error(`MCP client error: ${e.message}`)},i.onclose=()=>{f.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(pt,e=>{e.params.level=="critical"?f.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?f.error(`[Server] ${e.params.data}`):e.params.level=="error"?f.error(`[Server] ${e.params.data}`):e.params.level=="warning"?f.warn(`[Server] ${e.params.data}`):e.params.level=="info"?f.info(`[Server] ${e.params.data}`):e.params.level=="debug"?f.debug(`[Server] ${e.params.data}`):f.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(ht,e=>{f.debug("Tool list changed",e),this.fetchTools()}),f.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 o=await this.client.listTools({cursor:e});e=o.nextCursor;for(let n of o.tools||[])i.push(n);if(!o?.tools?.length||!e)break}let t=[];for(let o of i){let n=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:o.name,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:s=>this.performToolCall(o.name,s),disabled:n})}f.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,f.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return f.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let o;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];o=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];o=await this.performToolCall(this.config.searchToolName,{[n]:i})}else o=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(o))for(let n=0;n<o.length;n++){let s=o[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+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 o=="string"?o:JSON.stringify(o)});return e}async performToolCall(i,e){await this.connect(),f.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 o=t.content?.[0]?.text||"Unknown error";throw f.error(`Error calling tool ${i}: ${o}`),new Error(`Error calling tool ${i}: ${o}`)}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 mt}from"uuid";var gt=new h("Statistics"),O=[];async function y(r,i){let e={...i,event_id:mt(),event_date:new Date().toISOString(),sdk_version:x.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(O.push(e),!r||(await new Promise(o=>setTimeout(o,5e3)),O.length===0))return;let t=O.slice();O.length=0;try{let o=await fetch(r.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!o.ok)throw new Error(`Analytics submission failed: ${o.status} ${o.statusText}`)}catch(o){gt.warn("Failed to submit analytics event:",o),O.push(...t);return}}var L=new h("KnowledgeBase"),Te=1,ie=class r{constructor(i){this._sources=[{id:"core.internal",query:async()=>De(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${Te++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return p().knowledgeBaseSources&&(i=i.concat(p().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();L.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async d=>{try{let l=Date.now(),u=await d.query(i);return L.debug(`Source '${d.id}' took ${Date.now()-l}ms`),u||[]}catch(l){return L.warn(`Knowledge source '${d.id}' failed:`,l),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),p().knowledgeBase&&(n=n.concat(p().knowledgeBase)),n=n.filter(d=>d&&!d.disabled);for(let d=0;d<n.length;d++){let l=n[d];l.id=l.id||`temp.${d}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new ft({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(n);let c=s.search(i).map(d=>n.find(l=>l.id==d.id));for(let d of n)d.isContext&&(c.find(l=>l.id===d.id)||c.push(d));return this.lastResults=c,y(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),L.debug("Found results:",c),c}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${Te++}`),L.debug(`Registering remote knowledge base source: ${i}`);let t=[],o=[],n=!0,s=async(c,d)=>{L.debug(`Calling remote knowledge base action: ${c.id}`);let l={type:"action",userID:this.ai.userID,actionID:c.id,parameters:d},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let m=await u.json();return a(m.updateItems||[]),m.response},a=c=>{for(let d of c){if(!d.id){L.warn("KB item skipped since it has no ID.",d);continue}let l=t.find(u=>u.id==d.id);if(l){l.name=d.name||l.name||"",l.content=d.content||l.content||"",l.disabled=d.disabled??l.disabled,l.isContext=d.isContext??l.isContext,l.parameters=d.parameters||l.parameters||[],l.tags=d.tags||l.tags,l.type=d.type||l.type;continue}t.push({...d,action:u=>s(d,u)})}};this.registerSource(e,async c=>{if(n&&o.includes(c))return t;let d={type:"search",userID:this.ai?.userID||"",query:c},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let u=await l.json();return n=!u.noCache,o.includes(c)||o.push(c),a(u.items),t})}clone(){let i=new r(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${Te++}`);let e=new te(i);return this.registerSource(i.id,t=>e.search(t)),e}};var oe=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),o=encodeURIComponent(i.subject),n=encodeURIComponent(i.body),s=`mailto:${t}?subject=${o}&body=${n}`;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 Xe}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as dt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as ut}from"@modelcontextprotocol/sdk/client/sse.js";var x={name:"@intelliweave/embedded",version:"2.0.72-beta.4",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.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as pt,ToolListChangedNotificationSchema as ht}from"@modelcontextprotocol/sdk/types.js";var f=new h("MCPKnowledgeClient"),te=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(){f.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Xe({name:x.name,version:x.version}),t=new dt(new URL(this.config.baseURL));return await e.connect(t),f.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Xe({name:x.name,version:x.version}),o=new ut(new URL(this.config.baseURL));return await t.connect(o),f.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{f.error(`MCP client error: ${e.message}`)},i.onclose=()=>{f.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(pt,e=>{e.params.level=="critical"?f.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?f.error(`[Server] ${e.params.data}`):e.params.level=="error"?f.error(`[Server] ${e.params.data}`):e.params.level=="warning"?f.warn(`[Server] ${e.params.data}`):e.params.level=="info"?f.info(`[Server] ${e.params.data}`):e.params.level=="debug"?f.debug(`[Server] ${e.params.data}`):f.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(ht,e=>{f.debug("Tool list changed",e),this.fetchTools()}),f.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 o=await this.client.listTools({cursor:e});e=o.nextCursor;for(let n of o.tools||[])i.push(n);if(!o?.tools?.length||!e)break}let t=[];for(let o of i){let n=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:o.name,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:s=>this.performToolCall(o.name,s),disabled:n})}f.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,f.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return f.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let o;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];o=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];o=await this.performToolCall(this.config.searchToolName,{[n]:i})}else o=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(o))for(let n=0;n<o.length;n++){let s=o[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+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 o=="string"?o:JSON.stringify(o)});return e}async performToolCall(i,e){await this.connect(),f.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 o=t.content?.[0]?.text||"Unknown error";throw f.error(`Error calling tool ${i}: ${o}`),new Error(`Error calling tool ${i}: ${o}`)}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 mt}from"uuid";var gt=new h("Statistics"),O=[];async function y(r,i){let e={...i,event_id:mt(),event_date:new Date().toISOString(),sdk_version:x.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(O.push(e),!r||(await new Promise(o=>setTimeout(o,5e3)),O.length===0))return;let t=O.slice();O.length=0;try{let o=await fetch(r.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!o.ok)throw new Error(`Analytics submission failed: ${o.status} ${o.statusText}`)}catch(o){gt.warn("Failed to submit analytics event:",o),O.push(...t);return}}var L=new h("KnowledgeBase"),Te=1,ie=class r{constructor(i){this._sources=[{id:"core.internal",query:async()=>De(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${Te++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return p().knowledgeBaseSources&&(i=i.concat(p().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();L.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async d=>{try{let l=Date.now(),u=await d.query(i);return L.debug(`Source '${d.id}' took ${Date.now()-l}ms`),u||[]}catch(l){return L.warn(`Knowledge source '${d.id}' failed:`,l),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),p().knowledgeBase&&(n=n.concat(p().knowledgeBase)),n=n.filter(d=>d&&!d.disabled);for(let d=0;d<n.length;d++){let l=n[d];l.id=l.id||`temp.${d}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new ft({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(n);let c=s.search(i).map(d=>n.find(l=>l.id==d.id));for(let d of n)d.isContext&&(c.find(l=>l.id===d.id)||c.push(d));return this.lastResults=c,y(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),L.debug("Found results:",c),c}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${Te++}`),L.debug(`Registering remote knowledge base source: ${i}`);let t=[],o=[],n=!0,s=async(c,d)=>{L.debug(`Calling remote knowledge base action: ${c.id}`);let l={type:"action",userID:this.ai.userID,actionID:c.id,parameters:d},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let m=await u.json();return a(m.updateItems||[]),m.response},a=c=>{for(let d of c){if(!d.id){L.warn("KB item skipped since it has no ID.",d);continue}let l=t.find(u=>u.id==d.id);if(l){l.name=d.name||l.name||"",l.content=d.content||l.content||"",l.disabled=d.disabled??l.disabled,l.isContext=d.isContext??l.isContext,l.parameters=d.parameters||l.parameters||[],l.tags=d.tags||l.tags,l.type=d.type||l.type;continue}t.push({...d,action:u=>s(d,u)})}};this.registerSource(e,async c=>{if(n&&o.includes(c))return t;let d={type:"search",userID:this.ai?.userID||"",query:c},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let u=await l.json();return n=!u.noCache,o.includes(c)||o.push(c),a(u.items),t})}clone(){let i=new r(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${Te++}`);let e=new te(i);return this.registerSource(i.id,t=>e.search(t)),e}};var oe=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
|
|
|
@@ -660,7 +660,7 @@ ${n}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
660
660
|
|
|
661
661
|
</div>
|
|
662
662
|
|
|
663
|
-
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new W,N.isSupported&&(this.ai.audio=new N(this.ai))}onCreate(){p().embed&&b.warn("Only one <web-weaver-embed> element should be on the page."),p().embed=this;let e=p();b.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(b.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.layout&&!this.attr.layout&&(b.debug("[WebWeaverEmbed] Setting layout from client config:",e.layout),this.attr.layout=e.layout),e.positioningMode&&!this.attr.positioningMode&&(b.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(b.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(b.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(b.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(b.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),b.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",n=>this.onContainerClick(n)),this.child("web-weaver-logo").addEventListener("click",n=>this.onLogoClick(n)),this.child("interaction-bar").addEventListener("input-message",n=>this.processInput(n.detail)),this.child("interaction-bar").addEventListener("llm-button-click",n=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",n=>this.onLLMModelSelect(n)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:n=>(this.suggestions.push(n.text),"Suggestion button added")});let o=this.attr.apiKey||p().apiKey;if(!o)return b.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(o).then(n=>{this.config=n.config,p().introductionMessage=this.config.introductionMessage,p().analytics=this.config.analytics!==void 0?!!this.config.analytics:p().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(n=>{b.error("Failed to load AI configuration:",n),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(e,t){if(!t){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.removeProperty("--intelliweave-interaction-bg");return}let o=this.parseColorToRGB(t);if(!o){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.setProperty("--intelliweave-interaction-bg",t);return}let{r:n,g:s,b:a}=o;e.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${n}, ${s}, ${a}, 0.65)`),e.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(n*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),e.style.setProperty("--intelliweave-interaction-bg",`rgba(${n}, ${s}, ${a}, 0.9)`)}parseColorToRGB(e){if(!e)return null;let t=e.trim();if(t.startsWith("#")){let o=t.slice(1);if(o.length===3){let n=parseInt(o[0]+o[0],16),s=parseInt(o[1]+o[1],16),a=parseInt(o[2]+o[2],16);return{r:n,g:s,b:a}}if(o.length===6){let n=parseInt(o.slice(0,2),16),s=parseInt(o.slice(2,4),16),a=parseInt(o.slice(4,6),16);return{r:n,g:s,b:a}}return null}if(t.startsWith("rgb")){let o=t.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return o?{r:Math.max(0,Math.min(255,Math.round(Number(o[1])))),g:Math.max(0,Math.min(255,Math.round(Number(o[2])))),b:Math.max(0,Math.min(255,Math.round(Number(o[3]))))}:null}return null}applyConfigStylesAndAttributes(){let e=this.config,t=this.child("root");if(!t)return;let o=!1,s=this.attr.logo||e.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,o=!0;let J=this.child("web-weaver-logo");J&&J.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),c=this.root?.getElementById("fullscreen-name"),d=e.name||"";d!==this._lastPersonaName&&(this._lastPersonaName=d,c&&(c.textContent=d),o=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),o=!0);let l=this.root?.getElementById("fullscreen-header"),u=(this.attr.header||"").toLowerCase();if(l){let J=u==="hidden"||u==="none"||u==="false";l.style.display=!J&&(s||d)?"":"none"}let g=this.attr.background||e.background;g!==this._lastBackground&&(this._lastBackground=g,o=!0,g?(t.style.background=g,t.style.setProperty("--intelliweave-persona-bg",g),this.applyPersonaColorVariants(t,g)):(t.style.background="",t.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(t,void 0)));let v=this.attr.textColor||e.textColor,A=this.child("interaction-bar");v!==this._lastTextColor&&(this._lastTextColor=v,o=!0,v?(t.style.color=v,t.style.setProperty("--intelliweave-user-bubble-text",v),t.style.setProperty("--intelliweave-assistant-bubble-text",v),A&&A.setAttribute("textColor",v)):(t.style.color="",t.style.removeProperty("--intelliweave-user-bubble-text"),t.style.removeProperty("--intelliweave-assistant-bubble-text"),A&&A.removeAttribute("textColor")));let H=this.attr.displayMode||e.displayMode||"closed";H!==this._lastDisplayMode&&(this._lastDisplayMode=H,o=!0,H==="open"&&!this.attr.open&&(this.attr.open=!0));let fe=this.attr.layout||e.layout||"widget";fe!==this._lastLayout&&(this._lastLayout=fe,o=!0);let ye=this.attr.positioningMode||e.positioningMode||"fixed";ye!==this._lastPositioningMode&&(this._lastPositioningMode=ye,o=!0);let be=this.attr.positionX||e.positionX||"right";be!==this._lastPositionX&&(this._lastPositionX=be,o=!0);let we=this.attr.positionY||e.positionY||"bottom";we!==this._lastPositionY&&(this._lastPositionY=we,o=!0);let Ne=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,ve=Ne!==void 0?Ne:e.offsetX!==void 0?e.offsetX:20;ve!==this._lastOffsetX&&(this._lastOffsetX=ve,o=!0);let Le=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,xe=Le!==void 0?Le:e.offsetY!==void 0?e.offsetY:20;xe!==this._lastOffsetY&&(this._lastOffsetY=xe,o=!0),o&&b.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:t.style.background,finalTextColor:t.style.color,finalDisplayMode:H,finalLayout:fe,finalPositioningMode:ye,finalPositionX:be,finalPositionY:we,finalOffsetX:ve,finalOffsetY:xe})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),y(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let d=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;y(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:d}})}this._previousOpenState=this.attr.open;let e=this.child("root");this.attr.open?e.classList.add("open"):e.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(e.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):e.classList.remove("layout-fullscreen");let o=this._lastPositioningMode||"fixed",n=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,c=this._lastOffsetY!==void 0?this._lastOffsetY:20;o==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),o!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",n==="left"?e.style.left=a+"px":e.style.right=a+"px",s==="top"?e.style.top=c+"px":e.style.bottom=c+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((d,l)=>(l.priority||0)-(d.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){p().embed==this&&(p().embed=void 0)}onContainerClick(e){let t=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&t!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.open=!0))}onLogoClick(e){if(e.preventDefault(),e.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let t=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||t==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=p().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let o of p().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=o,n.addEventListener("click",s=>this.onSuggestionClick(s,o)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let t=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let a of Array.from(t.querySelectorAll(".suggestion-button")))a.remove();this.attr.focusID="";let o=document.createElement("div");o.className="input",o.innerText=e,t.appendChild(o);let n=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",t.appendChild(this.currentOutputElement);let s=Math.ceil(t.clientHeight-300);s<0&&(s=0),s>600&&(s=600),n&&(n.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"}),await this.ai.sendMessage(e);for(let a of this.suggestions){let c=document.createElement("div");c.className="suggestion-button",c.innerText=a,c.addEventListener("click",d=>this.onSuggestionClick(d,a)),this.currentOutputElement.appendChild(c)}}catch(o){b.error("Failed to process input:",o);let n=document.createElement("div");n.className="output",n.innerText="Sorry, there was a problem getting a response. "+o.message,t.appendChild(n);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),t.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e,t){let o=[];for(let n of e)for(let s=0;s<(n.sections?.length||0);s++){let a=n.sections[s],c=`msgelem-${n.id||""}_${s}_${a.type||"unknown"}`;if(c=c.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let d=a.text||"";d.includes(`
|
|
663
|
+
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new W,N.isSupported&&(this.ai.audio=new N(this.ai))}onCreate(){p().embed&&b.warn("Only one <web-weaver-embed> element should be on the page."),p().embed=this;let e=p();b.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(b.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.layout&&!this.attr.layout&&(b.debug("[WebWeaverEmbed] Setting layout from client config:",e.layout),this.attr.layout=e.layout),e.positioningMode&&!this.attr.positioningMode&&(b.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(b.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(b.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(b.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(b.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),b.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",n=>this.onContainerClick(n)),this.child("web-weaver-logo").addEventListener("click",n=>this.onLogoClick(n)),this.child("interaction-bar").addEventListener("input-message",n=>this.processInput(n.detail)),this.child("interaction-bar").addEventListener("llm-button-click",n=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",n=>this.onLLMModelSelect(n)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:n=>(this.suggestions.push(n.text),"Suggestion button added")});let o=this.attr.apiKey||p().apiKey;if(!o)return b.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(o).then(n=>{this.config=n.config,p().introductionMessage=this.config.introductionMessage,p().analytics=this.config.analytics!==void 0?!!this.config.analytics:p().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(n=>{b.error("Failed to load AI configuration:",n),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(e,t){if(!t){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.removeProperty("--intelliweave-interaction-bg");return}let o=this.parseColorToRGB(t);if(!o){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.setProperty("--intelliweave-interaction-bg",t);return}let{r:n,g:s,b:a}=o;e.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${n}, ${s}, ${a}, 0.65)`),e.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(n*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),e.style.setProperty("--intelliweave-interaction-bg",`rgba(${n}, ${s}, ${a}, 0.9)`)}parseColorToRGB(e){if(!e)return null;let t=e.trim();if(t.startsWith("#")){let o=t.slice(1);if(o.length===3){let n=parseInt(o[0]+o[0],16),s=parseInt(o[1]+o[1],16),a=parseInt(o[2]+o[2],16);return{r:n,g:s,b:a}}if(o.length===6){let n=parseInt(o.slice(0,2),16),s=parseInt(o.slice(2,4),16),a=parseInt(o.slice(4,6),16);return{r:n,g:s,b:a}}return null}if(t.startsWith("rgb")){let o=t.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return o?{r:Math.max(0,Math.min(255,Math.round(Number(o[1])))),g:Math.max(0,Math.min(255,Math.round(Number(o[2])))),b:Math.max(0,Math.min(255,Math.round(Number(o[3]))))}:null}return null}applyConfigStylesAndAttributes(){let e=this.config,t=this.child("root");if(!t)return;let o=!1,s=this.attr.logo||e.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,o=!0;let J=this.child("web-weaver-logo");J&&J.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),c=this.root?.getElementById("fullscreen-name"),d=e.name||"";d!==this._lastPersonaName&&(this._lastPersonaName=d,c&&(c.textContent=d),o=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),o=!0);let l=this.root?.getElementById("fullscreen-header"),u=(this.attr.header||"").toLowerCase();if(l){let J=u==="hidden"||u==="none"||u==="false";l.style.display=!J&&(s||d)?"":"none"}let g=this.attr.background||e.background;g!==this._lastBackground&&(this._lastBackground=g,o=!0,g?(t.style.background=g,t.style.setProperty("--intelliweave-persona-bg",g),this.applyPersonaColorVariants(t,g)):(t.style.background="",t.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(t,void 0)));let v=this.attr.textColor||e.textColor,A=this.child("interaction-bar");v!==this._lastTextColor&&(this._lastTextColor=v,o=!0,v?(t.style.color=v,t.style.setProperty("--intelliweave-user-bubble-text",v),t.style.setProperty("--intelliweave-assistant-bubble-text",v),A&&A.setAttribute("textColor",v)):(t.style.color="",t.style.removeProperty("--intelliweave-user-bubble-text"),t.style.removeProperty("--intelliweave-assistant-bubble-text"),A&&A.removeAttribute("textColor")));let H=this.attr.displayMode||e.displayMode||"closed";H!==this._lastDisplayMode&&(this._lastDisplayMode=H,o=!0,H==="open"&&!this.attr.open&&(this.attr.open=!0));let fe=this.attr.layout||e.layout||"widget";fe!==this._lastLayout&&(this._lastLayout=fe,o=!0);let ye=this.attr.positioningMode||e.positioningMode||"fixed";ye!==this._lastPositioningMode&&(this._lastPositioningMode=ye,o=!0);let be=this.attr.positionX||e.positionX||"right";be!==this._lastPositionX&&(this._lastPositionX=be,o=!0);let we=this.attr.positionY||e.positionY||"bottom";we!==this._lastPositionY&&(this._lastPositionY=we,o=!0);let Ne=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,ve=Ne!==void 0?Ne:e.offsetX!==void 0?e.offsetX:20;ve!==this._lastOffsetX&&(this._lastOffsetX=ve,o=!0);let Le=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,xe=Le!==void 0?Le:e.offsetY!==void 0?e.offsetY:20;xe!==this._lastOffsetY&&(this._lastOffsetY=xe,o=!0),o&&b.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:t.style.background,finalTextColor:t.style.color,finalDisplayMode:H,finalLayout:fe,finalPositioningMode:ye,finalPositionX:be,finalPositionY:we,finalOffsetX:ve,finalOffsetY:xe})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),y(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let d=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;y(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:d}})}this._previousOpenState=this.attr.open;let e=this.child("root");this.attr.open?e.classList.add("open"):e.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(e.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):e.classList.remove("layout-fullscreen");let o=this._lastPositioningMode||"fixed",n=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,c=this._lastOffsetY!==void 0?this._lastOffsetY:20;o==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),o!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",n==="left"?e.style.left=a+"px":e.style.right=a+"px",s==="top"?e.style.top=c+"px":e.style.bottom=c+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((d,l)=>(l.priority||0)-(d.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){p().embed==this&&(p().embed=void 0)}onContainerClick(e){let t=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&t!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.open=!0))}onLogoClick(e){if(e.preventDefault(),e.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let t=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||t==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=p().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let o of p().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=o,n.addEventListener("click",s=>this.onSuggestionClick(s,o)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let t=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let d of Array.from(t.querySelectorAll(".suggestion-button")))d.remove();this.attr.focusID="";let o=document.createElement("div");o.className="input",o.innerText=e,t.appendChild(o);let n=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",t.appendChild(this.currentOutputElement);let s=Math.ceil(t.clientHeight-300);s<0&&(s=0),s>600&&(s=600),n&&(n.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"});let a=await this.ai.sendMessage(e);for(let d of this.suggestions){let l=document.createElement("div");l.className="suggestion-button",l.innerText=d,l.addEventListener("click",u=>this.onSuggestionClick(u,d)),this.currentOutputElement.appendChild(l)}let c=a.text()||"";this.ai.audio?.speechRecognition?.isRunning&&this.ai.audio.speechOutput.speak(c)}catch(o){b.error("Failed to process input:",o);let n=document.createElement("div");n.className="output",n.innerText="Sorry, there was a problem getting a response. "+o.message,t.appendChild(n);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),t.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e,t){let o=[];for(let n of e)for(let s=0;s<(n.sections?.length||0);s++){let a=n.sections[s],c=`msgelem-${n.id||""}_${s}_${a.type||"unknown"}`;if(c=c.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let d=a.text||"";d.includes(`
|
|
664
664
|
`)&&(d=d.split(`
|
|
665
665
|
`)[0]),this.updateInfoElement(c,d,"thinking-icon"),o.push(c)}else if(a.type=="tool_call"){let l=new Z(e).toolResult(a.toolCallInstanceID||"");if(a.toolCallHiddenInUI!="always"){if(l?.toolErrorResponse)this.updateInfoElement(c,"**Error:** "+l.toolErrorResponse||"","tool-icon"),o.push(c);else if(!(a.toolCallHiddenInUI=="after-complete"&&l))if(a.toolKbID=="search"){let u=a.toolParameters?.query?`**Search:** ${a.toolParameters.query}`:"**Search**";this.updateInfoElement(c,u,"tool-icon"),o.push(c)}else this.updateInfoElement(c,a.toolKbName||"","tool-icon"),o.push(c)}}else if(a.type!="tool_result"){if(!a.text)continue;this.updateTextElement(c,a.text||""),o.push(c)}}for(let n of Array.from(this.currentOutputElement.children))o.includes(n.id)||n.remove()}updateTextElement(e,t){let o=this.currentOutputElement.querySelector(`#${e}`);o||(o=document.createElement("div"),o.id=e,o.className="output",this.currentOutputElement.appendChild(o));let n=$e().use(Je).use(Qe).use(Ke,{target:"_blank",rel:["noopener","noreferrer"]}).use(Fe).use(He).processSync(t||"");o.innerHTML=n.toString("utf-8")}updateInfoElement(e,t,o){let n=this.currentOutputElement.querySelector(`#${e}`);n||(n=document.createElement("div"),n.id=e,n.className="info-block",n.innerHTML=`
|
|
666
666
|
<div class='info-block-icon'></div>
|
|
@@ -92,7 +92,7 @@ ${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"ope
|
|
|
92
92
|
`;break;case"id":a=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new qy(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:g}));break;default:r(new qy(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:y,line:g}));break}}function f(){l.length>0&&e({id:a,event:c||void 0,data:l.endsWith(`
|
|
93
93
|
`)?l.slice(0,-1):l}),a=void 0,l="",c=""}function m(h={}){o&&h.consume&&d(o),s=!0,a=void 0,l="",c="",o=""}return{feed:u,reset:m}}function n8(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
|
|
94
94
|
`,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]===`
|
|
95
|
-
`&&n++}}return[e,r]}var By=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=Wy({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 i8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},As=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Gy=class{constructor(e,r){var n;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=Vy(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:i8}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i,o;let{resumptionToken:s}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);let l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new As(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_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){var n;let i=this._reconnectionOptions.maxRetries;if(r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{var u,d,p,f;try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new By({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:_}=await m.read();if(_)break;if(g.id&&(s=g.id,a=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let b=Gc.parse(JSON.parse(g.data));ka(b)&&(l=!0,o!==void 0&&(b.id=o)),(u=this.onmessage)===null||u===void 0||u.call(this,b)}catch(b){(d=this.onerror)===null||d===void 0||d.call(this,b)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(m){if((p=this.onerror)===null||p===void 0||p.call(this,new Error(`SSE stream disconnected: ${m}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(g){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}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 Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s,a,l,c;try{let{resumptionToken:u,onresumptiontoken:d}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:df(e)?e.id:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let p=await this._commonHeaders();p.set("content-type","application/json"),p.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:p,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},m=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,f),h=m.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!m.ok){let b=await m.text().catch(()=>null);if(m.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new As(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:I}=Su(m);if(this._resourceMetadataUrl=E,this._scope=I,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this._hasCompletedAuthFlow=!0,this.send(e)}if(m.status===403&&this._authProvider){let{resourceMetadataUrl:E,scope:I,error:P}=Su(m);if(P==="insufficient_scope"){let M=m.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new As(403,"Server returned 403 after trying upscoping");if(I&&(this._scope=I),E&&(this._resourceMetadataUrl=E),this._lastUpscopingHeader=M??void 0,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Br;return this.send(e)}}throw new As(m.status,`Error POSTing to endpoint: ${b}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,m.status===202){await((o=m.body)===null||o===void 0?void 0:o.cancel()),WA(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let g=(Array.isArray(e)?e:[e]).filter(b=>"method"in b&&"id"in b&&b.id!==void 0).length>0,_=m.headers.get("content-type");if(g)if(_?.includes("text/event-stream"))this._handleSseStream(m.body,{onresumptiontoken:d},!1);else if(_?.includes("application/json")){let b=await m.json(),E=Array.isArray(b)?b.map(I=>Gc.parse(I)):[Gc.parse(b)];for(let I of E)(s=this.onmessage)===null||s===void 0||s.call(this,I)}else throw await((a=m.body)===null||a===void 0?void 0:a.cancel()),new As(-1,`Unexpected content type: ${_}`);else await((l=m.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n,i;if(this._sessionId)try{let o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(await((n=a.body)===null||n===void 0?void 0:n.cancel()),!a.ok&&a.status!==405)throw new As(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Xy=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(vM(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(vM(this),r)}};function o8(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function BS(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(BS).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${BS(t.cause)}`:t.message:`${t}`}function vM(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var bM=t=>{throw TypeError(t)},eI=(t,e,r)=>e.has(t)||bM("Cannot "+r),Ze=(t,e,r)=>(eI(t,e,"read from private field"),r?r.call(t):e.get(t)),er=(t,e,r)=>e.has(t)?bM("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Et=(t,e,r,n)=>(eI(t,e,"write to private field"),e.set(t,r),r),Co=(t,e,r)=>(eI(t,e,"access private method"),r),ln,Ja,Iu,Hy,Ky,jp,Tu,Dp,zs,Eu,Au,Pu,Rp,hi,GS,HS,XS,_M,KS,JS,Mp,YS,QS,Ya=class extends EventTarget{constructor(e,r){var n,i;super(),er(this,hi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,er(this,ln),er(this,Ja),er(this,Iu),er(this,Hy),er(this,Ky),er(this,jp),er(this,Tu),er(this,Dp,null),er(this,zs),er(this,Eu),er(this,Au,null),er(this,Pu,null),er(this,Rp,null),er(this,HS,async o=>{var s;Ze(this,Eu).reset();let{body:a,redirected:l,status:c,headers:u}=o;if(c===204){Co(this,hi,Mp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Et(this,Iu,new URL(o.url)):Et(this,Iu,void 0),c!==200){Co(this,hi,Mp).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Co(this,hi,Mp).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.OPEN);let d=new Event("open");if((s=Ze(this,Rp))==null||s.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){Co(this,hi,Mp).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let p=new TextDecoder,f=a.getReader(),m=!0;do{let{done:h,value:y}=await f.read();y&&Ze(this,Eu).feed(p.decode(y,{stream:!h})),h&&(m=!1,Ze(this,Eu).reset(),Co(this,hi,YS).call(this))}while(m)}),er(this,XS,o=>{Et(this,zs,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Co(this,hi,YS).call(this,BS(o))}),er(this,KS,o=>{typeof o.id=="string"&&Et(this,Dp,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Ze(this,Iu)?Ze(this,Iu).origin:Ze(this,Ja).origin,lastEventId:o.id||""});Ze(this,Pu)&&(!o.event||o.event==="message")&&Ze(this,Pu).call(this,s),this.dispatchEvent(s)}),er(this,JS,o=>{Et(this,jp,o)}),er(this,QS,()=>{Et(this,Tu,void 0),Ze(this,ln)===this.CONNECTING&&Co(this,hi,GS).call(this)});try{if(e instanceof URL)Et(this,Ja,e);else if(typeof e=="string")Et(this,Ja,new URL(e,s8()));else throw new Error("Invalid URL")}catch{throw o8("An invalid or illegal string was specified")}Et(this,Eu,Wy({onEvent:Ze(this,KS),onRetry:Ze(this,JS)})),Et(this,ln,this.CONNECTING),Et(this,jp,3e3),Et(this,Ky,(n=r?.fetch)!=null?n:globalThis.fetch),Et(this,Hy,(i=r?.withCredentials)!=null?i:!1),Co(this,hi,GS).call(this)}get readyState(){return Ze(this,ln)}get url(){return Ze(this,Ja).href}get withCredentials(){return Ze(this,Hy)}get onerror(){return Ze(this,Au)}set onerror(e){Et(this,Au,e)}get onmessage(){return Ze(this,Pu)}set onmessage(e){Et(this,Pu,e)}get onopen(){return Ze(this,Rp)}set onopen(e){Et(this,Rp,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Ze(this,Tu)&&clearTimeout(Ze(this,Tu)),Ze(this,ln)!==this.CLOSED&&(Ze(this,zs)&&Ze(this,zs).abort(),Et(this,ln,this.CLOSED),Et(this,zs,void 0))}};ln=new WeakMap,Ja=new WeakMap,Iu=new WeakMap,Hy=new WeakMap,Ky=new WeakMap,jp=new WeakMap,Tu=new WeakMap,Dp=new WeakMap,zs=new WeakMap,Eu=new WeakMap,Au=new WeakMap,Pu=new WeakMap,Rp=new WeakMap,hi=new WeakSet,GS=function(){Et(this,ln,this.CONNECTING),Et(this,zs,new AbortController),Ze(this,Ky)(Ze(this,Ja),Co(this,hi,_M).call(this)).then(Ze(this,HS)).catch(Ze(this,XS))},HS=new WeakMap,XS=new WeakMap,_M=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ze(this,Dp)?{"Last-Event-ID":Ze(this,Dp)}:void 0},cache:"no-store",signal:(t=Ze(this,zs))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},KS=new WeakMap,JS=new WeakMap,Mp=function(t,e){var r;Ze(this,ln)!==this.CLOSED&&Et(this,ln,this.CLOSED);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n)},YS=function(t,e){var r;if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.CONNECTING);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n),Et(this,Tu,setTimeout(Ze(this,QS),Ze(this,jp)))},QS=new WeakMap,Ya.CONNECTING=0,Ya.OPEN=1,Ya.CLOSED=2;function s8(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var tI=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Jy=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Vy(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new Ya(this._url.href,{...this._eventSourceInit,fetch:async(a,l)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let u=await i(a,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:p}=Su(u);this._resourceMetadataUrl=d,this._scope=p}return u}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var l;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let c=new tI(a.code,a.message,a);s(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var l;let c=a;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){s(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}o()}),this._eventSource.onmessage=a=>{var l,c;let u=a,d;try{d=Gc.parse(JSON.parse(u.data))}catch(p){(l=this.onerror)===null||l===void 0||l.call(this,p);return}(c=this.onmessage)===null||c===void 0||c.call(this,d)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i,o;if(!this._endpoint)throw new Error("Not connected");try{let s=await this._commonHeaders();s.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!l.ok){let c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Su(l);if(this._resourceMetadataUrl=u,this._scope=d,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((i=l.body)===null||i===void 0?void 0:i.cancel())}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}};var Fi={name:"@intelliweave/embedded",version:"2.0.72-beta.3",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.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var tr=new Ve("MCPKnowledgeClient"),Yy=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(){tr.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new xp({name:Fi.name,version:Fi.version}),n=new Gy(new URL(this.config.baseURL));return await r.connect(n),tr.debug("Connected with HTTP streaming mode"),r}).catch(async r=>{let n=new xp({name:Fi.name,version:Fi.version}),i=new Jy(new URL(this.config.baseURL));return await n.connect(i),tr.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=r=>{tr.error(`MCP client error: ${r.message}`)},e.onclose=()=>{tr.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(ax,r=>{r.params.level=="critical"?tr.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?tr.error(`[Server] ${r.params.data}`):r.params.level=="error"?tr.error(`[Server] ${r.params.data}`):r.params.level=="warning"?tr.warn(`[Server] ${r.params.data}`):r.params.level=="info"?tr.info(`[Server] ${r.params.data}`):r.params.level=="debug"?tr.debug(`[Server] ${r.params.data}`):tr.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(sx,r=>{tr.debug("Tool list changed",r),this.fetchTools()}),tr.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})}tr.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,tr.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 tr.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(),tr.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 tr.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 l8=new Ve("Statistics"),Lp=[];async function Gr(t,e){let r={...e,event_id:dr(),event_date:new Date().toISOString(),sdk_version:Fi.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Lp.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Lp.length===0))return;let n=Lp.slice();Lp.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){l8.warn("Failed to submit analytics event:",i),Lp.push(...n);return}}var Qa=new Ve("KnowledgeBase"),rI=1,Qy=class t{constructor(e){this._sources=[{id:"core.internal",query:async()=>hP(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${rI++}`),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 St().knowledgeBaseSources&&(e=e.concat(St().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(r=>!r.disabled),e}async search(e){let r=Date.now();Qa.debug(`Searching knowledge base for: ${e}`);let n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],typeof document<"u"&&document.dispatchEvent(n),this._windowSources=n.sources;let o=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),d=await c.query(e);return Qa.debug(`Source '${c.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Qa.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),St().knowledgeBase&&(o=o.concat(St().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);for(let c=0;c<o.length;c++){let u=o[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new mP({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(e).map(c=>o.find(u=>u.id==c.id));for(let c of o)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Gr(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Qa.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${rI++}`),Qa.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Qa.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},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 p=await d.json();return a(p.updateItems||[]),p.response},a=l=>{for(let c of l){if(!c.id){Qa.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(){let e=new t(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${rI++}`);let r=new Yy(e);return this.registerSource(e.id,n=>r.search(n)),r}};var ev=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
95
|
+
`&&n++}}return[e,r]}var By=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=Wy({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 i8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},As=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Gy=class{constructor(e,r){var n;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=Vy(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:i8}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i,o;let{resumptionToken:s}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);let l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new As(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_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){var n;let i=this._reconnectionOptions.maxRetries;if(r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{var u,d,p,f;try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new By({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:_}=await m.read();if(_)break;if(g.id&&(s=g.id,a=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let b=Gc.parse(JSON.parse(g.data));ka(b)&&(l=!0,o!==void 0&&(b.id=o)),(u=this.onmessage)===null||u===void 0||u.call(this,b)}catch(b){(d=this.onerror)===null||d===void 0||d.call(this,b)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(m){if((p=this.onerror)===null||p===void 0||p.call(this,new Error(`SSE stream disconnected: ${m}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(g){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}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 Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s,a,l,c;try{let{resumptionToken:u,onresumptiontoken:d}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:df(e)?e.id:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let p=await this._commonHeaders();p.set("content-type","application/json"),p.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:p,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},m=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,f),h=m.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!m.ok){let b=await m.text().catch(()=>null);if(m.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new As(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:I}=Su(m);if(this._resourceMetadataUrl=E,this._scope=I,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this._hasCompletedAuthFlow=!0,this.send(e)}if(m.status===403&&this._authProvider){let{resourceMetadataUrl:E,scope:I,error:P}=Su(m);if(P==="insufficient_scope"){let M=m.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new As(403,"Server returned 403 after trying upscoping");if(I&&(this._scope=I),E&&(this._resourceMetadataUrl=E),this._lastUpscopingHeader=M??void 0,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Br;return this.send(e)}}throw new As(m.status,`Error POSTing to endpoint: ${b}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,m.status===202){await((o=m.body)===null||o===void 0?void 0:o.cancel()),WA(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let g=(Array.isArray(e)?e:[e]).filter(b=>"method"in b&&"id"in b&&b.id!==void 0).length>0,_=m.headers.get("content-type");if(g)if(_?.includes("text/event-stream"))this._handleSseStream(m.body,{onresumptiontoken:d},!1);else if(_?.includes("application/json")){let b=await m.json(),E=Array.isArray(b)?b.map(I=>Gc.parse(I)):[Gc.parse(b)];for(let I of E)(s=this.onmessage)===null||s===void 0||s.call(this,I)}else throw await((a=m.body)===null||a===void 0?void 0:a.cancel()),new As(-1,`Unexpected content type: ${_}`);else await((l=m.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n,i;if(this._sessionId)try{let o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(await((n=a.body)===null||n===void 0?void 0:n.cancel()),!a.ok&&a.status!==405)throw new As(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Xy=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(vM(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(vM(this),r)}};function o8(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function BS(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(BS).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${BS(t.cause)}`:t.message:`${t}`}function vM(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var bM=t=>{throw TypeError(t)},eI=(t,e,r)=>e.has(t)||bM("Cannot "+r),Ze=(t,e,r)=>(eI(t,e,"read from private field"),r?r.call(t):e.get(t)),er=(t,e,r)=>e.has(t)?bM("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Et=(t,e,r,n)=>(eI(t,e,"write to private field"),e.set(t,r),r),Co=(t,e,r)=>(eI(t,e,"access private method"),r),ln,Ja,Iu,Hy,Ky,jp,Tu,Dp,zs,Eu,Au,Pu,Rp,hi,GS,HS,XS,_M,KS,JS,Mp,YS,QS,Ya=class extends EventTarget{constructor(e,r){var n,i;super(),er(this,hi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,er(this,ln),er(this,Ja),er(this,Iu),er(this,Hy),er(this,Ky),er(this,jp),er(this,Tu),er(this,Dp,null),er(this,zs),er(this,Eu),er(this,Au,null),er(this,Pu,null),er(this,Rp,null),er(this,HS,async o=>{var s;Ze(this,Eu).reset();let{body:a,redirected:l,status:c,headers:u}=o;if(c===204){Co(this,hi,Mp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Et(this,Iu,new URL(o.url)):Et(this,Iu,void 0),c!==200){Co(this,hi,Mp).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Co(this,hi,Mp).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.OPEN);let d=new Event("open");if((s=Ze(this,Rp))==null||s.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){Co(this,hi,Mp).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let p=new TextDecoder,f=a.getReader(),m=!0;do{let{done:h,value:y}=await f.read();y&&Ze(this,Eu).feed(p.decode(y,{stream:!h})),h&&(m=!1,Ze(this,Eu).reset(),Co(this,hi,YS).call(this))}while(m)}),er(this,XS,o=>{Et(this,zs,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Co(this,hi,YS).call(this,BS(o))}),er(this,KS,o=>{typeof o.id=="string"&&Et(this,Dp,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Ze(this,Iu)?Ze(this,Iu).origin:Ze(this,Ja).origin,lastEventId:o.id||""});Ze(this,Pu)&&(!o.event||o.event==="message")&&Ze(this,Pu).call(this,s),this.dispatchEvent(s)}),er(this,JS,o=>{Et(this,jp,o)}),er(this,QS,()=>{Et(this,Tu,void 0),Ze(this,ln)===this.CONNECTING&&Co(this,hi,GS).call(this)});try{if(e instanceof URL)Et(this,Ja,e);else if(typeof e=="string")Et(this,Ja,new URL(e,s8()));else throw new Error("Invalid URL")}catch{throw o8("An invalid or illegal string was specified")}Et(this,Eu,Wy({onEvent:Ze(this,KS),onRetry:Ze(this,JS)})),Et(this,ln,this.CONNECTING),Et(this,jp,3e3),Et(this,Ky,(n=r?.fetch)!=null?n:globalThis.fetch),Et(this,Hy,(i=r?.withCredentials)!=null?i:!1),Co(this,hi,GS).call(this)}get readyState(){return Ze(this,ln)}get url(){return Ze(this,Ja).href}get withCredentials(){return Ze(this,Hy)}get onerror(){return Ze(this,Au)}set onerror(e){Et(this,Au,e)}get onmessage(){return Ze(this,Pu)}set onmessage(e){Et(this,Pu,e)}get onopen(){return Ze(this,Rp)}set onopen(e){Et(this,Rp,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Ze(this,Tu)&&clearTimeout(Ze(this,Tu)),Ze(this,ln)!==this.CLOSED&&(Ze(this,zs)&&Ze(this,zs).abort(),Et(this,ln,this.CLOSED),Et(this,zs,void 0))}};ln=new WeakMap,Ja=new WeakMap,Iu=new WeakMap,Hy=new WeakMap,Ky=new WeakMap,jp=new WeakMap,Tu=new WeakMap,Dp=new WeakMap,zs=new WeakMap,Eu=new WeakMap,Au=new WeakMap,Pu=new WeakMap,Rp=new WeakMap,hi=new WeakSet,GS=function(){Et(this,ln,this.CONNECTING),Et(this,zs,new AbortController),Ze(this,Ky)(Ze(this,Ja),Co(this,hi,_M).call(this)).then(Ze(this,HS)).catch(Ze(this,XS))},HS=new WeakMap,XS=new WeakMap,_M=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ze(this,Dp)?{"Last-Event-ID":Ze(this,Dp)}:void 0},cache:"no-store",signal:(t=Ze(this,zs))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},KS=new WeakMap,JS=new WeakMap,Mp=function(t,e){var r;Ze(this,ln)!==this.CLOSED&&Et(this,ln,this.CLOSED);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n)},YS=function(t,e){var r;if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.CONNECTING);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n),Et(this,Tu,setTimeout(Ze(this,QS),Ze(this,jp)))},QS=new WeakMap,Ya.CONNECTING=0,Ya.OPEN=1,Ya.CLOSED=2;function s8(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var tI=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Jy=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Vy(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new Ya(this._url.href,{...this._eventSourceInit,fetch:async(a,l)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let u=await i(a,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:p}=Su(u);this._resourceMetadataUrl=d,this._scope=p}return u}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var l;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let c=new tI(a.code,a.message,a);s(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var l;let c=a;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){s(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}o()}),this._eventSource.onmessage=a=>{var l,c;let u=a,d;try{d=Gc.parse(JSON.parse(u.data))}catch(p){(l=this.onerror)===null||l===void 0||l.call(this,p);return}(c=this.onmessage)===null||c===void 0||c.call(this,d)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i,o;if(!this._endpoint)throw new Error("Not connected");try{let s=await this._commonHeaders();s.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!l.ok){let c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Su(l);if(this._resourceMetadataUrl=u,this._scope=d,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((i=l.body)===null||i===void 0?void 0:i.cancel())}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}};var Fi={name:"@intelliweave/embedded",version:"2.0.72-beta.4",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.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var tr=new Ve("MCPKnowledgeClient"),Yy=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(){tr.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new xp({name:Fi.name,version:Fi.version}),n=new Gy(new URL(this.config.baseURL));return await r.connect(n),tr.debug("Connected with HTTP streaming mode"),r}).catch(async r=>{let n=new xp({name:Fi.name,version:Fi.version}),i=new Jy(new URL(this.config.baseURL));return await n.connect(i),tr.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=r=>{tr.error(`MCP client error: ${r.message}`)},e.onclose=()=>{tr.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(ax,r=>{r.params.level=="critical"?tr.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?tr.error(`[Server] ${r.params.data}`):r.params.level=="error"?tr.error(`[Server] ${r.params.data}`):r.params.level=="warning"?tr.warn(`[Server] ${r.params.data}`):r.params.level=="info"?tr.info(`[Server] ${r.params.data}`):r.params.level=="debug"?tr.debug(`[Server] ${r.params.data}`):tr.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(sx,r=>{tr.debug("Tool list changed",r),this.fetchTools()}),tr.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})}tr.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,tr.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 tr.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(),tr.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 tr.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 l8=new Ve("Statistics"),Lp=[];async function Gr(t,e){let r={...e,event_id:dr(),event_date:new Date().toISOString(),sdk_version:Fi.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Lp.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Lp.length===0))return;let n=Lp.slice();Lp.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){l8.warn("Failed to submit analytics event:",i),Lp.push(...n);return}}var Qa=new Ve("KnowledgeBase"),rI=1,Qy=class t{constructor(e){this._sources=[{id:"core.internal",query:async()=>hP(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${rI++}`),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 St().knowledgeBaseSources&&(e=e.concat(St().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(r=>!r.disabled),e}async search(e){let r=Date.now();Qa.debug(`Searching knowledge base for: ${e}`);let n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],typeof document<"u"&&document.dispatchEvent(n),this._windowSources=n.sources;let o=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),d=await c.query(e);return Qa.debug(`Source '${c.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Qa.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),St().knowledgeBase&&(o=o.concat(St().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);for(let c=0;c<o.length;c++){let u=o[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new mP({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(e).map(c=>o.find(u=>u.id==c.id));for(let c of o)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Gr(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Qa.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${rI++}`),Qa.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Qa.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},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 p=await d.json();return a(p.updateItems||[]),p.response},a=l=>{for(let c of l){if(!c.id){Qa.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(){let e=new t(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${rI++}`);let r=new Yy(e);return this.registerSource(e.id,n=>r.search(n)),r}};var ev=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
96
96
|
|
|
97
97
|
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}
|
|
98
98
|
|
|
@@ -765,7 +765,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
|
|
|
765
765
|
|
|
766
766
|
</div>
|
|
767
767
|
|
|
768
|
-
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new tv,gm.isSupported&&(this.ai.audio=new gm(this.ai))}onCreate(){St().embed&&un.warn("Only one <web-weaver-embed> element should be on the page."),St().embed=this;let r=St();un.debug("[WebWeaverEmbed] Client config:",r),r.displayMode&&!this.attr.displayMode&&(un.debug("[WebWeaverEmbed] Setting displayMode from client config:",r.displayMode),this.attr.displayMode=r.displayMode),r.layout&&!this.attr.layout&&(un.debug("[WebWeaverEmbed] Setting layout from client config:",r.layout),this.attr.layout=r.layout),r.positioningMode&&!this.attr.positioningMode&&(un.debug("[WebWeaverEmbed] Setting positioningMode from client config:",r.positioningMode),this.attr.positioningMode=r.positioningMode),r.positionX&&!this.attr.positionX&&(un.debug("[WebWeaverEmbed] Setting positionX from client config:",r.positionX),this.attr.positionX=r.positionX),r.positionY&&!this.attr.positionY&&(un.debug("[WebWeaverEmbed] Setting positionY from client config:",r.positionY),this.attr.positionY=r.positionY),r.offsetX!==void 0&&!this.attr.offsetX&&(un.debug("[WebWeaverEmbed] Setting offsetX from client config:",r.offsetX),this.attr.offsetX=String(r.offsetX)),r.offsetY!==void 0&&!this.attr.offsetY&&(un.debug("[WebWeaverEmbed] Setting offsetY from client config:",r.offsetY),this.attr.offsetY=String(r.offsetY)),un.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",o=>this.onContainerClick(o)),this.child("web-weaver-logo").addEventListener("click",o=>this.onLogoClick(o)),this.child("interaction-bar").addEventListener("input-message",o=>this.processInput(o.detail)),this.child("interaction-bar").addEventListener("llm-button-click",o=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",o=>this.onLLMModelSelect(o)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:o=>(this.suggestions.push(o.text),"Suggestion button added")});let i=this.attr.apiKey||St().apiKey;if(!i)return un.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(i).then(o=>{this.config=o.config,St().introductionMessage=this.config.introductionMessage,St().analytics=this.config.analytics!==void 0?!!this.config.analytics:St().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(o=>{un.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(r,n){if(!n){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.removeProperty("--intelliweave-interaction-bg");return}let i=this.parseColorToRGB(n);if(!i){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.setProperty("--intelliweave-interaction-bg",n);return}let{r:o,g:s,b:a}=i;r.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${a}, 0.65)`),r.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),r.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${a}, 0.9)`)}parseColorToRGB(r){if(!r)return null;let n=r.trim();if(n.startsWith("#")){let i=n.slice(1);if(i.length===3){let o=parseInt(i[0]+i[0],16),s=parseInt(i[1]+i[1],16),a=parseInt(i[2]+i[2],16);return{r:o,g:s,b:a}}if(i.length===6){let o=parseInt(i.slice(0,2),16),s=parseInt(i.slice(2,4),16),a=parseInt(i.slice(4,6),16);return{r:o,g:s,b:a}}return null}if(n.startsWith("rgb")){let i=n.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return i?{r:Math.max(0,Math.min(255,Math.round(Number(i[1])))),g:Math.max(0,Math.min(255,Math.round(Number(i[2])))),b:Math.max(0,Math.min(255,Math.round(Number(i[3]))))}:null}return null}applyConfigStylesAndAttributes(){let r=this.config,n=this.child("root");if(!n)return;let i=!1,s=this.attr.logo||r.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,i=!0;let ie=this.child("web-weaver-logo");ie&&ie.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),c=r.name||"";c!==this._lastPersonaName&&(this._lastPersonaName=c,l&&(l.textContent=c),i=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),i=!0);let u=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(u){let ie=d==="hidden"||d==="none"||d==="false";u.style.display=!ie&&(s||c)?"":"none"}let f=this.attr.background||r.background;f!==this._lastBackground&&(this._lastBackground=f,i=!0,f?(n.style.background=f,n.style.setProperty("--intelliweave-persona-bg",f),this.applyPersonaColorVariants(n,f)):(n.style.background="",n.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(n,void 0)));let h=this.attr.textColor||r.textColor,y=this.child("interaction-bar");h!==this._lastTextColor&&(this._lastTextColor=h,i=!0,h?(n.style.color=h,n.style.setProperty("--intelliweave-user-bubble-text",h),n.style.setProperty("--intelliweave-assistant-bubble-text",h),y&&y.setAttribute("textColor",h)):(n.style.color="",n.style.removeProperty("--intelliweave-user-bubble-text"),n.style.removeProperty("--intelliweave-assistant-bubble-text"),y&&y.removeAttribute("textColor")));let _=this.attr.displayMode||r.displayMode||"closed";_!==this._lastDisplayMode&&(this._lastDisplayMode=_,i=!0,_==="open"&&!this.attr.open&&(this.attr.open=!0));let E=this.attr.layout||r.layout||"widget";E!==this._lastLayout&&(this._lastLayout=E,i=!0);let P=this.attr.positioningMode||r.positioningMode||"fixed";P!==this._lastPositioningMode&&(this._lastPositioningMode=P,i=!0);let V=this.attr.positionX||r.positionX||"right";V!==this._lastPositionX&&(this._lastPositionX=V,i=!0);let L=this.attr.positionY||r.positionY||"bottom";L!==this._lastPositionY&&(this._lastPositionY=L,i=!0);let G=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,H=G!==void 0?G:r.offsetX!==void 0?r.offsetX:20;H!==this._lastOffsetX&&(this._lastOffsetX=H,i=!0);let W=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,Y=W!==void 0?W:r.offsetY!==void 0?r.offsetY:20;Y!==this._lastOffsetY&&(this._lastOffsetY=Y,i=!0),i&&un.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:n.style.background,finalTextColor:n.style.color,finalDisplayMode:_,finalLayout:E,finalPositioningMode:P,finalPositionX:V,finalPositionY:L,finalOffsetX:H,finalOffsetY:Y})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),Gr(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let c=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;Gr(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:c}})}this._previousOpenState=this.attr.open;let r=this.child("root");this.attr.open?r.classList.add("open"):r.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(r.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):r.classList.remove("layout-fullscreen");let i=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;i==="container"?(r.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):r.classList.remove("container-mode"),i!=="container"&&(r.style.left="",r.style.right="",r.style.top="",r.style.bottom="",o==="left"?r.style.left=a+"px":r.style.right=a+"px",s==="top"?r.style.top=l+"px":r.style.bottom=l+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((c,u)=>(u.priority||0)-(c.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){St().embed==this&&(St().embed=void 0)}onContainerClick(r){let n=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&n!=="open"&&(this.attr.open||(r.preventDefault(),this.attr.open=!0))}onLogoClick(r){if(r.preventDefault(),r.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let n=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||n==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let r=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;r.children.length>0;)r.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let n=document.createElement("div");n.className="introduction-message",n.innerHTML=St().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,r.appendChild(n),this.ai.insertAssistantMessage(n.innerText);for(let i of St().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",s=>this.onSuggestionClick(s,i)),r.appendChild(o)}}async processInput(r){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let n=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let a of Array.from(n.querySelectorAll(".suggestion-button")))a.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=r,n.appendChild(i);let o=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",n.appendChild(this.currentOutputElement);let s=Math.ceil(n.clientHeight-300);s<0&&(s=0),s>600&&(s=600),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"}),await this.ai.sendMessage(r);for(let a of this.suggestions){let l=document.createElement("div");l.className="suggestion-button",l.innerText=a,l.addEventListener("click",c=>this.onSuggestionClick(c,a)),this.currentOutputElement.appendChild(l)}}catch(i){un.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,n.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),n.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(r,n){let i=[];for(let o of r)for(let s=0;s<(o.sections?.length||0);s++){let a=o.sections[s],l=`msgelem-${o.id||""}_${s}_${a.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let c=a.text||"";c.includes(`
|
|
768
|
+
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new tv,gm.isSupported&&(this.ai.audio=new gm(this.ai))}onCreate(){St().embed&&un.warn("Only one <web-weaver-embed> element should be on the page."),St().embed=this;let r=St();un.debug("[WebWeaverEmbed] Client config:",r),r.displayMode&&!this.attr.displayMode&&(un.debug("[WebWeaverEmbed] Setting displayMode from client config:",r.displayMode),this.attr.displayMode=r.displayMode),r.layout&&!this.attr.layout&&(un.debug("[WebWeaverEmbed] Setting layout from client config:",r.layout),this.attr.layout=r.layout),r.positioningMode&&!this.attr.positioningMode&&(un.debug("[WebWeaverEmbed] Setting positioningMode from client config:",r.positioningMode),this.attr.positioningMode=r.positioningMode),r.positionX&&!this.attr.positionX&&(un.debug("[WebWeaverEmbed] Setting positionX from client config:",r.positionX),this.attr.positionX=r.positionX),r.positionY&&!this.attr.positionY&&(un.debug("[WebWeaverEmbed] Setting positionY from client config:",r.positionY),this.attr.positionY=r.positionY),r.offsetX!==void 0&&!this.attr.offsetX&&(un.debug("[WebWeaverEmbed] Setting offsetX from client config:",r.offsetX),this.attr.offsetX=String(r.offsetX)),r.offsetY!==void 0&&!this.attr.offsetY&&(un.debug("[WebWeaverEmbed] Setting offsetY from client config:",r.offsetY),this.attr.offsetY=String(r.offsetY)),un.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",o=>this.onContainerClick(o)),this.child("web-weaver-logo").addEventListener("click",o=>this.onLogoClick(o)),this.child("interaction-bar").addEventListener("input-message",o=>this.processInput(o.detail)),this.child("interaction-bar").addEventListener("llm-button-click",o=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",o=>this.onLLMModelSelect(o)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:o=>(this.suggestions.push(o.text),"Suggestion button added")});let i=this.attr.apiKey||St().apiKey;if(!i)return un.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(i).then(o=>{this.config=o.config,St().introductionMessage=this.config.introductionMessage,St().analytics=this.config.analytics!==void 0?!!this.config.analytics:St().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(o=>{un.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(r,n){if(!n){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.removeProperty("--intelliweave-interaction-bg");return}let i=this.parseColorToRGB(n);if(!i){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.setProperty("--intelliweave-interaction-bg",n);return}let{r:o,g:s,b:a}=i;r.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${a}, 0.65)`),r.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),r.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${a}, 0.9)`)}parseColorToRGB(r){if(!r)return null;let n=r.trim();if(n.startsWith("#")){let i=n.slice(1);if(i.length===3){let o=parseInt(i[0]+i[0],16),s=parseInt(i[1]+i[1],16),a=parseInt(i[2]+i[2],16);return{r:o,g:s,b:a}}if(i.length===6){let o=parseInt(i.slice(0,2),16),s=parseInt(i.slice(2,4),16),a=parseInt(i.slice(4,6),16);return{r:o,g:s,b:a}}return null}if(n.startsWith("rgb")){let i=n.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return i?{r:Math.max(0,Math.min(255,Math.round(Number(i[1])))),g:Math.max(0,Math.min(255,Math.round(Number(i[2])))),b:Math.max(0,Math.min(255,Math.round(Number(i[3]))))}:null}return null}applyConfigStylesAndAttributes(){let r=this.config,n=this.child("root");if(!n)return;let i=!1,s=this.attr.logo||r.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,i=!0;let ie=this.child("web-weaver-logo");ie&&ie.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),c=r.name||"";c!==this._lastPersonaName&&(this._lastPersonaName=c,l&&(l.textContent=c),i=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),i=!0);let u=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(u){let ie=d==="hidden"||d==="none"||d==="false";u.style.display=!ie&&(s||c)?"":"none"}let f=this.attr.background||r.background;f!==this._lastBackground&&(this._lastBackground=f,i=!0,f?(n.style.background=f,n.style.setProperty("--intelliweave-persona-bg",f),this.applyPersonaColorVariants(n,f)):(n.style.background="",n.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(n,void 0)));let h=this.attr.textColor||r.textColor,y=this.child("interaction-bar");h!==this._lastTextColor&&(this._lastTextColor=h,i=!0,h?(n.style.color=h,n.style.setProperty("--intelliweave-user-bubble-text",h),n.style.setProperty("--intelliweave-assistant-bubble-text",h),y&&y.setAttribute("textColor",h)):(n.style.color="",n.style.removeProperty("--intelliweave-user-bubble-text"),n.style.removeProperty("--intelliweave-assistant-bubble-text"),y&&y.removeAttribute("textColor")));let _=this.attr.displayMode||r.displayMode||"closed";_!==this._lastDisplayMode&&(this._lastDisplayMode=_,i=!0,_==="open"&&!this.attr.open&&(this.attr.open=!0));let E=this.attr.layout||r.layout||"widget";E!==this._lastLayout&&(this._lastLayout=E,i=!0);let P=this.attr.positioningMode||r.positioningMode||"fixed";P!==this._lastPositioningMode&&(this._lastPositioningMode=P,i=!0);let V=this.attr.positionX||r.positionX||"right";V!==this._lastPositionX&&(this._lastPositionX=V,i=!0);let L=this.attr.positionY||r.positionY||"bottom";L!==this._lastPositionY&&(this._lastPositionY=L,i=!0);let G=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,H=G!==void 0?G:r.offsetX!==void 0?r.offsetX:20;H!==this._lastOffsetX&&(this._lastOffsetX=H,i=!0);let W=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,Y=W!==void 0?W:r.offsetY!==void 0?r.offsetY:20;Y!==this._lastOffsetY&&(this._lastOffsetY=Y,i=!0),i&&un.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:n.style.background,finalTextColor:n.style.color,finalDisplayMode:_,finalLayout:E,finalPositioningMode:P,finalPositionX:V,finalPositionY:L,finalOffsetX:H,finalOffsetY:Y})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),Gr(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let c=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;Gr(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:c}})}this._previousOpenState=this.attr.open;let r=this.child("root");this.attr.open?r.classList.add("open"):r.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(r.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):r.classList.remove("layout-fullscreen");let i=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;i==="container"?(r.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):r.classList.remove("container-mode"),i!=="container"&&(r.style.left="",r.style.right="",r.style.top="",r.style.bottom="",o==="left"?r.style.left=a+"px":r.style.right=a+"px",s==="top"?r.style.top=l+"px":r.style.bottom=l+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((c,u)=>(u.priority||0)-(c.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){St().embed==this&&(St().embed=void 0)}onContainerClick(r){let n=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&n!=="open"&&(this.attr.open||(r.preventDefault(),this.attr.open=!0))}onLogoClick(r){if(r.preventDefault(),r.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let n=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||n==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let r=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;r.children.length>0;)r.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let n=document.createElement("div");n.className="introduction-message",n.innerHTML=St().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,r.appendChild(n),this.ai.insertAssistantMessage(n.innerText);for(let i of St().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",s=>this.onSuggestionClick(s,i)),r.appendChild(o)}}async processInput(r){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let n=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let c of Array.from(n.querySelectorAll(".suggestion-button")))c.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=r,n.appendChild(i);let o=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",n.appendChild(this.currentOutputElement);let s=Math.ceil(n.clientHeight-300);s<0&&(s=0),s>600&&(s=600),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"});let a=await this.ai.sendMessage(r);for(let c of this.suggestions){let u=document.createElement("div");u.className="suggestion-button",u.innerText=c,u.addEventListener("click",d=>this.onSuggestionClick(d,c)),this.currentOutputElement.appendChild(u)}let l=a.text()||"";this.ai.audio?.speechRecognition?.isRunning&&this.ai.audio.speechOutput.speak(l)}catch(i){un.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,n.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),n.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(r,n){let i=[];for(let o of r)for(let s=0;s<(o.sections?.length||0);s++){let a=o.sections[s],l=`msgelem-${o.id||""}_${s}_${a.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let c=a.text||"";c.includes(`
|
|
769
769
|
`)&&(c=c.split(`
|
|
770
770
|
`)[0]),this.updateInfoElement(l,c,"thinking-icon"),i.push(l)}else if(a.type=="tool_call"){let u=new zu(r).toolResult(a.toolCallInstanceID||"");if(a.toolCallHiddenInUI!="always"){if(u?.toolErrorResponse)this.updateInfoElement(l,"**Error:** "+u.toolErrorResponse||"","tool-icon"),i.push(l);else if(!(a.toolCallHiddenInUI=="after-complete"&&u))if(a.toolKbID=="search"){let d=a.toolParameters?.query?`**Search:** ${a.toolParameters.query}`:"**Search**";this.updateInfoElement(l,d,"tool-icon"),i.push(l)}else this.updateInfoElement(l,a.toolKbName||"","tool-icon"),i.push(l)}}else if(a.type!="tool_result"){if(!a.text)continue;this.updateTextElement(l,a.text||""),i.push(l)}}for(let o of Array.from(this.currentOutputElement.children))i.includes(o.id)||o.remove()}updateTextElement(r,n){let i=this.currentOutputElement.querySelector(`#${r}`);i||(i=document.createElement("div"),i.id=r,i.className="output",this.currentOutputElement.appendChild(i));let o=jv().use(lm).use(cm).use(Kp,{target:"_blank",rel:["noopener","noreferrer"]}).use(Jp).use(tm).processSync(n||"");i.innerHTML=o.toString("utf-8")}updateInfoElement(r,n,i){let o=this.currentOutputElement.querySelector(`#${r}`);o||(o=document.createElement("div"),o.id=r,o.className="info-block",o.innerHTML=`
|
|
771
771
|
<div class='info-block-icon'></div>
|