@intelliweave/embedded 2.0.70 → 2.0.71
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.
|
@@ -11,7 +11,7 @@ import{v4 as Me}from"uuid";function ye(l){let i=(l||"").split(`
|
|
|
11
11
|
|
|
12
12
|
`),i.createGroup("actions").setItemPadding(25),i.createGroup("messages").setItemPadding(10),i})();this.config=i,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(i){throw new Error("Not implemented")}addUserMessage(i){throw new Error("Not implemented")}addAssistantMessage(i){throw new Error("Not implemented")}onBeforeIncomingMessage(i){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(i){return this.toolGroup.add({id:i.name,customData:i,cannotRemove:i.isContext,sortOrder:101,disabled:i.disabled,content:JSON.stringify(i)})}};import{v4 as X}from"uuid";var S=new h("ChatGPT"),H=class extends W{async sendMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(e),customData:e}),await this.processMessages();let s=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return s?.role=="assistant"&&s.content||""}addAssistantMessage(i){let e={role:"assistant",content:i};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(e),customData:e})}addUserMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(i=>i.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),S.debugEnabled&&S.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(t=>t.customData),messages:this.messageGroup.items.map(t=>t.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let t of e.tool_calls)await this.processToolCall(t);await this.processMessages()}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendRequest(i){let e={};return e["Content-Type"]="application/json",this.config.apiKey&&(e.Authorization=`Bearer ${this.config.apiKey}`),await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:e,body:JSON.stringify(i)})}async sendToAPI(i){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let a=this.messageGroup.items.length-1;a>=0;a--){let d=this.messageGroup.items[a].customData;if(d.role=="assistant"&&d.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(d.role=="user")break}S.debugEnabled&&S.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(a=>a.customData),messages:this.messageGroup.items.map(a=>a.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(a=>a.customData)]};for(let a of this.toolGroup.getAll()){let d=a.customData;d.description&&d.description.length>1024&&S.warn(`Tool description for "${d.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:d.name,description:(d.description||"").substring(0,1024),parameters:d.params}};t.tools.push(c)}if(t.user||delete t.user,t.tools.length||delete t.tools,i)return t;let s=await this.sendRequest(t);if(!s.ok){let a=`${s.status} ${s.statusText}`;try{let c=await s.json();a=c.errorText||c.error?.message||c.error||a}catch{}let d=new Error(a);throw d.code=s.status,d}let n=null,o=null;if(this.config.stream){for await(let d of ke(s.body)){if(d.data=="[DONE]")break;if(!d.data)continue;let c=JSON.parse(d.data);if(o){for(let r in c.choices[0].delta)if(typeof c.choices[0].delta[r]=="string"){if(r=="role"&&o[r]==c.choices[0].delta[r])continue;o[r]=(o[r]||"")+c.choices[0].delta[r]}for(let r of c.choices[0].delta.tool_calls||[]){if(o.tool_calls||(o.tool_calls=[]),!o.tool_calls[r.index]){o.tool_calls[r.index]=r;continue}let u=o.tool_calls[r.index];u.function=u.function||{},u.function.name=(u.function.name||"")+(r.function?.name||""),u.function.arguments=(u.function.arguments||"")+(r.function?.arguments||"")}}else o={chunkID:c.id,...c.choices[0].delta};o?.content&&!o.content.startsWith("{")&&this.config.onAIMessage?.(o.content,!0)}let a=Fe(JSON.stringify(t)+JSON.stringify(o)||"");this.stats.tokensUsed+=a,S.debug(`Estimated ${a} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else n=await s.json(),this.stats.tokensUsed+=n?.usage?.total_tokens||0,S.debug(`Used ${n?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),o=n?.choices?.[0]?.message;if(o||(S.warn("No response block in API response."),o={role:"assistant",content:""}),o.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(o),this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(o),customData:o}),o.content&&this.config.onAIMessage?.(o.content,!1)}async processToolCall(i){try{let t=this.toolGroup.items.find(a=>a.id==i.function.name)?.customData;if(!t)throw new Error(`Tool "${i.function.name}" not found.`);let s=JSON.parse(i.function.arguments);this.config.onAIToolStart?.(i.function.name,s);let n=await t.callback(s);typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success");let o={role:"tool",content:n,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(o),customData:o})}catch(e){S.warn(`Unable to process tool call for "${i?.function?.name}"`,e);let t={role:"tool",content:`Error: ${e.message}`,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(t),customData:t})}}};import Ye from"@anthropic-ai/sdk";import{v4 as U}from"uuid";var j=new h("AnthropicChat"),$=class extends W{addUserMessage(i){let e={role:"user",content:i||""};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(e),customData:e})}addAssistantMessage(i){let e={role:"assistant",content:i||""};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(e),customData:e})}async sendMessage(i){this.addUserMessage(i);let e=new Ye({apiKey:this.config.apiKey,baseURL:this.config.endpoint,dangerouslyAllowBrowser:!0}),t=!0,s="",n="";for(;t;){t=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),j.debug("Before processing state",{messages:this.messageGroup.getAll().map(p=>p.customData),tools:this.toolGroup.getAll().map(p=>p.customData),context:this.contextGroup.getAll().map(p=>p.content)});let o=this.toolGroup.getAll().map(p=>({name:p.customData?.name||"",description:p.customData?.description||"",input_schema:{type:"object",required:p.customData?.params.required||[],properties:p.customData?.params.properties||{}}})),a;if(this.config.stream){let p=e.messages.stream({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(Z=>Z.customData),tools:o,stream:!0});p.on("text",Z=>{n+=Z,this.config.onAIMessage?.(n,!0)}),a=await p.finalMessage()}else a=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(p=>p.customData),tools:o});j.debug("Message received",a);let d=!0;Array.isArray(a.content)&&a.content.length==0&&(d=!1);let c={role:a.role,content:a.content};d&&this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(c),customData:c});let r=[];for(let p of a.content)p.type=="thinking"?j.debug(`AI is thinking: ${p.thinking}`):p.type=="text"?s+=p.text||`
|
|
13
13
|
|
|
14
|
-
`:p.type=="tool_use"&&r.push(this.performToolCall(p));let u=await Promise.all(r);if(u.length>0){let p={role:"user",content:u};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(p),customData:p}),t=!0}this.config.onAIMessage?.(s,!0),this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return s=s.trim(),this.config.onAIMessage?.(s,!1),s}async performToolCall(i){try{let e=this.toolGroup.getAll().find(s=>s.customData?.name==i.name);if(!e)throw new Error(`Tool ${i.name} not found`);this.config.onAIToolStart?.(i.name,i.input);let t=await e.customData.callback(i.input);return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),{type:"tool_result",tool_use_id:i.id,content:String(t||"")}}catch(e){return j.error(`Error performing tool call ${i.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:i.id,content:`Error performing tool call ${i.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import{v4 as we}from"uuid";import Qe from"minisearch";var Xe=l=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(i,e)=>{let t=await e.knowledgeBase.search(i.query),s=e;s._lastKBsearch=i.query,s._nextRequestUseKBitems=t,e.submitAnalyticsEvent({type:"kb-search",query:i.query,results:t});let n=t.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=t.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:i.url}),`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,e.submitAnalyticsEvent({type:"change-route",path:t}),`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),s=encodeURIComponent(i.subject),n=encodeURIComponent(i.body),o=`mailto:${t}?subject=${s}&body=${n}`;try{window.location.href=o}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:i.email_address,subject:i.subject,body_length:i.body.length}),`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as Te}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Oe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Je}from"@modelcontextprotocol/sdk/client/sse.js";var G={name:"@intelliweave/embedded",version:"2.0.70",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as He,ToolListChangedNotificationSchema as Ue}from"@modelcontextprotocol/sdk/types.js";var g=new h("MCPKnowledgeClient"),Q=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){g.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Te({name:G.name,version:G.version}),t=new Oe(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Te({name:G.name,version:G.version}),s=new Je(new URL(this.config.baseURL));return await t.connect(s),g.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{g.error(`MCP client error: ${e.message}`)},i.onclose=()=>{g.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(He,e=>{e.params.level=="critical"?g.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?g.error(`[Server] ${e.params.data}`):e.params.level=="error"?g.error(`[Server] ${e.params.data}`):e.params.level=="warning"?g.warn(`[Server] ${e.params.data}`):e.params.level=="info"?g.info(`[Server] ${e.params.data}`):e.params.level=="debug"?g.debug(`[Server] ${e.params.data}`):g.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(Ue,e=>{g.debug("Tool list changed",e),this.fetchTools()}),g.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let s=await this.client.listTools({cursor:e});e=s.nextCursor;for(let n of s.tools||[])i.push(n);if(!s?.tools?.length||!e)break}let t=[];for(let s of i){let n=!!(this.config.searchToolName&&s.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:s.name,name:s.name,content:s.description||"",type:"action",isContext:!0,parameters:s.inputSchema,action:o=>this.performToolCall(s.name,o),disabled:n})}g.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,g.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return g.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let s;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let n=0;n<s.length;n++){let o=s[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return e}async performToolCall(i,e){await this.connect(),g.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let s=t.content?.[0]?.text||"Unknown error";throw g.error(`Error calling tool ${i}: ${s}`),new Error(`Error calling tool ${i}: ${s}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};import{v4 as je}from"uuid";var $e=new h("Statistics"),N=[];async function f(l,i){let e={...i,event_id:je(),event_date:new Date().toISOString(),sdk_version:G.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(N.push(e),!l||(await new Promise(s=>setTimeout(s,5e3)),N.length===0))return;let t=N.slice();N.length=0;try{let s=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){$e.warn("Failed to submit analytics event:",s),N.push(...t);return}}var k=new h("KnowledgeBase"),ve=1,q=class l{constructor(i){this._sources=[{id:"core.internal",query:async()=>Xe(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.${ve++}`),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 m().knowledgeBaseSources&&(i=i.concat(m().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();k.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async c=>{try{let r=Date.now(),u=await c.query(i);return k.debug(`Source '${c.id}' took ${Date.now()-r}ms`),u||[]}catch(r){return k.warn(`Knowledge source '${c.id}' failed:`,r),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),m().knowledgeBase&&(n=n.concat(m().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let r=n[c];r.id=r.id||`temp.${c}`,r._functionID=r.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!r.action&&r.type=="tour"&&(r.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!r.action&&r.type=="info"&&(r.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new Qe({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(n);let d=o.search(i).map(c=>n.find(r=>r.id==c.id));for(let c of n)c.isContext&&(d.find(r=>r.id===c.id)||d.push(c));return this.lastResults=d,f(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),k.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${ve++}`),k.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{k.debug(`Calling remote knowledge base action: ${d.id}`);let r={type:"action",userID:this.ai.userID,actionID:d.id,parameters:c},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return a(p.updateItems||[]),p.response},a=d=>{for(let c of d){if(!c.id){k.warn("KB item skipped since it has no ID.",c);continue}let r=t.find(u=>u.id==c.id);if(r){r.name=c.name||r.name||"",r.content=c.content||r.content||"",r.disabled=c.disabled??r.disabled,r.isContext=c.isContext??r.isContext,r.parameters=c.parameters||r.parameters||[],r.tags=c.tags||r.tags,r.type=c.type||r.type;continue}t.push({...c,action:u=>o(c,u)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",query:d},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let u=await r.json();return n=!u.noCache,s.includes(d)||s.push(d),a(u.items),t})}clone(){let i=new l(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${ve++}`);let e=new Q(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ee=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
14
|
+
`:p.type=="tool_use"&&r.push(this.performToolCall(p));let u=await Promise.all(r);if(u.length>0){let p={role:"user",content:u};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(p),customData:p}),t=!0}this.config.onAIMessage?.(s,!0),this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return s=s.trim(),this.config.onAIMessage?.(s,!1),s}async performToolCall(i){try{let e=this.toolGroup.getAll().find(s=>s.customData?.name==i.name);if(!e)throw new Error(`Tool ${i.name} not found`);this.config.onAIToolStart?.(i.name,i.input);let t=await e.customData.callback(i.input);return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),{type:"tool_result",tool_use_id:i.id,content:String(t||"")}}catch(e){return j.error(`Error performing tool call ${i.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:i.id,content:`Error performing tool call ${i.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import{v4 as we}from"uuid";import Qe from"minisearch";var Xe=l=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(i,e)=>{let t=await e.knowledgeBase.search(i.query),s=e;s._lastKBsearch=i.query,s._nextRequestUseKBitems=t,e.submitAnalyticsEvent({type:"kb-search",query:i.query,results:t});let n=t.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=t.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:i.url}),`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,e.submitAnalyticsEvent({type:"change-route",path:t}),`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),s=encodeURIComponent(i.subject),n=encodeURIComponent(i.body),o=`mailto:${t}?subject=${s}&body=${n}`;try{window.location.href=o}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:i.email_address,subject:i.subject,body_length:i.body.length}),`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as Te}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Oe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Je}from"@modelcontextprotocol/sdk/client/sse.js";var G={name:"@intelliweave/embedded",version:"2.0.71",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as He,ToolListChangedNotificationSchema as Ue}from"@modelcontextprotocol/sdk/types.js";var g=new h("MCPKnowledgeClient"),Q=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){g.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Te({name:G.name,version:G.version}),t=new Oe(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Te({name:G.name,version:G.version}),s=new Je(new URL(this.config.baseURL));return await t.connect(s),g.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{g.error(`MCP client error: ${e.message}`)},i.onclose=()=>{g.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(He,e=>{e.params.level=="critical"?g.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?g.error(`[Server] ${e.params.data}`):e.params.level=="error"?g.error(`[Server] ${e.params.data}`):e.params.level=="warning"?g.warn(`[Server] ${e.params.data}`):e.params.level=="info"?g.info(`[Server] ${e.params.data}`):e.params.level=="debug"?g.debug(`[Server] ${e.params.data}`):g.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(Ue,e=>{g.debug("Tool list changed",e),this.fetchTools()}),g.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let s=await this.client.listTools({cursor:e});e=s.nextCursor;for(let n of s.tools||[])i.push(n);if(!s?.tools?.length||!e)break}let t=[];for(let s of i){let n=!!(this.config.searchToolName&&s.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:s.name,name:s.name,content:s.description||"",type:"action",isContext:!0,parameters:s.inputSchema,action:o=>this.performToolCall(s.name,o),disabled:n})}g.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,g.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return g.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let s;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let n=0;n<s.length;n++){let o=s[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return e}async performToolCall(i,e){await this.connect(),g.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let s=t.content?.[0]?.text||"Unknown error";throw g.error(`Error calling tool ${i}: ${s}`),new Error(`Error calling tool ${i}: ${s}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};import{v4 as je}from"uuid";var $e=new h("Statistics"),N=[];async function f(l,i){let e={...i,event_id:je(),event_date:new Date().toISOString(),sdk_version:G.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(N.push(e),!l||(await new Promise(s=>setTimeout(s,5e3)),N.length===0))return;let t=N.slice();N.length=0;try{let s=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){$e.warn("Failed to submit analytics event:",s),N.push(...t);return}}var k=new h("KnowledgeBase"),ve=1,q=class l{constructor(i){this._sources=[{id:"core.internal",query:async()=>Xe(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.${ve++}`),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 m().knowledgeBaseSources&&(i=i.concat(m().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();k.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async c=>{try{let r=Date.now(),u=await c.query(i);return k.debug(`Source '${c.id}' took ${Date.now()-r}ms`),u||[]}catch(r){return k.warn(`Knowledge source '${c.id}' failed:`,r),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),m().knowledgeBase&&(n=n.concat(m().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let r=n[c];r.id=r.id||`temp.${c}`,r._functionID=r.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!r.action&&r.type=="tour"&&(r.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!r.action&&r.type=="info"&&(r.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new Qe({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(n);let d=o.search(i).map(c=>n.find(r=>r.id==c.id));for(let c of n)c.isContext&&(d.find(r=>r.id===c.id)||d.push(c));return this.lastResults=d,f(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),k.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${ve++}`),k.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{k.debug(`Calling remote knowledge base action: ${d.id}`);let r={type:"action",userID:this.ai.userID,actionID:d.id,parameters:c},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return a(p.updateItems||[]),p.response},a=d=>{for(let c of d){if(!c.id){k.warn("KB item skipped since it has no ID.",c);continue}let r=t.find(u=>u.id==c.id);if(r){r.name=c.name||r.name||"",r.content=c.content||r.content||"",r.disabled=c.disabled??r.disabled,r.isContext=c.isContext??r.isContext,r.parameters=c.parameters||r.parameters||[],r.tags=c.tags||r.tags,r.type=c.type||r.type;continue}t.push({...c,action:u=>o(c,u)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",query:d},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let u=await r.json();return n=!u.noCache,s.includes(d)||s.push(d),a(u.items),t})}clone(){let i=new l(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${ve++}`);let e=new Q(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ee=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
15
15
|
|
|
16
16
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(e.toLowerCase().includes("true"))return!0;if(e.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+e)}async choose(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
17
17
|
|
|
Binary file
|
package/dist/node/node.js
CHANGED
|
@@ -11,7 +11,7 @@ import{v4 as J}from"uuid";function G(u){let t=(u||"").split(`
|
|
|
11
11
|
|
|
12
12
|
`),t.createGroup("actions").setItemPadding(25),t.createGroup("messages").setItemPadding(10),t})();this.config=t,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(t){throw new Error("Not implemented")}addUserMessage(t){throw new Error("Not implemented")}addAssistantMessage(t){throw new Error("Not implemented")}onBeforeIncomingMessage(t){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(t){return this.toolGroup.add({id:t.name,customData:t,cannotRemove:t.isContext,sortOrder:101,disabled:t.disabled,content:JSON.stringify(t)})}};import{v4 as T}from"uuid";var w=new g("ChatGPT"),D=class extends I{async sendMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e}),await this.processMessages();let n=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return n?.role=="assistant"&&n.content||""}addAssistantMessage(t){let e={role:"assistant",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e})}addUserMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(t=>t.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),w.debugEnabled&&w.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(s=>s.customData),messages:this.messageGroup.items.map(s=>s.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let s of e.tool_calls)await this.processToolCall(s);await this.processMessages()}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendRequest(t){let e={};return e["Content-Type"]="application/json",this.config.apiKey&&(e.Authorization=`Bearer ${this.config.apiKey}`),await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:e,body:JSON.stringify(t)})}async sendToAPI(t){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let a=this.messageGroup.items.length-1;a>=0;a--){let r=this.messageGroup.items[a].customData;if(r.role=="assistant"&&r.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(r.role=="user")break}w.debugEnabled&&w.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(a=>a.customData),messages:this.messageGroup.items.map(a=>a.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let s={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(a=>a.customData)]};for(let a of this.toolGroup.getAll()){let r=a.customData;r.description&&r.description.length>1024&&w.warn(`Tool description for "${r.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:r.name,description:(r.description||"").substring(0,1024),parameters:r.params}};s.tools.push(c)}if(s.user||delete s.user,s.tools.length||delete s.tools,t)return s;let n=await this.sendRequest(s);if(!n.ok){let a=`${n.status} ${n.statusText}`;try{let c=await n.json();a=c.errorText||c.error?.message||c.error||a}catch{}let r=new Error(a);throw r.code=n.status,r}let i=null,o=null;if(this.config.stream){for await(let r of q(n.body)){if(r.data=="[DONE]")break;if(!r.data)continue;let c=JSON.parse(r.data);if(o){for(let l in c.choices[0].delta)if(typeof c.choices[0].delta[l]=="string"){if(l=="role"&&o[l]==c.choices[0].delta[l])continue;o[l]=(o[l]||"")+c.choices[0].delta[l]}for(let l of c.choices[0].delta.tool_calls||[]){if(o.tool_calls||(o.tool_calls=[]),!o.tool_calls[l.index]){o.tool_calls[l.index]=l;continue}let m=o.tool_calls[l.index];m.function=m.function||{},m.function.name=(m.function.name||"")+(l.function?.name||""),m.function.arguments=(m.function.arguments||"")+(l.function?.arguments||"")}}else o={chunkID:c.id,...c.choices[0].delta};o?.content&&!o.content.startsWith("{")&&this.config.onAIMessage?.(o.content,!0)}let a=oe(JSON.stringify(s)+JSON.stringify(o)||"");this.stats.tokensUsed+=a,w.debug(`Estimated ${a} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else i=await n.json(),this.stats.tokensUsed+=i?.usage?.total_tokens||0,w.debug(`Used ${i?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),o=i?.choices?.[0]?.message;if(o||(w.warn("No response block in API response."),o={role:"assistant",content:""}),o.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(o),this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(o),customData:o}),o.content&&this.config.onAIMessage?.(o.content,!1)}async processToolCall(t){try{let s=this.toolGroup.items.find(a=>a.id==t.function.name)?.customData;if(!s)throw new Error(`Tool "${t.function.name}" not found.`);let n=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,n);let i=await s.callback(n);typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success");let o={role:"tool",content:i,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(o),customData:o})}catch(e){w.warn(`Unable to process tool call for "${t?.function?.name}"`,e);let s={role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(s),customData:s})}}};import re from"@anthropic-ai/sdk";import{v4 as P}from"uuid";var O=new g("AnthropicChat"),N=class extends I{addUserMessage(t){let e={role:"user",content:t||""};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(e),customData:e})}addAssistantMessage(t){let e={role:"assistant",content:t||""};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(e),customData:e})}async sendMessage(t){this.addUserMessage(t);let e=new re({apiKey:this.config.apiKey,baseURL:this.config.endpoint,dangerouslyAllowBrowser:!0}),s=!0,n="",i="";for(;s;){s=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),O.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.customData),tools:this.toolGroup.getAll().map(d=>d.customData),context:this.contextGroup.getAll().map(d=>d.content)});let o=this.toolGroup.getAll().map(d=>({name:d.customData?.name||"",description:d.customData?.description||"",input_schema:{type:"object",required:d.customData?.params.required||[],properties:d.customData?.params.properties||{}}})),a;if(this.config.stream){let d=e.messages.stream({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(v=>v.customData),tools:o,stream:!0});d.on("text",v=>{i+=v,this.config.onAIMessage?.(i,!0)}),a=await d.finalMessage()}else a=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(d=>d.customData),tools:o});O.debug("Message received",a);let r=!0;Array.isArray(a.content)&&a.content.length==0&&(r=!1);let c={role:a.role,content:a.content};r&&this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(c),customData:c});let l=[];for(let d of a.content)d.type=="thinking"?O.debug(`AI is thinking: ${d.thinking}`):d.type=="text"?n+=d.text||`
|
|
13
13
|
|
|
14
|
-
`:d.type=="tool_use"&&l.push(this.performToolCall(d));let m=await Promise.all(l);if(m.length>0){let d={role:"user",content:m};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(d),customData:d}),s=!0}this.config.onAIMessage?.(n,!0),this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return n=n.trim(),this.config.onAIMessage?.(n,!1),n}async performToolCall(t){try{let e=this.toolGroup.getAll().find(n=>n.customData?.name==t.name);if(!e)throw new Error(`Tool ${t.name} not found`);this.config.onAIToolStart?.(t.name,t.input);let s=await e.customData.callback(t.input);return typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),{type:"tool_result",tool_use_id:t.id,content:String(s||"")}}catch(e){return O.error(`Error performing tool call ${t.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:t.id,content:`Error performing tool call ${t.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import ge from"minisearch";var Q=u=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(t,e)=>{let s=await e.knowledgeBase.search(t.query),n=e;n._lastKBsearch=t.query,n._nextRequestUseKBitems=s,e.submitAnalyticsEvent({type:"kb-search",query:t.query,results:s});let i=s.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=s.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!u?.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:(t,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(!t.url||typeof t.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(t.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:t.url}),`Opened URL: ${t.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"||!u?.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:(t,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(!t.path||typeof t.path!="string")throw new Error("Path parameter is required and must be a string.");let s=new URL(t.path,window.location.origin).pathname;return window.location.href=s,e.submitAnalyticsEvent({type:"change-route",path:s}),`Changed route to: ${s}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!u?.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:(t,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(!t.email_address||typeof t.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!t.subject||typeof t.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!t.body||typeof t.body!="string")throw new Error("Body parameter is required and must be a string.");let s=encodeURIComponent(t.email_address),n=encodeURIComponent(t.subject),i=encodeURIComponent(t.body),o=`mailto:${s}?subject=${n}&body=${i}`;try{window.location.href=o}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:t.email_address,subject:t.subject,body_length:t.body.length}),`Email opened in default mail client. Recipient: ${t.email_address}, Subject: ${t.subject}`}}];import{Client as ee}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as le}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as ce}from"@modelcontextprotocol/sdk/client/sse.js";var y={name:"@intelliweave/embedded",version:"2.0.70",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as ue,ToolListChangedNotificationSchema as de}from"@modelcontextprotocol/sdk/types.js";var h=new g("MCPKnowledgeClient"),W=class{constructor(t){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=t}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 t=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new ee({name:y.name,version:y.version}),s=new le(new URL(this.config.baseURL));return await e.connect(s),h.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let s=new ee({name:y.name,version:y.version}),n=new ce(new URL(this.config.baseURL));return await s.connect(n),h.debug("Connected with SSE mode"),s});return await this.disconnect(),this.client=t,t.onerror=e=>{h.error(`MCP client error: ${e.message}`)},t.onclose=()=>{h.debug("MCP client connection closed"),this.client=void 0},t.setNotificationHandler(ue,e=>{e.params.level=="critical"?h.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?h.error(`[Server] ${e.params.data}`):e.params.level=="error"?h.error(`[Server] ${e.params.data}`):e.params.level=="warning"?h.warn(`[Server] ${e.params.data}`):e.params.level=="info"?h.info(`[Server] ${e.params.data}`):e.params.level=="debug"?h.debug(`[Server] ${e.params.data}`):h.log(`[Server] ${e.params.data}`)}),t.setNotificationHandler(de,e=>{h.debug("Tool list changed",e),this.fetchTools()}),h.debug("Fetching tools from MCP server..."),await this.fetchTools(),t}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let t=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let i of n.tools||[])t.push(i);if(!n?.tools?.length||!e)break}let s=[];for(let n of t){let i=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:o=>this.performToolCall(n.name,o),disabled:i})}h.debug(`Fetched ${t.length} tools from MCP server.`),this.tools=t,this.iwActions=s}async search(t){if(t==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),s=await this.performSearchCall(t);return e=e.concat(s),this.lastSearchQuery=t,this.lastSearchResults=e,h.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(t){let e=[];if(!this.config.searchToolName)return e;let s=this.tools.find(i=>i.name==this.config.searchToolName);if(!s)return h.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(s.inputSchema.required?.length==1){let i=s.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let i=Object.keys(s.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let i=0;i<n.length;i++){let o=n[i];e.push({id:this.config.id+":"+this.config.searchToolName+":"+i,name:`Search result ${i+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(t,e){await this.connect(),h.debug(`Performing tool call for ${t} with params:`,e),this.stats.toolsCalled+=1;let s=await this.client.callTool({name:t,arguments:e});if(s.isError){let n=s.content?.[0]?.text||"Unknown error";throw h.error(`Error calling tool ${t}: ${n}`),new Error(`Error calling tool ${t}: ${n}`)}if(Array.isArray(s.content)&&s.content.length==1&&s.content[0].type=="text")try{return JSON.parse(s.content[0].text)}catch{}return s.content||[]}};import{v4 as me}from"uuid";var he=new g("Statistics"),_=[];async function b(u,t){let e={...t,event_id:me(),event_date:new Date().toISOString(),sdk_version:y.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(_.push(e),!u||(await new Promise(n=>setTimeout(n,5e3)),_.length===0))return;let s=_.slice();_.length=0;try{let n=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){he.warn("Failed to submit analytics event:",n),_.push(...s);return}}var S=new g("KnowledgeBase"),j=1,$=class u{constructor(t){this._sources=[{id:"core.internal",query:async()=>Q(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${j++}`),this._sources.push({id:s,query:e}),s}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return p().knowledgeBaseSources&&(t=t.concat(p().knowledgeBaseSources)),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){let e=Date.now();S.debug(`Searching knowledge base for: ${t}`);let s=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});s.query=t,s.entries=[],s.sources=[],typeof document<"u"&&document.dispatchEvent(s),this._windowSources=s.sources;let i=(await Promise.all(this.sources.map(async c=>{try{let l=Date.now(),m=await c.query(t);return S.debug(`Source '${c.id}' took ${Date.now()-l}ms`),m||[]}catch(l){return S.warn(`Knowledge source '${c.id}' failed:`,l),[]}}))).flat();i=i.concat(s.entries),i=i.concat(this.manualEntries),p().knowledgeBase&&(i=i.concat(p().knowledgeBase)),i=i.filter(c=>c&&!c.disabled);for(let c=0;c<i.length;c++){let l=i[c];l.id=l.id||`temp.${c}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!l.action&&l.type=="tour"&&(l.action=m=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=m=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new ge({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let r=o.search(t).map(c=>i.find(l=>l.id==c.id));for(let c of i)c.isContext&&(r.find(l=>l.id===c.id)||r.push(c));return this.lastResults=r,b(this.ai,{event_type:"kb_search",value:r.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),S.debug("Found results:",r),r}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${j++}`),S.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],i=!0,o=async(r,c)=>{S.debug(`Calling remote knowledge base action: ${r.id}`);let l={type:"action",userID:this.ai.userID,actionID:r.id,parameters:c},m=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!m.ok)throw new Error(`HTTP Error ${m.status} ${m.statusText}`);let d=await m.json();return a(d.updateItems||[]),d.response},a=r=>{for(let c of r){if(!c.id){S.warn("KB item skipped since it has no ID.",c);continue}let l=s.find(m=>m.id==c.id);if(l){l.name=c.name||l.name||"",l.content=c.content||l.content||"",l.disabled=c.disabled??l.disabled,l.isContext=c.isContext??l.isContext,l.parameters=c.parameters||l.parameters||[],l.tags=c.tags||l.tags,l.type=c.type||l.type;continue}s.push({...c,action:m=>o(c,m)})}};this.registerSource(e,async r=>{if(i&&n.includes(r))return s;let c={type:"search",userID:this.ai?.userID||"",query:r},l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let m=await l.json();return i=!m.noCache,n.includes(r)||n.push(r),a(m.items),s})}clone(){let t=new u(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}registerMCPSource(t){t.id||(t.id=`external.${j++}`);let e=new W(t);return this.registerSource(t.id,s=>e.search(s)),e}};import{v4 as F}from"uuid";var K=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
14
|
+
`:d.type=="tool_use"&&l.push(this.performToolCall(d));let m=await Promise.all(l);if(m.length>0){let d={role:"user",content:m};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(d),customData:d}),s=!0}this.config.onAIMessage?.(n,!0),this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return n=n.trim(),this.config.onAIMessage?.(n,!1),n}async performToolCall(t){try{let e=this.toolGroup.getAll().find(n=>n.customData?.name==t.name);if(!e)throw new Error(`Tool ${t.name} not found`);this.config.onAIToolStart?.(t.name,t.input);let s=await e.customData.callback(t.input);return typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),{type:"tool_result",tool_use_id:t.id,content:String(s||"")}}catch(e){return O.error(`Error performing tool call ${t.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:t.id,content:`Error performing tool call ${t.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import ge from"minisearch";var Q=u=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(t,e)=>{let s=await e.knowledgeBase.search(t.query),n=e;n._lastKBsearch=t.query,n._nextRequestUseKBitems=s,e.submitAnalyticsEvent({type:"kb-search",query:t.query,results:s});let i=s.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=s.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!u?.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:(t,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(!t.url||typeof t.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(t.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:t.url}),`Opened URL: ${t.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"||!u?.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:(t,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(!t.path||typeof t.path!="string")throw new Error("Path parameter is required and must be a string.");let s=new URL(t.path,window.location.origin).pathname;return window.location.href=s,e.submitAnalyticsEvent({type:"change-route",path:s}),`Changed route to: ${s}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!u?.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:(t,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(!t.email_address||typeof t.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!t.subject||typeof t.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!t.body||typeof t.body!="string")throw new Error("Body parameter is required and must be a string.");let s=encodeURIComponent(t.email_address),n=encodeURIComponent(t.subject),i=encodeURIComponent(t.body),o=`mailto:${s}?subject=${n}&body=${i}`;try{window.location.href=o}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:t.email_address,subject:t.subject,body_length:t.body.length}),`Email opened in default mail client. Recipient: ${t.email_address}, Subject: ${t.subject}`}}];import{Client as ee}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as le}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as ce}from"@modelcontextprotocol/sdk/client/sse.js";var y={name:"@intelliweave/embedded",version:"2.0.71",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as ue,ToolListChangedNotificationSchema as de}from"@modelcontextprotocol/sdk/types.js";var h=new g("MCPKnowledgeClient"),W=class{constructor(t){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=t}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 t=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new ee({name:y.name,version:y.version}),s=new le(new URL(this.config.baseURL));return await e.connect(s),h.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let s=new ee({name:y.name,version:y.version}),n=new ce(new URL(this.config.baseURL));return await s.connect(n),h.debug("Connected with SSE mode"),s});return await this.disconnect(),this.client=t,t.onerror=e=>{h.error(`MCP client error: ${e.message}`)},t.onclose=()=>{h.debug("MCP client connection closed"),this.client=void 0},t.setNotificationHandler(ue,e=>{e.params.level=="critical"?h.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?h.error(`[Server] ${e.params.data}`):e.params.level=="error"?h.error(`[Server] ${e.params.data}`):e.params.level=="warning"?h.warn(`[Server] ${e.params.data}`):e.params.level=="info"?h.info(`[Server] ${e.params.data}`):e.params.level=="debug"?h.debug(`[Server] ${e.params.data}`):h.log(`[Server] ${e.params.data}`)}),t.setNotificationHandler(de,e=>{h.debug("Tool list changed",e),this.fetchTools()}),h.debug("Fetching tools from MCP server..."),await this.fetchTools(),t}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let t=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let i of n.tools||[])t.push(i);if(!n?.tools?.length||!e)break}let s=[];for(let n of t){let i=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:o=>this.performToolCall(n.name,o),disabled:i})}h.debug(`Fetched ${t.length} tools from MCP server.`),this.tools=t,this.iwActions=s}async search(t){if(t==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),s=await this.performSearchCall(t);return e=e.concat(s),this.lastSearchQuery=t,this.lastSearchResults=e,h.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(t){let e=[];if(!this.config.searchToolName)return e;let s=this.tools.find(i=>i.name==this.config.searchToolName);if(!s)return h.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(s.inputSchema.required?.length==1){let i=s.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let i=Object.keys(s.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let i=0;i<n.length;i++){let o=n[i];e.push({id:this.config.id+":"+this.config.searchToolName+":"+i,name:`Search result ${i+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(t,e){await this.connect(),h.debug(`Performing tool call for ${t} with params:`,e),this.stats.toolsCalled+=1;let s=await this.client.callTool({name:t,arguments:e});if(s.isError){let n=s.content?.[0]?.text||"Unknown error";throw h.error(`Error calling tool ${t}: ${n}`),new Error(`Error calling tool ${t}: ${n}`)}if(Array.isArray(s.content)&&s.content.length==1&&s.content[0].type=="text")try{return JSON.parse(s.content[0].text)}catch{}return s.content||[]}};import{v4 as me}from"uuid";var he=new g("Statistics"),_=[];async function b(u,t){let e={...t,event_id:me(),event_date:new Date().toISOString(),sdk_version:y.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(_.push(e),!u||(await new Promise(n=>setTimeout(n,5e3)),_.length===0))return;let s=_.slice();_.length=0;try{let n=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){he.warn("Failed to submit analytics event:",n),_.push(...s);return}}var S=new g("KnowledgeBase"),j=1,$=class u{constructor(t){this._sources=[{id:"core.internal",query:async()=>Q(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${j++}`),this._sources.push({id:s,query:e}),s}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return p().knowledgeBaseSources&&(t=t.concat(p().knowledgeBaseSources)),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){let e=Date.now();S.debug(`Searching knowledge base for: ${t}`);let s=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});s.query=t,s.entries=[],s.sources=[],typeof document<"u"&&document.dispatchEvent(s),this._windowSources=s.sources;let i=(await Promise.all(this.sources.map(async c=>{try{let l=Date.now(),m=await c.query(t);return S.debug(`Source '${c.id}' took ${Date.now()-l}ms`),m||[]}catch(l){return S.warn(`Knowledge source '${c.id}' failed:`,l),[]}}))).flat();i=i.concat(s.entries),i=i.concat(this.manualEntries),p().knowledgeBase&&(i=i.concat(p().knowledgeBase)),i=i.filter(c=>c&&!c.disabled);for(let c=0;c<i.length;c++){let l=i[c];l.id=l.id||`temp.${c}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!l.action&&l.type=="tour"&&(l.action=m=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=m=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new ge({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let r=o.search(t).map(c=>i.find(l=>l.id==c.id));for(let c of i)c.isContext&&(r.find(l=>l.id===c.id)||r.push(c));return this.lastResults=r,b(this.ai,{event_type:"kb_search",value:r.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),S.debug("Found results:",r),r}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${j++}`),S.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],i=!0,o=async(r,c)=>{S.debug(`Calling remote knowledge base action: ${r.id}`);let l={type:"action",userID:this.ai.userID,actionID:r.id,parameters:c},m=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!m.ok)throw new Error(`HTTP Error ${m.status} ${m.statusText}`);let d=await m.json();return a(d.updateItems||[]),d.response},a=r=>{for(let c of r){if(!c.id){S.warn("KB item skipped since it has no ID.",c);continue}let l=s.find(m=>m.id==c.id);if(l){l.name=c.name||l.name||"",l.content=c.content||l.content||"",l.disabled=c.disabled??l.disabled,l.isContext=c.isContext??l.isContext,l.parameters=c.parameters||l.parameters||[],l.tags=c.tags||l.tags,l.type=c.type||l.type;continue}s.push({...c,action:m=>o(c,m)})}};this.registerSource(e,async r=>{if(i&&n.includes(r))return s;let c={type:"search",userID:this.ai?.userID||"",query:r},l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let m=await l.json();return i=!m.noCache,n.includes(r)||n.push(r),a(m.items),s})}clone(){let t=new u(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}registerMCPSource(t){t.id||(t.id=`external.${j++}`);let e=new W(t);return this.registerSource(t.id,s=>e.search(s)),e}};import{v4 as F}from"uuid";var K=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
15
15
|
|
|
16
16
|
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(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
17
17
|
|
package/dist/react/react.js
CHANGED
|
@@ -11,7 +11,7 @@ import Fe,{createContext as wt,useContext as xt,useEffect as ue,useMemo as St,us
|
|
|
11
11
|
|
|
12
12
|
`),i.createGroup("actions").setItemPadding(25),i.createGroup("messages").setItemPadding(10),i})();this.config=i,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(i){throw new Error("Not implemented")}addUserMessage(i){throw new Error("Not implemented")}addAssistantMessage(i){throw new Error("Not implemented")}onBeforeIncomingMessage(i){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(i){return this.toolGroup.add({id:i.name,customData:i,cannotRemove:i.isContext,sortOrder:101,disabled:i.disabled,content:JSON.stringify(i)})}};import{v4 as T}from"uuid";var x=new u("ChatGPT"),H=class extends X{async sendMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e}),await this.processMessages();let s=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return s?.role=="assistant"&&s.content||""}addAssistantMessage(i){let e={role:"assistant",content:i};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e})}addUserMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(i=>i.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),x.debugEnabled&&x.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(t=>t.customData),messages:this.messageGroup.items.map(t=>t.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let t of e.tool_calls)await this.processToolCall(t);await this.processMessages()}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendRequest(i){let e={};return e["Content-Type"]="application/json",this.config.apiKey&&(e.Authorization=`Bearer ${this.config.apiKey}`),await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:e,body:JSON.stringify(i)})}async sendToAPI(i){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let r=this.messageGroup.items.length-1;r>=0;r--){let d=this.messageGroup.items[r].customData;if(d.role=="assistant"&&d.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(d.role=="user")break}x.debugEnabled&&x.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(r=>r.customData),messages:this.messageGroup.items.map(r=>r.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(r=>r.customData)]};for(let r of this.toolGroup.getAll()){let d=r.customData;d.description&&d.description.length>1024&&x.warn(`Tool description for "${d.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:d.name,description:(d.description||"").substring(0,1024),parameters:d.params}};t.tools.push(c)}if(t.user||delete t.user,t.tools.length||delete t.tools,i)return t;let s=await this.sendRequest(t);if(!s.ok){let r=`${s.status} ${s.statusText}`;try{let c=await s.json();r=c.errorText||c.error?.message||c.error||r}catch{}let d=new Error(r);throw d.code=s.status,d}let n=null,o=null;if(this.config.stream){for await(let d of We(s.body)){if(d.data=="[DONE]")break;if(!d.data)continue;let c=JSON.parse(d.data);if(o){for(let l in c.choices[0].delta)if(typeof c.choices[0].delta[l]=="string"){if(l=="role"&&o[l]==c.choices[0].delta[l])continue;o[l]=(o[l]||"")+c.choices[0].delta[l]}for(let l of c.choices[0].delta.tool_calls||[]){if(o.tool_calls||(o.tool_calls=[]),!o.tool_calls[l.index]){o.tool_calls[l.index]=l;continue}let p=o.tool_calls[l.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(l.function?.name||""),p.function.arguments=(p.function.arguments||"")+(l.function?.arguments||"")}}else o={chunkID:c.id,...c.choices[0].delta};o?.content&&!o.content.startsWith("{")&&this.config.onAIMessage?.(o.content,!0)}let r=He(JSON.stringify(t)+JSON.stringify(o)||"");this.stats.tokensUsed+=r,x.debug(`Estimated ${r} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else n=await s.json(),this.stats.tokensUsed+=n?.usage?.total_tokens||0,x.debug(`Used ${n?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),o=n?.choices?.[0]?.message;if(o||(x.warn("No response block in API response."),o={role:"assistant",content:""}),o.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(o),this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(o),customData:o}),o.content&&this.config.onAIMessage?.(o.content,!1)}async processToolCall(i){try{let t=this.toolGroup.items.find(r=>r.id==i.function.name)?.customData;if(!t)throw new Error(`Tool "${i.function.name}" not found.`);let s=JSON.parse(i.function.arguments);this.config.onAIToolStart?.(i.function.name,s);let n=await t.callback(s);typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success");let o={role:"tool",content:n,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(o),customData:o})}catch(e){x.warn(`Unable to process tool call for "${i?.function?.name}"`,e);let t={role:"tool",content:`Error: ${e.message}`,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(t),customData:t})}}};import Ue from"@anthropic-ai/sdk";import{v4 as U}from"uuid";var j=new u("AnthropicChat"),$=class extends X{addUserMessage(i){let e={role:"user",content:i||""};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(e),customData:e})}addAssistantMessage(i){let e={role:"assistant",content:i||""};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(e),customData:e})}async sendMessage(i){this.addUserMessage(i);let e=new Ue({apiKey:this.config.apiKey,baseURL:this.config.endpoint,dangerouslyAllowBrowser:!0}),t=!0,s="",n="";for(;t;){t=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),j.debug("Before processing state",{messages:this.messageGroup.getAll().map(m=>m.customData),tools:this.toolGroup.getAll().map(m=>m.customData),context:this.contextGroup.getAll().map(m=>m.content)});let o=this.toolGroup.getAll().map(m=>({name:m.customData?.name||"",description:m.customData?.description||"",input_schema:{type:"object",required:m.customData?.params.required||[],properties:m.customData?.params.properties||{}}})),r;if(this.config.stream){let m=e.messages.stream({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(Z=>Z.customData),tools:o,stream:!0});m.on("text",Z=>{n+=Z,this.config.onAIMessage?.(n,!0)}),r=await m.finalMessage()}else r=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(m=>m.customData),tools:o});j.debug("Message received",r);let d=!0;Array.isArray(r.content)&&r.content.length==0&&(d=!1);let c={role:r.role,content:r.content};d&&this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(c),customData:c});let l=[];for(let m of r.content)m.type=="thinking"?j.debug(`AI is thinking: ${m.thinking}`):m.type=="text"?s+=m.text||`
|
|
13
13
|
|
|
14
|
-
`:m.type=="tool_use"&&l.push(this.performToolCall(m));let p=await Promise.all(l);if(p.length>0){let m={role:"user",content:p};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(m),customData:m}),t=!0}this.config.onAIMessage?.(s,!0),this.stats.tokensUsed+=r.usage.input_tokens+r.usage.output_tokens}return s=s.trim(),this.config.onAIMessage?.(s,!1),s}async performToolCall(i){try{let e=this.toolGroup.getAll().find(s=>s.customData?.name==i.name);if(!e)throw new Error(`Tool ${i.name} not found`);this.config.onAIToolStart?.(i.name,i.input);let t=await e.customData.callback(i.input);return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),{type:"tool_result",tool_use_id:i.id,content:String(t||"")}}catch(e){return j.error(`Error performing tool call ${i.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:i.id,content:`Error performing tool call ${i.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import{v4 as xe}from"uuid";import st from"minisearch";var Ee=a=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(i,e)=>{let t=await e.knowledgeBase.search(i.query),s=e;s._lastKBsearch=i.query,s._nextRequestUseKBitems=t,e.submitAnalyticsEvent({type:"kb-search",query:i.query,results:t});let n=t.filter(r=>r.type!="action").map(r=>"id="+r.id).join(", ")||"(none)",o=t.filter(r=>r.type=="action").map(r=>"name="+r._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:i.url}),`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,e.submitAnalyticsEvent({type:"change-route",path:t}),`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),s=encodeURIComponent(i.subject),n=encodeURIComponent(i.body),o=`mailto:${t}?subject=${s}&body=${n}`;try{window.location.href=o}catch(r){throw new Error(`Failed to open email client: ${r instanceof Error?r.message:String(r)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:i.email_address,subject:i.subject,body_length:i.body.length}),`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as Re}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as $e}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Qe}from"@modelcontextprotocol/sdk/client/sse.js";var S={name:"@intelliweave/embedded",version:"2.0.70",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as qe,ToolListChangedNotificationSchema as et}from"@modelcontextprotocol/sdk/types.js";var g=new u("MCPKnowledgeClient"),Q=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){g.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Re({name:S.name,version:S.version}),t=new $e(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Re({name:S.name,version:S.version}),s=new Qe(new URL(this.config.baseURL));return await t.connect(s),g.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{g.error(`MCP client error: ${e.message}`)},i.onclose=()=>{g.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(qe,e=>{e.params.level=="critical"?g.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?g.error(`[Server] ${e.params.data}`):e.params.level=="error"?g.error(`[Server] ${e.params.data}`):e.params.level=="warning"?g.warn(`[Server] ${e.params.data}`):e.params.level=="info"?g.info(`[Server] ${e.params.data}`):e.params.level=="debug"?g.debug(`[Server] ${e.params.data}`):g.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(et,e=>{g.debug("Tool list changed",e),this.fetchTools()}),g.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let s=await this.client.listTools({cursor:e});e=s.nextCursor;for(let n of s.tools||[])i.push(n);if(!s?.tools?.length||!e)break}let t=[];for(let s of i){let n=!!(this.config.searchToolName&&s.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:s.name,name:s.name,content:s.description||"",type:"action",isContext:!0,parameters:s.inputSchema,action:o=>this.performToolCall(s.name,o),disabled:n})}g.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,g.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return g.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let s;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let n=0;n<s.length;n++){let o=s[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return e}async performToolCall(i,e){await this.connect(),g.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let s=t.content?.[0]?.text||"Unknown error";throw g.error(`Error calling tool ${i}: ${s}`),new Error(`Error calling tool ${i}: ${s}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};import{v4 as tt}from"uuid";var it=new u("Statistics"),N=[];async function f(a,i){let e={...i,event_id:tt(),event_date:new Date().toISOString(),sdk_version:S.version,conversation_id:a?.conversationID||"",api_key:a?.apiKey||"",user_id:a?.userID||""};if(N.push(e),!a||(await new Promise(s=>setTimeout(s,5e3)),N.length===0))return;let t=N.slice();N.length=0;try{let s=await fetch(a.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){it.warn("Failed to submit analytics event:",s),N.push(...t);return}}var k=new u("KnowledgeBase"),we=1,q=class a{constructor(i){this._sources=[{id:"core.internal",query:async()=>Ee(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${we++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return h().knowledgeBaseSources&&(i=i.concat(h().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();k.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async c=>{try{let l=Date.now(),p=await c.query(i);return k.debug(`Source '${c.id}' took ${Date.now()-l}ms`),p||[]}catch(l){return k.warn(`Knowledge source '${c.id}' failed:`,l),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),h().knowledgeBase&&(n=n.concat(h().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let l=n[c];l.id=l.id||`temp.${c}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!l.action&&l.type=="tour"&&(l.action=p=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=p=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new st({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(n);let d=o.search(i).map(c=>n.find(l=>l.id==c.id));for(let c of n)c.isContext&&(d.find(l=>l.id===c.id)||d.push(c));return this.lastResults=d,f(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),k.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${we++}`),k.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{k.debug(`Calling remote knowledge base action: ${d.id}`);let l={type:"action",userID:this.ai.userID,actionID:d.id,parameters:c},p=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!p.ok)throw new Error(`HTTP Error ${p.status} ${p.statusText}`);let m=await p.json();return r(m.updateItems||[]),m.response},r=d=>{for(let c of d){if(!c.id){k.warn("KB item skipped since it has no ID.",c);continue}let l=t.find(p=>p.id==c.id);if(l){l.name=c.name||l.name||"",l.content=c.content||l.content||"",l.disabled=c.disabled??l.disabled,l.isContext=c.isContext??l.isContext,l.parameters=c.parameters||l.parameters||[],l.tags=c.tags||l.tags,l.type=c.type||l.type;continue}t.push({...c,action:p=>o(c,p)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",query:d},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let p=await l.json();return n=!p.noCache,s.includes(d)||s.push(d),r(p.items),t})}clone(){let i=new a(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${we++}`);let e=new Q(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ee=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
14
|
+
`:m.type=="tool_use"&&l.push(this.performToolCall(m));let p=await Promise.all(l);if(p.length>0){let m={role:"user",content:p};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(m),customData:m}),t=!0}this.config.onAIMessage?.(s,!0),this.stats.tokensUsed+=r.usage.input_tokens+r.usage.output_tokens}return s=s.trim(),this.config.onAIMessage?.(s,!1),s}async performToolCall(i){try{let e=this.toolGroup.getAll().find(s=>s.customData?.name==i.name);if(!e)throw new Error(`Tool ${i.name} not found`);this.config.onAIToolStart?.(i.name,i.input);let t=await e.customData.callback(i.input);return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),{type:"tool_result",tool_use_id:i.id,content:String(t||"")}}catch(e){return j.error(`Error performing tool call ${i.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:i.id,content:`Error performing tool call ${i.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import{v4 as xe}from"uuid";import st from"minisearch";var Ee=a=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(i,e)=>{let t=await e.knowledgeBase.search(i.query),s=e;s._lastKBsearch=i.query,s._nextRequestUseKBitems=t,e.submitAnalyticsEvent({type:"kb-search",query:i.query,results:t});let n=t.filter(r=>r.type!="action").map(r=>"id="+r.id).join(", ")||"(none)",o=t.filter(r=>r.type=="action").map(r=>"name="+r._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:i.url}),`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,e.submitAnalyticsEvent({type:"change-route",path:t}),`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),s=encodeURIComponent(i.subject),n=encodeURIComponent(i.body),o=`mailto:${t}?subject=${s}&body=${n}`;try{window.location.href=o}catch(r){throw new Error(`Failed to open email client: ${r instanceof Error?r.message:String(r)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:i.email_address,subject:i.subject,body_length:i.body.length}),`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as Re}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as $e}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Qe}from"@modelcontextprotocol/sdk/client/sse.js";var S={name:"@intelliweave/embedded",version:"2.0.71",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as qe,ToolListChangedNotificationSchema as et}from"@modelcontextprotocol/sdk/types.js";var g=new u("MCPKnowledgeClient"),Q=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){g.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Re({name:S.name,version:S.version}),t=new $e(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Re({name:S.name,version:S.version}),s=new Qe(new URL(this.config.baseURL));return await t.connect(s),g.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{g.error(`MCP client error: ${e.message}`)},i.onclose=()=>{g.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(qe,e=>{e.params.level=="critical"?g.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?g.error(`[Server] ${e.params.data}`):e.params.level=="error"?g.error(`[Server] ${e.params.data}`):e.params.level=="warning"?g.warn(`[Server] ${e.params.data}`):e.params.level=="info"?g.info(`[Server] ${e.params.data}`):e.params.level=="debug"?g.debug(`[Server] ${e.params.data}`):g.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(et,e=>{g.debug("Tool list changed",e),this.fetchTools()}),g.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let s=await this.client.listTools({cursor:e});e=s.nextCursor;for(let n of s.tools||[])i.push(n);if(!s?.tools?.length||!e)break}let t=[];for(let s of i){let n=!!(this.config.searchToolName&&s.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:s.name,name:s.name,content:s.description||"",type:"action",isContext:!0,parameters:s.inputSchema,action:o=>this.performToolCall(s.name,o),disabled:n})}g.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,g.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return g.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let s;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let n=0;n<s.length;n++){let o=s[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return e}async performToolCall(i,e){await this.connect(),g.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let s=t.content?.[0]?.text||"Unknown error";throw g.error(`Error calling tool ${i}: ${s}`),new Error(`Error calling tool ${i}: ${s}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};import{v4 as tt}from"uuid";var it=new u("Statistics"),N=[];async function f(a,i){let e={...i,event_id:tt(),event_date:new Date().toISOString(),sdk_version:S.version,conversation_id:a?.conversationID||"",api_key:a?.apiKey||"",user_id:a?.userID||""};if(N.push(e),!a||(await new Promise(s=>setTimeout(s,5e3)),N.length===0))return;let t=N.slice();N.length=0;try{let s=await fetch(a.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){it.warn("Failed to submit analytics event:",s),N.push(...t);return}}var k=new u("KnowledgeBase"),we=1,q=class a{constructor(i){this._sources=[{id:"core.internal",query:async()=>Ee(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${we++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return h().knowledgeBaseSources&&(i=i.concat(h().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();k.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async c=>{try{let l=Date.now(),p=await c.query(i);return k.debug(`Source '${c.id}' took ${Date.now()-l}ms`),p||[]}catch(l){return k.warn(`Knowledge source '${c.id}' failed:`,l),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),h().knowledgeBase&&(n=n.concat(h().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let l=n[c];l.id=l.id||`temp.${c}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!l.action&&l.type=="tour"&&(l.action=p=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=p=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new st({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(n);let d=o.search(i).map(c=>n.find(l=>l.id==c.id));for(let c of n)c.isContext&&(d.find(l=>l.id===c.id)||d.push(c));return this.lastResults=d,f(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),k.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${we++}`),k.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{k.debug(`Calling remote knowledge base action: ${d.id}`);let l={type:"action",userID:this.ai.userID,actionID:d.id,parameters:c},p=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!p.ok)throw new Error(`HTTP Error ${p.status} ${p.statusText}`);let m=await p.json();return r(m.updateItems||[]),m.response},r=d=>{for(let c of d){if(!c.id){k.warn("KB item skipped since it has no ID.",c);continue}let l=t.find(p=>p.id==c.id);if(l){l.name=c.name||l.name||"",l.content=c.content||l.content||"",l.disabled=c.disabled??l.disabled,l.isContext=c.isContext??l.isContext,l.parameters=c.parameters||l.parameters||[],l.tags=c.tags||l.tags,l.type=c.type||l.type;continue}t.push({...c,action:p=>o(c,p)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",query:d},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let p=await l.json();return n=!p.noCache,s.includes(d)||s.push(d),r(p.items),t})}clone(){let i=new a(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${we++}`);let e=new Q(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ee=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
15
15
|
|
|
16
16
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(e.toLowerCase().includes("true"))return!0;if(e.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+e)}async choose(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
17
17
|
|
|
@@ -3311,7 +3311,7 @@ Assistant:`;Tt.DEFAULT_TIMEOUT=6e5;Tt.AnthropicError=se;Tt.APIError=qt;Tt.APICon
|
|
|
3311
3311
|
`;break;case"id":s=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new Yh(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:g}));break;default:r(new Yh(`Unknown field "${f.length>20?`${f.slice(0,20)}\u2026`:f}"`,{type:"unknown-field",field:f,value:y,line:g}));break}}function p(){l.length>0&&e({id:s,event:c||void 0,data:l.endsWith(`
|
|
3312
3312
|
`)?l.slice(0,-1):l}),s=void 0,l="",c=""}function h(f={}){a&&f.consume&&d(a),o=!0,s=void 0,l="",c="",a=""}return{feed:u,reset:h}}function x9(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),a=t.indexOf(`
|
|
3313
3313
|
`,n),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i!==-1?o=i:a!==-1&&(o=a),o===-1){r=t.slice(n);break}else{let s=t.slice(n,o);e.push(s),n=o+1,t[n-1]==="\r"&&t[n]===`
|
|
3314
|
-
`&&n++}}return[e,r]}var ef=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(a){i=Qh({onEvent:o=>{a.enqueue(o)},onError(o){e==="terminate"?a.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:n})},transform(a){i.feed(a)}})}};var E9={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},$a=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},tf=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=Xh(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:E9}async _authThenStart(){var e;if(!this._authProvider)throw new Rr("No auth provider");let r;try{r=await Ji(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 Rr;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=Cl((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i,a;let{resumptionToken:o}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),o&&s.set("last-event-id",o);let l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:s,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 $a(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}_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 a=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},a)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:a}=r,o,s=!1,l=!1;(async()=>{var u,d,m,p;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new ef({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:x}=await h.read();if(x)break;if(g.id&&(o=g.id,s=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let v=Js.parse(JSON.parse(g.data));lo(v)&&(l=!0,a!==void 0&&(v.id=a)),(u=this.onmessage)===null||u===void 0||u.call(this,v)}catch(v){(d=this.onerror)===null||d===void 0||d.call(this,v)}}(n||s)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a},0)}catch(h){if((m=this.onerror)===null||m===void 0||m.call(this,new Error(`SSE stream disconnected: ${h}`)),(n||s)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a},0)}catch(g){(p=this.onerror)===null||p===void 0||p.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 Rr("No auth provider");if(await Ji(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rr("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,a,o,s,l,c;try{let{resumptionToken:u,onresumptiontoken:d}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:qc(e)?e.id:void 0}).catch(v=>{var I;return(I=this.onerror)===null||I===void 0?void 0:I.call(this,v)});return}let m=await this._commonHeaders();m.set("content-type","application/json"),m.set("accept","application/json, text/event-stream");let p={...this._requestInit,method:"POST",headers:m,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},h=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,p),f=h.headers.get("mcp-session-id");if(f&&(this._sessionId=f),!h.ok){let v=await h.text().catch(()=>null);if(h.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new $a(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:I,scope:T}=Il(h);if(this._resourceMetadataUrl=I,this._scope=T,await Ji(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rr;return this._hasCompletedAuthFlow=!0,this.send(e)}if(h.status===403&&this._authProvider){let{resourceMetadataUrl:I,scope:T,error:C}=Il(h);if(C==="insufficient_scope"){let M=h.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new $a(403,"Server returned 403 after trying upscoping");if(T&&(this._scope=T),I&&(this._resourceMetadataUrl=I),this._lastUpscopingHeader=M??void 0,await Ji(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Rr;return this.send(e)}}throw new $a(h.status,`Error POSTing to endpoint: ${v}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,h.status===202){await((a=h.body)===null||a===void 0?void 0:a.cancel()),oI(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(v=>{var I;return(I=this.onerror)===null||I===void 0?void 0:I.call(this,v)});return}let g=(Array.isArray(e)?e:[e]).filter(v=>"method"in v&&"id"in v&&v.id!==void 0).length>0,x=h.headers.get("content-type");if(g)if(x?.includes("text/event-stream"))this._handleSseStream(h.body,{onresumptiontoken:d},!1);else if(x?.includes("application/json")){let v=await h.json(),I=Array.isArray(v)?v.map(T=>Js.parse(T)):[Js.parse(v)];for(let T of I)(o=this.onmessage)===null||o===void 0||o.call(this,T)}else throw await((s=h.body)===null||s===void 0?void 0:s.cancel()),new $a(-1,`Unexpected content type: ${x}`);else await((l=h.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 a=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:a,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},s=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,o);if(await((n=s.body)===null||n===void 0?void 0:n.cancel()),!s.ok&&s.status!==405)throw new $a(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(a){throw(i=this.onerror)===null||i===void 0||i.call(this,a),a}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var nf=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(OO(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(OO(this),r)}};function T9(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Ik(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Ik).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Ik(t.cause)}`:t.message:`${t}`}function OO(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var MO=t=>{throw TypeError(t)},$k=(t,e,r)=>e.has(t)||MO("Cannot "+r),De=(t,e,r)=>($k(t,e,"read from private field"),r?r.call(t):e.get(t)),Vt=(t,e,r)=>e.has(t)?MO("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),wt=(t,e,r,n)=>($k(t,e,"write to private field"),e.set(t,r),r),Xi=(t,e,r)=>($k(t,e,"access private method"),r),Wr,$o,Al,rf,af,bd,Nl,vd,La,Pl,Ol,Rl,gd,Kn,Ak,Pk,Rk,DO,Nk,Ok,yd,Dk,Mk,Lo=class extends EventTarget{constructor(e,r){var n,i;super(),Vt(this,Kn),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Vt(this,Wr),Vt(this,$o),Vt(this,Al),Vt(this,rf),Vt(this,af),Vt(this,bd),Vt(this,Nl),Vt(this,vd,null),Vt(this,La),Vt(this,Pl),Vt(this,Ol,null),Vt(this,Rl,null),Vt(this,gd,null),Vt(this,Pk,async a=>{var o;De(this,Pl).reset();let{body:s,redirected:l,status:c,headers:u}=a;if(c===204){Xi(this,Kn,yd).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?wt(this,Al,new URL(a.url)):wt(this,Al,void 0),c!==200){Xi(this,Kn,yd).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Xi(this,Kn,yd).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(De(this,Wr)===this.CLOSED)return;wt(this,Wr,this.OPEN);let d=new Event("open");if((o=De(this,gd))==null||o.call(this,d),this.dispatchEvent(d),typeof s!="object"||!s||!("getReader"in s)){Xi(this,Kn,yd).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let m=new TextDecoder,p=s.getReader(),h=!0;do{let{done:f,value:y}=await p.read();y&&De(this,Pl).feed(m.decode(y,{stream:!f})),f&&(h=!1,De(this,Pl).reset(),Xi(this,Kn,Dk).call(this))}while(h)}),Vt(this,Rk,a=>{wt(this,La,void 0),!(a.name==="AbortError"||a.type==="aborted")&&Xi(this,Kn,Dk).call(this,Ik(a))}),Vt(this,Nk,a=>{typeof a.id=="string"&&wt(this,vd,a.id);let o=new MessageEvent(a.event||"message",{data:a.data,origin:De(this,Al)?De(this,Al).origin:De(this,$o).origin,lastEventId:a.id||""});De(this,Rl)&&(!a.event||a.event==="message")&&De(this,Rl).call(this,o),this.dispatchEvent(o)}),Vt(this,Ok,a=>{wt(this,bd,a)}),Vt(this,Mk,()=>{wt(this,Nl,void 0),De(this,Wr)===this.CONNECTING&&Xi(this,Kn,Ak).call(this)});try{if(e instanceof URL)wt(this,$o,e);else if(typeof e=="string")wt(this,$o,new URL(e,C9()));else throw new Error("Invalid URL")}catch{throw T9("An invalid or illegal string was specified")}wt(this,Pl,Qh({onEvent:De(this,Nk),onRetry:De(this,Ok)})),wt(this,Wr,this.CONNECTING),wt(this,bd,3e3),wt(this,af,(n=r?.fetch)!=null?n:globalThis.fetch),wt(this,rf,(i=r?.withCredentials)!=null?i:!1),Xi(this,Kn,Ak).call(this)}get readyState(){return De(this,Wr)}get url(){return De(this,$o).href}get withCredentials(){return De(this,rf)}get onerror(){return De(this,Ol)}set onerror(e){wt(this,Ol,e)}get onmessage(){return De(this,Rl)}set onmessage(e){wt(this,Rl,e)}get onopen(){return De(this,gd)}set onopen(e){wt(this,gd,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(){De(this,Nl)&&clearTimeout(De(this,Nl)),De(this,Wr)!==this.CLOSED&&(De(this,La)&&De(this,La).abort(),wt(this,Wr,this.CLOSED),wt(this,La,void 0))}};Wr=new WeakMap,$o=new WeakMap,Al=new WeakMap,rf=new WeakMap,af=new WeakMap,bd=new WeakMap,Nl=new WeakMap,vd=new WeakMap,La=new WeakMap,Pl=new WeakMap,Ol=new WeakMap,Rl=new WeakMap,gd=new WeakMap,Kn=new WeakSet,Ak=function(){wt(this,Wr,this.CONNECTING),wt(this,La,new AbortController),De(this,af)(De(this,$o),Xi(this,Kn,DO).call(this)).then(De(this,Pk)).catch(De(this,Rk))},Pk=new WeakMap,Rk=new WeakMap,DO=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...De(this,vd)?{"Last-Event-ID":De(this,vd)}:void 0},cache:"no-store",signal:(t=De(this,La))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Nk=new WeakMap,Ok=new WeakMap,yd=function(t,e){var r;De(this,Wr)!==this.CLOSED&&wt(this,Wr,this.CLOSED);let n=new nf("error",{code:e,message:t});(r=De(this,Ol))==null||r.call(this,n),this.dispatchEvent(n)},Dk=function(t,e){var r;if(De(this,Wr)===this.CLOSED)return;wt(this,Wr,this.CONNECTING);let n=new nf("error",{code:e,message:t});(r=De(this,Ol))==null||r.call(this,n),this.dispatchEvent(n),wt(this,Nl,setTimeout(De(this,Mk),De(this,bd)))},Mk=new WeakMap,Lo.CONNECTING=0,Lo.OPEN=1,Lo.CLOSED=2;function C9(){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 Lk=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},of=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=Xh(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new Rr("No auth provider");let r;try{r=await Ji(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 Rr;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=Cl((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((a,o)=>{this._eventSource=new Lo(this._url.href,{...this._eventSourceInit,fetch:async(s,l)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let u=await i(s,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:m}=Il(u);this._resourceMetadataUrl=d,this._scope=m}return u}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{var l;if(s.code===401&&this._authProvider){this._authThenStart().then(a,o);return}let c=new Lk(s.code,s.message,s);o(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{var l;let c=s;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){o(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}a()}),this._eventSource.onmessage=s=>{var l,c;let u=s,d;try{d=Js.parse(JSON.parse(u.data))}catch(m){(l=this.onerror)===null||l===void 0||l.call(this,m);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 Rr("No auth provider");if(await Ji(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rr("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,a;if(!this._endpoint)throw new Error("Not connected");try{let o=await this._commonHeaders();o.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:o,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,s);if(!l.ok){let c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Il(l);if(this._resourceMetadataUrl=u,this._scope=d,await Ji(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rr;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(o){throw(a=this.onerror)===null||a===void 0||a.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}};var Yi={name:"@intelliweave/embedded",version:"2.0.70",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var Ht=new Re("MCPKnowledgeClient"),sf=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(){Ht.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new nd({name:Yi.name,version:Yi.version}),n=new tf(new URL(this.config.baseURL));return await r.connect(n),Ht.debug("Connected with HTTP streaming mode"),r}).catch(async r=>{let n=new nd({name:Yi.name,version:Yi.version}),i=new of(new URL(this.config.baseURL));return await n.connect(i),Ht.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=r=>{Ht.error(`MCP client error: ${r.message}`)},e.onclose=()=>{Ht.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(Gv,r=>{r.params.level=="critical"?Ht.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?Ht.error(`[Server] ${r.params.data}`):r.params.level=="error"?Ht.error(`[Server] ${r.params.data}`):r.params.level=="warning"?Ht.warn(`[Server] ${r.params.data}`):r.params.level=="info"?Ht.info(`[Server] ${r.params.data}`):r.params.level=="debug"?Ht.debug(`[Server] ${r.params.data}`):Ht.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Uv,r=>{Ht.debug("Tool list changed",r),this.fetchTools()}),Ht.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 a of i.tools||[])e.push(a);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let a=!!(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:o=>this.performToolCall(i.name,o),disabled:a})}Ht.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,Ht.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(a=>a.name==this.config.searchToolName);if(!n)return Ht.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let a=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[a]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let a=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[a]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let a=0;a<i.length;a++){let o=i[a];r.push({id:this.config.id+":"+this.config.searchToolName+":"+a,name:`Search result ${a+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}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(),Ht.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 Ht.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 A9=new Re("Statistics"),_d=[];async function Nr(t,e){let r={...e,event_id:_t(),event_date:new Date().toISOString(),sdk_version:Yi.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(_d.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),_d.length===0))return;let n=_d.slice();_d.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){A9.warn("Failed to submit analytics event:",i),_d.push(...n);return}}var zo=new Re("KnowledgeBase"),zk=1,lf=class t{constructor(e){this._sources=[{id:"core.internal",query:async()=>PT(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.${zk++}`),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 ht().knowledgeBaseSources&&(e=e.concat(ht().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(r=>!r.disabled),e}async search(e){let r=Date.now();zo.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 a=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),d=await c.query(e);return zo.debug(`Source '${c.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return zo.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();a=a.concat(n.entries),a=a.concat(this.manualEntries),ht().knowledgeBase&&(a=a.concat(ht().knowledgeBase)),a=a.filter(c=>c&&!c.disabled);for(let c=0;c<a.length;c++){let u=a[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!u.action&&u.type=="tour"&&(u.action=d=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!u.action&&u.type=="info"&&(u.action=d=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new AT({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(a);let l=o.search(e).map(c=>a.find(u=>u.id==c.id));for(let c of a)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Nr(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),zo.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${zk++}`),zo.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],a=!0,o=async(l,c)=>{zo.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 m=await d.json();return s(m.updateItems||[]),m.response},s=l=>{for(let c of l){if(!c.id){zo.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=>o(c,d)})}};this.registerSource(r,async l=>{if(a&&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 a=!d.noCache,i.includes(l)||i.push(l),s(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.${zk++}`);let r=new sf(e);return this.registerSource(e.id,n=>r.search(n)),r}};var cf=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
3314
|
+
`&&n++}}return[e,r]}var ef=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(a){i=Qh({onEvent:o=>{a.enqueue(o)},onError(o){e==="terminate"?a.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:n})},transform(a){i.feed(a)}})}};var E9={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},$a=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},tf=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=Xh(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:E9}async _authThenStart(){var e;if(!this._authProvider)throw new Rr("No auth provider");let r;try{r=await Ji(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 Rr;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=Cl((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i,a;let{resumptionToken:o}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),o&&s.set("last-event-id",o);let l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:s,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 $a(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}_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 a=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},a)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:a}=r,o,s=!1,l=!1;(async()=>{var u,d,m,p;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new ef({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:x}=await h.read();if(x)break;if(g.id&&(o=g.id,s=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let v=Js.parse(JSON.parse(g.data));lo(v)&&(l=!0,a!==void 0&&(v.id=a)),(u=this.onmessage)===null||u===void 0||u.call(this,v)}catch(v){(d=this.onerror)===null||d===void 0||d.call(this,v)}}(n||s)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a},0)}catch(h){if((m=this.onerror)===null||m===void 0||m.call(this,new Error(`SSE stream disconnected: ${h}`)),(n||s)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:a},0)}catch(g){(p=this.onerror)===null||p===void 0||p.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 Rr("No auth provider");if(await Ji(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rr("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,a,o,s,l,c;try{let{resumptionToken:u,onresumptiontoken:d}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:qc(e)?e.id:void 0}).catch(v=>{var I;return(I=this.onerror)===null||I===void 0?void 0:I.call(this,v)});return}let m=await this._commonHeaders();m.set("content-type","application/json"),m.set("accept","application/json, text/event-stream");let p={...this._requestInit,method:"POST",headers:m,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},h=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,p),f=h.headers.get("mcp-session-id");if(f&&(this._sessionId=f),!h.ok){let v=await h.text().catch(()=>null);if(h.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new $a(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:I,scope:T}=Il(h);if(this._resourceMetadataUrl=I,this._scope=T,await Ji(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rr;return this._hasCompletedAuthFlow=!0,this.send(e)}if(h.status===403&&this._authProvider){let{resourceMetadataUrl:I,scope:T,error:C}=Il(h);if(C==="insufficient_scope"){let M=h.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new $a(403,"Server returned 403 after trying upscoping");if(T&&(this._scope=T),I&&(this._resourceMetadataUrl=I),this._lastUpscopingHeader=M??void 0,await Ji(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Rr;return this.send(e)}}throw new $a(h.status,`Error POSTing to endpoint: ${v}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,h.status===202){await((a=h.body)===null||a===void 0?void 0:a.cancel()),oI(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(v=>{var I;return(I=this.onerror)===null||I===void 0?void 0:I.call(this,v)});return}let g=(Array.isArray(e)?e:[e]).filter(v=>"method"in v&&"id"in v&&v.id!==void 0).length>0,x=h.headers.get("content-type");if(g)if(x?.includes("text/event-stream"))this._handleSseStream(h.body,{onresumptiontoken:d},!1);else if(x?.includes("application/json")){let v=await h.json(),I=Array.isArray(v)?v.map(T=>Js.parse(T)):[Js.parse(v)];for(let T of I)(o=this.onmessage)===null||o===void 0||o.call(this,T)}else throw await((s=h.body)===null||s===void 0?void 0:s.cancel()),new $a(-1,`Unexpected content type: ${x}`);else await((l=h.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 a=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:a,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},s=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,o);if(await((n=s.body)===null||n===void 0?void 0:n.cancel()),!s.ok&&s.status!==405)throw new $a(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(a){throw(i=this.onerror)===null||i===void 0||i.call(this,a),a}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var nf=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(OO(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(OO(this),r)}};function T9(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Ik(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Ik).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Ik(t.cause)}`:t.message:`${t}`}function OO(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var MO=t=>{throw TypeError(t)},$k=(t,e,r)=>e.has(t)||MO("Cannot "+r),De=(t,e,r)=>($k(t,e,"read from private field"),r?r.call(t):e.get(t)),Vt=(t,e,r)=>e.has(t)?MO("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),wt=(t,e,r,n)=>($k(t,e,"write to private field"),e.set(t,r),r),Xi=(t,e,r)=>($k(t,e,"access private method"),r),Wr,$o,Al,rf,af,bd,Nl,vd,La,Pl,Ol,Rl,gd,Kn,Ak,Pk,Rk,DO,Nk,Ok,yd,Dk,Mk,Lo=class extends EventTarget{constructor(e,r){var n,i;super(),Vt(this,Kn),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Vt(this,Wr),Vt(this,$o),Vt(this,Al),Vt(this,rf),Vt(this,af),Vt(this,bd),Vt(this,Nl),Vt(this,vd,null),Vt(this,La),Vt(this,Pl),Vt(this,Ol,null),Vt(this,Rl,null),Vt(this,gd,null),Vt(this,Pk,async a=>{var o;De(this,Pl).reset();let{body:s,redirected:l,status:c,headers:u}=a;if(c===204){Xi(this,Kn,yd).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?wt(this,Al,new URL(a.url)):wt(this,Al,void 0),c!==200){Xi(this,Kn,yd).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Xi(this,Kn,yd).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(De(this,Wr)===this.CLOSED)return;wt(this,Wr,this.OPEN);let d=new Event("open");if((o=De(this,gd))==null||o.call(this,d),this.dispatchEvent(d),typeof s!="object"||!s||!("getReader"in s)){Xi(this,Kn,yd).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let m=new TextDecoder,p=s.getReader(),h=!0;do{let{done:f,value:y}=await p.read();y&&De(this,Pl).feed(m.decode(y,{stream:!f})),f&&(h=!1,De(this,Pl).reset(),Xi(this,Kn,Dk).call(this))}while(h)}),Vt(this,Rk,a=>{wt(this,La,void 0),!(a.name==="AbortError"||a.type==="aborted")&&Xi(this,Kn,Dk).call(this,Ik(a))}),Vt(this,Nk,a=>{typeof a.id=="string"&&wt(this,vd,a.id);let o=new MessageEvent(a.event||"message",{data:a.data,origin:De(this,Al)?De(this,Al).origin:De(this,$o).origin,lastEventId:a.id||""});De(this,Rl)&&(!a.event||a.event==="message")&&De(this,Rl).call(this,o),this.dispatchEvent(o)}),Vt(this,Ok,a=>{wt(this,bd,a)}),Vt(this,Mk,()=>{wt(this,Nl,void 0),De(this,Wr)===this.CONNECTING&&Xi(this,Kn,Ak).call(this)});try{if(e instanceof URL)wt(this,$o,e);else if(typeof e=="string")wt(this,$o,new URL(e,C9()));else throw new Error("Invalid URL")}catch{throw T9("An invalid or illegal string was specified")}wt(this,Pl,Qh({onEvent:De(this,Nk),onRetry:De(this,Ok)})),wt(this,Wr,this.CONNECTING),wt(this,bd,3e3),wt(this,af,(n=r?.fetch)!=null?n:globalThis.fetch),wt(this,rf,(i=r?.withCredentials)!=null?i:!1),Xi(this,Kn,Ak).call(this)}get readyState(){return De(this,Wr)}get url(){return De(this,$o).href}get withCredentials(){return De(this,rf)}get onerror(){return De(this,Ol)}set onerror(e){wt(this,Ol,e)}get onmessage(){return De(this,Rl)}set onmessage(e){wt(this,Rl,e)}get onopen(){return De(this,gd)}set onopen(e){wt(this,gd,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(){De(this,Nl)&&clearTimeout(De(this,Nl)),De(this,Wr)!==this.CLOSED&&(De(this,La)&&De(this,La).abort(),wt(this,Wr,this.CLOSED),wt(this,La,void 0))}};Wr=new WeakMap,$o=new WeakMap,Al=new WeakMap,rf=new WeakMap,af=new WeakMap,bd=new WeakMap,Nl=new WeakMap,vd=new WeakMap,La=new WeakMap,Pl=new WeakMap,Ol=new WeakMap,Rl=new WeakMap,gd=new WeakMap,Kn=new WeakSet,Ak=function(){wt(this,Wr,this.CONNECTING),wt(this,La,new AbortController),De(this,af)(De(this,$o),Xi(this,Kn,DO).call(this)).then(De(this,Pk)).catch(De(this,Rk))},Pk=new WeakMap,Rk=new WeakMap,DO=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...De(this,vd)?{"Last-Event-ID":De(this,vd)}:void 0},cache:"no-store",signal:(t=De(this,La))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Nk=new WeakMap,Ok=new WeakMap,yd=function(t,e){var r;De(this,Wr)!==this.CLOSED&&wt(this,Wr,this.CLOSED);let n=new nf("error",{code:e,message:t});(r=De(this,Ol))==null||r.call(this,n),this.dispatchEvent(n)},Dk=function(t,e){var r;if(De(this,Wr)===this.CLOSED)return;wt(this,Wr,this.CONNECTING);let n=new nf("error",{code:e,message:t});(r=De(this,Ol))==null||r.call(this,n),this.dispatchEvent(n),wt(this,Nl,setTimeout(De(this,Mk),De(this,bd)))},Mk=new WeakMap,Lo.CONNECTING=0,Lo.OPEN=1,Lo.CLOSED=2;function C9(){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 Lk=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},of=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=Xh(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new Rr("No auth provider");let r;try{r=await Ji(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 Rr;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=Cl((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((a,o)=>{this._eventSource=new Lo(this._url.href,{...this._eventSourceInit,fetch:async(s,l)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let u=await i(s,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:m}=Il(u);this._resourceMetadataUrl=d,this._scope=m}return u}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{var l;if(s.code===401&&this._authProvider){this._authThenStart().then(a,o);return}let c=new Lk(s.code,s.message,s);o(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{var l;let c=s;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){o(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}a()}),this._eventSource.onmessage=s=>{var l,c;let u=s,d;try{d=Js.parse(JSON.parse(u.data))}catch(m){(l=this.onerror)===null||l===void 0||l.call(this,m);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 Rr("No auth provider");if(await Ji(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rr("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,a;if(!this._endpoint)throw new Error("Not connected");try{let o=await this._commonHeaders();o.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:o,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,s);if(!l.ok){let c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Il(l);if(this._resourceMetadataUrl=u,this._scope=d,await Ji(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rr;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(o){throw(a=this.onerror)===null||a===void 0||a.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}};var Yi={name:"@intelliweave/embedded",version:"2.0.71",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var Ht=new Re("MCPKnowledgeClient"),sf=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(){Ht.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new nd({name:Yi.name,version:Yi.version}),n=new tf(new URL(this.config.baseURL));return await r.connect(n),Ht.debug("Connected with HTTP streaming mode"),r}).catch(async r=>{let n=new nd({name:Yi.name,version:Yi.version}),i=new of(new URL(this.config.baseURL));return await n.connect(i),Ht.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=r=>{Ht.error(`MCP client error: ${r.message}`)},e.onclose=()=>{Ht.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(Gv,r=>{r.params.level=="critical"?Ht.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?Ht.error(`[Server] ${r.params.data}`):r.params.level=="error"?Ht.error(`[Server] ${r.params.data}`):r.params.level=="warning"?Ht.warn(`[Server] ${r.params.data}`):r.params.level=="info"?Ht.info(`[Server] ${r.params.data}`):r.params.level=="debug"?Ht.debug(`[Server] ${r.params.data}`):Ht.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Uv,r=>{Ht.debug("Tool list changed",r),this.fetchTools()}),Ht.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 a of i.tools||[])e.push(a);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let a=!!(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:o=>this.performToolCall(i.name,o),disabled:a})}Ht.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,Ht.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(a=>a.name==this.config.searchToolName);if(!n)return Ht.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let a=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[a]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let a=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[a]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let a=0;a<i.length;a++){let o=i[a];r.push({id:this.config.id+":"+this.config.searchToolName+":"+a,name:`Search result ${a+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}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(),Ht.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 Ht.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 A9=new Re("Statistics"),_d=[];async function Nr(t,e){let r={...e,event_id:_t(),event_date:new Date().toISOString(),sdk_version:Yi.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(_d.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),_d.length===0))return;let n=_d.slice();_d.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){A9.warn("Failed to submit analytics event:",i),_d.push(...n);return}}var zo=new Re("KnowledgeBase"),zk=1,lf=class t{constructor(e){this._sources=[{id:"core.internal",query:async()=>PT(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.${zk++}`),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 ht().knowledgeBaseSources&&(e=e.concat(ht().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(r=>!r.disabled),e}async search(e){let r=Date.now();zo.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 a=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),d=await c.query(e);return zo.debug(`Source '${c.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return zo.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();a=a.concat(n.entries),a=a.concat(this.manualEntries),ht().knowledgeBase&&(a=a.concat(ht().knowledgeBase)),a=a.filter(c=>c&&!c.disabled);for(let c=0;c<a.length;c++){let u=a[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!u.action&&u.type=="tour"&&(u.action=d=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!u.action&&u.type=="info"&&(u.action=d=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new AT({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(a);let l=o.search(e).map(c=>a.find(u=>u.id==c.id));for(let c of a)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Nr(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),zo.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${zk++}`),zo.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],a=!0,o=async(l,c)=>{zo.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 m=await d.json();return s(m.updateItems||[]),m.response},s=l=>{for(let c of l){if(!c.id){zo.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=>o(c,d)})}};this.registerSource(r,async l=>{if(a&&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 a=!d.noCache,i.includes(l)||i.push(l),s(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.${zk++}`);let r=new sf(e);return this.registerSource(e.id,n=>r.search(n)),r}};var cf=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
3315
3315
|
|
|
3316
3316
|
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}
|
|
3317
3317
|
|
package/dist/webpack/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import{v4 as Xe}from"uuid";function ve(r){let i=(r||"").split(`
|
|
|
6
6
|
`);for(let d of l){n=d.indexOf(": ");let c=d.slice(0,n),u=d.slice(n+2);n==-1&&(c=d,u=""),c&&(a[c]!==void 0?a[c]+=`
|
|
7
7
|
`+u:a[c]=u)}yield a}},t=new TextDecoder,s=r.getReader();for(;;){let{done:n,value:o}=await s.read();if(n)break;i+=t.decode(o,{stream:!0}),yield*e()}i+=t.decode()+`
|
|
8
8
|
|
|
9
|
-
`,yield*e()}function Ee(){if(p().userID)return p().userID||"";if(typeof localStorage<"u"){let r=localStorage.getItem("intelliweave.uid")||"";return r||(r=Xe(),localStorage.setItem("intelliweave.uid",r),r)}else return Xe()}function Re(r){let i=r;if(i?.type=="object"&&i.properties)return r;let e={type:"object",properties:{},required:[]};if(r&&Array.isArray(r)){let t=r;for(let s of t)e.properties[s.name]={type:s.type||"string",description:s.description||""}}return e}var O=class O{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return O.debug?!0:typeof window<"u"&&p().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...s)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...s)}};O.debug=!1;var m=O;var X=new m("ONNXModel"),S=class r{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,X.debug(`Model input parameters: ${i.inputNames.join(", ")}`),X.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!r.lib}static async load(i){if(!r.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(X.debug("Loading ONNX runtime"),this.onnx=await r.lib()),X.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new r(e)}makeTensor(i,e,t=0){let s=1;for(let o of e)s*=o;let n;if(i=="float32")n=new r.onnx.Tensor(new Float32Array(s),e);else if(i=="int8")n=new r.onnx.Tensor(new Int8Array(s),e);else if(i=="int16")n=new r.onnx.Tensor(new Int16Array(s),e);else if(i=="int32")n=new r.onnx.Tensor(new Int32Array(s),e);else if(i=="int64")n=new r.onnx.Tensor(new BigInt64Array(s),e);else if(i=="uint8")n=new r.onnx.Tensor(new Uint8Array(s),e);else if(i=="uint16")n=new r.onnx.Tensor(new Uint16Array(s),e);else if(i=="uint32")n=new r.onnx.Tensor(new Uint32Array(s),e);else if(i=="uint64")n=new r.onnx.Tensor(new BigUint64Array(s),e);else throw new Error(`Invalid type: ${i}`);return t!==0&&(i=="int64"||i=="uint64")?n.data.fill(BigInt(t)):t!==0&&n.data.fill(t),n}registerConstant(i,e){if(!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);return this.constantTensors[i]=e,e}makeConstant(i,e,t,s=0){return this.registerConstant(i,this.makeTensor(e,t,s))}registerState(i,e,t){if(e||(e=i),!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[i]={outputName:e,tensor:t},t}makeState(i,e,t,s,n=0){return this.registerState(i,e,this.makeTensor(t,s,n))}async run(i={}){if(this._runActive&&this.ignoreIfBusy)return X.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)i[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)i[e]=this.constantTensors[e];try{let e=await this.session.run(i);for(let t in this.stateTensors){let s=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=s}return e}finally{this._runActive=!1}}resetState(){X.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var Ve="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpc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y5jaHVua1Bvc2l0aW9uXTtyZXR1cm4gdGhpcy5jaHVua1Bvc2l0aW9uKyssdGhpcy5jaHVua1Bvc2l0aW9uPHRoaXMuY2h1bmtzWzBdLmxlbmd0aHx8KHRoaXMuY2h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var qe=new m("PCMPlayerNode"),T=class extends AudioWorkletNode{constructor(e,t,s){super(e,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!s||s!="int16"&&s!="float32")throw new Error(`Invalid format: ${s}`);this.sampleRate=t,this.format=s,this.port.onmessage=n=>this.onWorkletMessage(n),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:s})}static async registerModule(e){await e.audioWorklet.addModule(Ve)}feed(e){this.port.postMessage({action:"data",buffer:e.buffer},[e.buffer])}async play(e){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(t=>this._playPromiseResolve=t),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:e}}));try{let t=e.getReader();for(;!this.isCancelled;){let{done:s,value:n}=await t.read();if(s||!n)break;this.feed(n)}}catch(t){qe.warn("Stream error:",t),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:e,error:t}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(e){e.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var J=new m("SpeechOutput"),Le=.5,et=.8,H=class extends EventTarget{constructor(e){super();this.maxVolumeHeard=0;this.ai=e,this.ai.addEventListener("output",t=>this.onTextOutputFromAI(t)),this.ai.audio?.speechRecognition.addEventListener("speechstart",t=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(e){e.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(e.detail.message)}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let s of this.analyserBuffer)e+=s*s;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}async speak(e){if(!this.ai?.config?.voice?.providerID)return J.warn("No voice provider configured");let t=`speech-${tt++}`;await this.ai.audio.beginAccess(t);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(t)}}async _speakWithLock(e){let t=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:e}});if(this.dispatchEvent(t),e=t.detail.message,t.defaultPrevented||!e)return;this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=et);let s=this.ai?._voiceTracker||J.timer(`${this.ai.config.voice.providerID} voice`);s(`Speak: ${e}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let n=new T(this.ai.audio.context,24e3,"int16");this.currentPlayer=n,n.connect(this.analyserNode),n.addEventListener("end",a=>{let l=a;s(`PCM stream ${l.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==n&&!l.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let o;if(this.ai.config.voice.providerID=="openai")o=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:e,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")o=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:e})});else{J.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(s(`Received response ${o.status} ${o.statusText}`),!o.ok){J.warn(`Failed to generate voice sample: ${o.status} ${o.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),s("Playing PCM stream"),await n.play(o.body),s("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let e=this.currentPlayerVolume,t=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Le);let s=400;e.gain.linearRampToValueAtTime(0,s/1e3),await new Promise(n=>setTimeout(n,s+250)),e.disconnect(),t?.stop(),t?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Le)}},tt=1;function U(r,i){let e=i.reduce((l,d)=>l+d.byteLength,0),t=new DataView(new ArrayBuffer(44));t.setUint8(0,82),t.setUint8(1,73),t.setUint8(2,70),t.setUint8(3,70),t.setUint32(4,44+e,!0),t.setUint8(8,87),t.setUint8(9,65),t.setUint8(10,86),t.setUint8(11,69);let s=1,n=32,o=s*n/8,a=r*o;return t.setUint8(12,102),t.setUint8(13,109),t.setUint8(14,116),t.setUint8(15,32),t.setUint32(16,16,!0),t.setUint16(20,3,!0),t.setUint16(22,s,!0),t.setUint32(24,r,!0),t.setUint32(28,a,!0),t.setUint16(32,o,!0),t.setUint16(34,n,!0),t.setUint8(36,100),t.setUint8(37,97),t.setUint8(38,116),t.setUint8(39,97),t.setUint32(40,e,!0),new File([t,...i],"audio.wav",{type:"audio/wav"})}var Be="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pd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hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var E=class extends AudioWorkletNode{constructor(e,t,s,n){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=s;let o=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!o.includes(s))throw new Error(`Invalid format ${s}, must be one of: ${o.join(", ")}`);if(!n||n<=0)throw new Error(`Invalid buffer size: ${n}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:s,bufferSize:n})}static async registerModule(e){await e.audioWorklet.addModule(Be)}onWorkletMessage(e){if(e.data.action=="data"){let t=null;if(this.format=="int16"&&(t=new Int16Array(e.data.buffer)),this.format=="int64"&&(t=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(t=new Float32Array(e.data.buffer)),!t)throw new Error(`Invalid format: ${this.format}`);this.onData(t),this.dispatchEvent(new CustomEvent("data",{detail:{data:t}}))}}onData(e){}};var we=16e3,j=256,R=8,_=new m("VoiceDetectionNode"),D=class D extends E{constructor(e){super(e,we,"float32",j*R);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!D.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return we}get numberOfSamples(){return j}get numberOfSampleChunks(){return R}get outputBufferSize(){return j*R}get isModelLoaded(){return!!this.vad}async loadModel(){_.debug("Loading VAD model"),this.vad=await S.load(D.vadModelURL),this.vad.ignoreIfBusy=!0,_.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],we),this.vad.makeState("h","hn","float32",[2,R,64]),this.vad.makeState("c","cn","float32",[2,R,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new S.onnx.Tensor(e,[R,j])});if(!t)return;this.currentProbability=0;for(let o=0;o<t.output.data.length;o++)t.output.data[o]>this.currentProbability&&(this.currentProbability=t.output.data[o]);let s=this.isVoiceActive?this.sentivityEnd:this.sensitivity,n=this.currentProbability>s;if(!n&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=n,n&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),_.debug("Started speaking")):n?this.lastVoiceActiveDate=Date.now():!n&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!n&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),_.debug("Stopped speaking after timeout")),!n){let o=Date.now();o>this.nextVadReset&&(this.nextVadReset=o+5e3,this.vad.resetState())}}catch(t){_.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};D.vadModelURL="";var V=D;var Pe=new m("VoiceChunkOutputNode"),L=class extends V{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((e,t)=>e+t.length,0)/8e3}async onData(e){if(await super.onData(e),this.isVoiceActive&&!this._voiceRecording){Pe.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let t of this.buffers)this.recordedBuffers.push(t),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:t,isFinal:!1}})),this.onVoiceChunk(t);this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!0}})),this.onVoiceChunk(e),this._voiceRecording=!1;let t=this.recordedBuffers.reduce((s,n)=>s+n.length,0);Pe.debug(`Voice complete, recorded ${(t/8e3).toFixed(2)} seconds of audio, ${t*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(e);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(e){}onVoiceEnd(e){}};var $=new m("OpenAITranscriptionNode"),Q=class extends L{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=$.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=U(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let n="";try{let o=new FormData;o.append("file",s),o.append("model","whisper-1"),o.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);t("Response received"),n=await a.text(),t("Content received: "+n),this.lastRequestAbortController=void 0}catch(o){$.error(`Failed to transcribe speech: ${o.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return $.debug("Transcription complete, but no text was found");$.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var q=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var x=new m("IntelliWeaveTranscriptionNode"),st="wss://speech.intelliweave.ai/api/v1/transcribe",te=class te extends L{constructor(e,t){super(e);this.apiAddress=st;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(x.debug("Opening WebSocket connection"),this.ws=new q(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(e.buffer),this.ws.onopen=()=>{x.debug("WebSocket connection opened")},this.ws.addEventListener("message",s=>{let n=JSON.parse(s.data);if(n.error)return x.warn("Error: "+n.error);if(n.type!="transcription")return x.warn("Invalid response type",n);if(n.streaming&&!n.final)return x.debug("Partial transcription: "+n.partialText);if(this.isTranscribing=!1,!n.text.trim())return x.warn(`Empty transcription (${n.processingTime}ms)`);x.debug(`Transcription: ${n.text} (${n.processingTime}ms)`),this.onVoiceTranscription(n.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",s=>x.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{x.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),te.debugExportWav){let t=U(this.sampleRate,e),s=document.createElement("a");s.href=URL.createObjectURL(t),s.download="recording.wav",s.click()}}onVoiceTranscription(e){}onSocketClose(){x.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};te.debugExportWav=!1;var ee=te;var G={name:"@intelliweave/embedded",version:"2.0.70",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{v4 as ot}from"uuid";var at=new m("Statistics"),K=[];async function f(r,i){let e={...i,event_id:ot(),event_date:new Date().toISOString(),sdk_version:G.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(K.push(e),!r||(await new Promise(s=>setTimeout(s,5e3)),K.length===0))return;let t=K.slice();K.length=0;try{let s=await fetch(r.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){at.warn("Failed to submit analytics event:",s),K.push(...t);return}}var xe=new m("SpeechRecognition"),ie=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e,this.ai.knowledgeBase.registerSource(()=>[{id:"system.microphone.enable",type:"action",name:"Enable or disable microphone",isContext:!0,content:`Starts or stops listening to input from the user through the microphone. ${this.isRunning?"Microphone access is currently enabled and you can hear the user.":"Microphone access is currently disabled."}.`,parameters:[{name:"enable",type:"boolean",description:"If true, enables the microphone. If false, disables it."}],action:async t=>{t.enable?await this.start():this.stop()}}])}get isSupported(){if(!S.lib||!this.ai?.vadModel||!C().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let e=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,e.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),V.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new Q(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new ee(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",t=>{this.ai._voiceTracker=xe.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),f(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("speechend",t=>{this.ai._voiceTracker?.("Speech ended");let s=this.recordingStartTime?Date.now()-this.recordingStartTime:0;f(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:s}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),f(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:t.detail.confidence||void 0}}),this.onTranscription(t)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){xe.error("Failed to start speech recognition:",e),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(e=>e.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let s of this.analyserBuffer)e+=s*s;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(e){let t=e.detail.text;xe.debug("Heard:",t),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:t,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(e){throw this._skipEvents=!1,e}}}};var se=new m("AudioSystem"),M=class r{constructor(i){this.locks=[];if(!i)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=i,this.ai.audio=this,this.speechRecognition=new ie(this.ai),this.speechOutput=new H(this.ai)}static get isSupported(){return!(!S.lib||!C().AudioWorkletNode)}static async registerModules(i){await Promise.all([T.registerModule(i),E.registerModule(i)])}async beginAccess(i){se.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(se.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await r.registerModules(this.context))}endAccess(i){se.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(se.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var Ae=class{constructor(i,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!i)throw new Error(`Invalid array class: ${i}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=i,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((i,e)=>i+e.length,0)}feed(i){this.partialBuffers.push(i)}get canDrain(){return this.partialBuffers.reduce((e,t)=>e+t.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let i=this.ArrayClass,e=new i(this.outputBufferSize),t=0;for(;t!=e.length;){if(t>e.length)throw new Error(`Buffer overflow: ${t} > ${e.length}`);let s=e.length-t,n=this.partialBuffers[0],o=n.length-this.partialBufferOffset;o<s?(e.set(n.subarray(this.partialBufferOffset),t),t+=o,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(n.subarray(this.partialBufferOffset,this.partialBufferOffset+s),t),t+=s,this.partialBufferOffset+=s)}return e}pad(){let i=this.queuedSize%this.outputBufferSize;if(i==0)return;let e=this.ArrayClass,t=new e(i);this.feed(t)}};var Ne=class{constructor(i,e,t,s){if(!i||!e||!t)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=i,this.toSampleRate=e,this.channels=t||0,this.inputBufferSize=s,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=i=>i,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(i){try{return this.outputBuffer.subarray(0,i)}catch{try{return this.outputBuffer.length=i,this.outputBuffer}catch{return this.outputBuffer.slice(0,i)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=i=>{let e=i.length,t=this.channels,s,n,o,a,l,d,c,u,h;if(e%t!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,n=this.ratioWeight,o=this.lastWeight,a=0,l=0,d=0,c=0,u=this.outputBuffer;o<1;o+=n)for(l=o%1,a=1-l,this.lastWeight=o%1,h=0;h<this.channels;++h)u[c++]=this.lastOutput[h]*a+i[h]*l;for(o-=1,e-=t,d=Math.floor(o)*t;c<s&&d<e;){for(l=o%1,a=1-l,h=0;h<this.channels;++h)u[c++]=i[d+(h>0?h:0)]*a+i[d+(t+h)]*l;o+=n,d=Math.floor(o)*t}for(h=0;h<t;++h)this.lastOutput[h]=i[d++];return this.bufferSlice(c)}}multiTap(){this.resampler=i=>{let e=i.length,t,s,n=this.channels,o,a,l,d,c,u,h,y,N;if(e%n!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(t=this.outputBufferSize,s=[],o=this.ratioWeight,a=0,d=0,c=0,u=!this.tailExists,this.tailExists=!1,h=this.outputBuffer,y=0,N=0,l=0;l<n;++l)s[l]=0;do{if(u)for(a=o,l=0;l<n;++l)s[l]=0;else{for(a=this.lastWeight,l=0;l<n;++l)s[l]=this.lastOutput[l];u=!0}for(;a>0&&d<e;)if(c=1+d-N,a>=c){for(l=0;l<n;++l)s[l]+=i[d++]*c;N=d,a-=c}else{for(l=0;l<n;++l)s[l]+=i[d+(l>0?l:0)]*a;N+=a,a=0;break}if(a===0)for(l=0;l<n;++l)h[y++]=s[l]/o;else{for(this.lastWeight=a,l=0;l<n;++l)this.lastOutput[l]=s[l];this.tailExists=!0;break}}while(d<e&&y<t);return this.bufferSlice(y)}}resample(i){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(i)}};function Ei(r){let i=r.length,e=new Int16Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,r[i]));e[i]=t<0?t*32768:t*32767}return e}function Ri(r){let i=r.length,e=new BigInt64Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,r[i]));e[i]=BigInt(Math.floor(t<0?t*32768:t*32767))*0x100000000000n}return e}function Vi(r){let i=r.length,e=new Float32Array(i);for(;i--;){let t=r[i];e[i]=t>=32768?-(65536-t)/32768:t/32767}return e}import{countTokens as lt}from"gpt-tokenizer";import{countTokens as ne}from"gpt-tokenizer";import{v4 as rt}from"uuid";var oe=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new Se;return e.id=i,this.groups.push(e),e}group(i){return this.groups.find(e=>e.id===i)}countTokens(){return this.groups.reduce((i,e)=>i+e.tokenCount,0)}removeOverflow(){let i=this.countTokens(),e=this.groups.reduce((t,s)=>t+s.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((n,o)=>{let a=Math.floor(n.weight/e*this.size),l=Math.floor(o.weight/e*this.size),d=n.tokenCount-a;return o.tokenCount-l-d}),s=this.removeOneItem(t);if(!s)throw new Error("Too many items in the token window that cannot be removed.");i-=s.tokenCount}}removeOneItem(i){for(let e of i){let t=e.items.findIndex(n=>!n.cannotRemove);if(t===-1)continue;let s=e.items[t];return e.items.splice(t,1),e.tokenCount-=s.tokenCount,s}return null}},Se=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
9
|
+
`,yield*e()}function Ee(){if(p().userID)return p().userID||"";if(typeof localStorage<"u"){let r=localStorage.getItem("intelliweave.uid")||"";return r||(r=Xe(),localStorage.setItem("intelliweave.uid",r),r)}else return Xe()}function Re(r){let i=r;if(i?.type=="object"&&i.properties)return r;let e={type:"object",properties:{},required:[]};if(r&&Array.isArray(r)){let t=r;for(let s of t)e.properties[s.name]={type:s.type||"string",description:s.description||""}}return e}var O=class O{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return O.debug?!0:typeof window<"u"&&p().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...s)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...s)}};O.debug=!1;var m=O;var X=new m("ONNXModel"),S=class r{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,X.debug(`Model input parameters: ${i.inputNames.join(", ")}`),X.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!r.lib}static async load(i){if(!r.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(X.debug("Loading ONNX runtime"),this.onnx=await r.lib()),X.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new r(e)}makeTensor(i,e,t=0){let s=1;for(let o of e)s*=o;let n;if(i=="float32")n=new r.onnx.Tensor(new Float32Array(s),e);else if(i=="int8")n=new r.onnx.Tensor(new Int8Array(s),e);else if(i=="int16")n=new r.onnx.Tensor(new Int16Array(s),e);else if(i=="int32")n=new r.onnx.Tensor(new Int32Array(s),e);else if(i=="int64")n=new r.onnx.Tensor(new BigInt64Array(s),e);else if(i=="uint8")n=new r.onnx.Tensor(new Uint8Array(s),e);else if(i=="uint16")n=new r.onnx.Tensor(new Uint16Array(s),e);else if(i=="uint32")n=new r.onnx.Tensor(new Uint32Array(s),e);else if(i=="uint64")n=new r.onnx.Tensor(new BigUint64Array(s),e);else throw new Error(`Invalid type: ${i}`);return t!==0&&(i=="int64"||i=="uint64")?n.data.fill(BigInt(t)):t!==0&&n.data.fill(t),n}registerConstant(i,e){if(!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);return this.constantTensors[i]=e,e}makeConstant(i,e,t,s=0){return this.registerConstant(i,this.makeTensor(e,t,s))}registerState(i,e,t){if(e||(e=i),!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[i]={outputName:e,tensor:t},t}makeState(i,e,t,s,n=0){return this.registerState(i,e,this.makeTensor(t,s,n))}async run(i={}){if(this._runActive&&this.ignoreIfBusy)return X.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)i[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)i[e]=this.constantTensors[e];try{let e=await this.session.run(i);for(let t in this.stateTensors){let s=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=s}return e}finally{this._runActive=!1}}resetState(){X.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var Ve="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHV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IEVycm9yKGBJbnZhbGlkIGZvcm1hdDogJHt0aGlzLmZvcm1hdH1gKTtsZXQgYT10aGlzLnJlc2FtcGxlci5yZXNhbXBsZShyKTt0aGlzLmNodW5rcy5wdXNoKGEpfW5leHRGbG9hdCgpe2lmKCF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIDA7bGV0IHQ9dGhpcy5jaHVua3NbMF1bdGhpcy5jaHVua1Bvc2l0aW9uXTtyZXR1cm4gdGhpcy5jaHVua1Bvc2l0aW9uKyssdGhpcy5jaHVua1Bvc2l0aW9uPHRoaXMuY2h1bmtzWzBdLmxlbmd0aHx8KHRoaXMuY2h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var qe=new m("PCMPlayerNode"),T=class extends AudioWorkletNode{constructor(e,t,s){super(e,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!s||s!="int16"&&s!="float32")throw new Error(`Invalid format: ${s}`);this.sampleRate=t,this.format=s,this.port.onmessage=n=>this.onWorkletMessage(n),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:s})}static async registerModule(e){await e.audioWorklet.addModule(Ve)}feed(e){this.port.postMessage({action:"data",buffer:e.buffer},[e.buffer])}async play(e){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(t=>this._playPromiseResolve=t),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:e}}));try{let t=e.getReader();for(;!this.isCancelled;){let{done:s,value:n}=await t.read();if(s||!n)break;this.feed(n)}}catch(t){qe.warn("Stream error:",t),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:e,error:t}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(e){e.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var J=new m("SpeechOutput"),Le=.5,et=.8,H=class extends EventTarget{constructor(e){super();this.maxVolumeHeard=0;this.ai=e,this.ai.addEventListener("output",t=>this.onTextOutputFromAI(t)),this.ai.audio?.speechRecognition.addEventListener("speechstart",t=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(e){e.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(e.detail.message)}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let s of this.analyserBuffer)e+=s*s;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}async speak(e){if(!this.ai?.config?.voice?.providerID)return J.warn("No voice provider configured");let t=`speech-${tt++}`;await this.ai.audio.beginAccess(t);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(t)}}async _speakWithLock(e){let t=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:e}});if(this.dispatchEvent(t),e=t.detail.message,t.defaultPrevented||!e)return;this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=et);let s=this.ai?._voiceTracker||J.timer(`${this.ai.config.voice.providerID} voice`);s(`Speak: ${e}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let n=new T(this.ai.audio.context,24e3,"int16");this.currentPlayer=n,n.connect(this.analyserNode),n.addEventListener("end",a=>{let l=a;s(`PCM stream ${l.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==n&&!l.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let o;if(this.ai.config.voice.providerID=="openai")o=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:e,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")o=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:e})});else{J.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(s(`Received response ${o.status} ${o.statusText}`),!o.ok){J.warn(`Failed to generate voice sample: ${o.status} ${o.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),s("Playing PCM stream"),await n.play(o.body),s("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let e=this.currentPlayerVolume,t=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Le);let s=400;e.gain.linearRampToValueAtTime(0,s/1e3),await new Promise(n=>setTimeout(n,s+250)),e.disconnect(),t?.stop(),t?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Le)}},tt=1;function U(r,i){let e=i.reduce((l,d)=>l+d.byteLength,0),t=new DataView(new ArrayBuffer(44));t.setUint8(0,82),t.setUint8(1,73),t.setUint8(2,70),t.setUint8(3,70),t.setUint32(4,44+e,!0),t.setUint8(8,87),t.setUint8(9,65),t.setUint8(10,86),t.setUint8(11,69);let s=1,n=32,o=s*n/8,a=r*o;return t.setUint8(12,102),t.setUint8(13,109),t.setUint8(14,116),t.setUint8(15,32),t.setUint32(16,16,!0),t.setUint16(20,3,!0),t.setUint16(22,s,!0),t.setUint32(24,r,!0),t.setUint32(28,a,!0),t.setUint16(32,o,!0),t.setUint16(34,n,!0),t.setUint8(36,100),t.setUint8(37,97),t.setUint8(38,116),t.setUint8(39,97),t.setUint32(40,e,!0),new File([t,...i],"audio.wav",{type:"audio/wav"})}var Be="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0d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aW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var E=class extends AudioWorkletNode{constructor(e,t,s,n){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=s;let o=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!o.includes(s))throw new Error(`Invalid format ${s}, must be one of: ${o.join(", ")}`);if(!n||n<=0)throw new Error(`Invalid buffer size: ${n}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:s,bufferSize:n})}static async registerModule(e){await e.audioWorklet.addModule(Be)}onWorkletMessage(e){if(e.data.action=="data"){let t=null;if(this.format=="int16"&&(t=new Int16Array(e.data.buffer)),this.format=="int64"&&(t=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(t=new Float32Array(e.data.buffer)),!t)throw new Error(`Invalid format: ${this.format}`);this.onData(t),this.dispatchEvent(new CustomEvent("data",{detail:{data:t}}))}}onData(e){}};var we=16e3,j=256,R=8,_=new m("VoiceDetectionNode"),D=class D extends E{constructor(e){super(e,we,"float32",j*R);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!D.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return we}get numberOfSamples(){return j}get numberOfSampleChunks(){return R}get outputBufferSize(){return j*R}get isModelLoaded(){return!!this.vad}async loadModel(){_.debug("Loading VAD model"),this.vad=await S.load(D.vadModelURL),this.vad.ignoreIfBusy=!0,_.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],we),this.vad.makeState("h","hn","float32",[2,R,64]),this.vad.makeState("c","cn","float32",[2,R,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new S.onnx.Tensor(e,[R,j])});if(!t)return;this.currentProbability=0;for(let o=0;o<t.output.data.length;o++)t.output.data[o]>this.currentProbability&&(this.currentProbability=t.output.data[o]);let s=this.isVoiceActive?this.sentivityEnd:this.sensitivity,n=this.currentProbability>s;if(!n&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=n,n&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),_.debug("Started speaking")):n?this.lastVoiceActiveDate=Date.now():!n&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!n&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),_.debug("Stopped speaking after timeout")),!n){let o=Date.now();o>this.nextVadReset&&(this.nextVadReset=o+5e3,this.vad.resetState())}}catch(t){_.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};D.vadModelURL="";var V=D;var Pe=new m("VoiceChunkOutputNode"),L=class extends V{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((e,t)=>e+t.length,0)/8e3}async onData(e){if(await super.onData(e),this.isVoiceActive&&!this._voiceRecording){Pe.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let t of this.buffers)this.recordedBuffers.push(t),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:t,isFinal:!1}})),this.onVoiceChunk(t);this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!0}})),this.onVoiceChunk(e),this._voiceRecording=!1;let t=this.recordedBuffers.reduce((s,n)=>s+n.length,0);Pe.debug(`Voice complete, recorded ${(t/8e3).toFixed(2)} seconds of audio, ${t*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(e);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(e){}onVoiceEnd(e){}};var $=new m("OpenAITranscriptionNode"),Q=class extends L{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=$.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=U(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let n="";try{let o=new FormData;o.append("file",s),o.append("model","whisper-1"),o.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);t("Response received"),n=await a.text(),t("Content received: "+n),this.lastRequestAbortController=void 0}catch(o){$.error(`Failed to transcribe speech: ${o.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return $.debug("Transcription complete, but no text was found");$.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var q=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var x=new m("IntelliWeaveTranscriptionNode"),st="wss://speech.intelliweave.ai/api/v1/transcribe",te=class te extends L{constructor(e,t){super(e);this.apiAddress=st;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(x.debug("Opening WebSocket connection"),this.ws=new q(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(e.buffer),this.ws.onopen=()=>{x.debug("WebSocket connection opened")},this.ws.addEventListener("message",s=>{let n=JSON.parse(s.data);if(n.error)return x.warn("Error: "+n.error);if(n.type!="transcription")return x.warn("Invalid response type",n);if(n.streaming&&!n.final)return x.debug("Partial transcription: "+n.partialText);if(this.isTranscribing=!1,!n.text.trim())return x.warn(`Empty transcription (${n.processingTime}ms)`);x.debug(`Transcription: ${n.text} (${n.processingTime}ms)`),this.onVoiceTranscription(n.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",s=>x.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{x.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),te.debugExportWav){let t=U(this.sampleRate,e),s=document.createElement("a");s.href=URL.createObjectURL(t),s.download="recording.wav",s.click()}}onVoiceTranscription(e){}onSocketClose(){x.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};te.debugExportWav=!1;var ee=te;var G={name:"@intelliweave/embedded",version:"2.0.71",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{v4 as ot}from"uuid";var at=new m("Statistics"),K=[];async function f(r,i){let e={...i,event_id:ot(),event_date:new Date().toISOString(),sdk_version:G.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(K.push(e),!r||(await new Promise(s=>setTimeout(s,5e3)),K.length===0))return;let t=K.slice();K.length=0;try{let s=await fetch(r.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){at.warn("Failed to submit analytics event:",s),K.push(...t);return}}var xe=new m("SpeechRecognition"),ie=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e,this.ai.knowledgeBase.registerSource(()=>[{id:"system.microphone.enable",type:"action",name:"Enable or disable microphone",isContext:!0,content:`Starts or stops listening to input from the user through the microphone. ${this.isRunning?"Microphone access is currently enabled and you can hear the user.":"Microphone access is currently disabled."}.`,parameters:[{name:"enable",type:"boolean",description:"If true, enables the microphone. If false, disables it."}],action:async t=>{t.enable?await this.start():this.stop()}}])}get isSupported(){if(!S.lib||!this.ai?.vadModel||!C().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let e=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,e.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),V.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new Q(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new ee(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",t=>{this.ai._voiceTracker=xe.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),f(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("speechend",t=>{this.ai._voiceTracker?.("Speech ended");let s=this.recordingStartTime?Date.now()-this.recordingStartTime:0;f(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:s}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),f(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:t.detail.confidence||void 0}}),this.onTranscription(t)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){xe.error("Failed to start speech recognition:",e),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(e=>e.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let s of this.analyserBuffer)e+=s*s;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(e){let t=e.detail.text;xe.debug("Heard:",t),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:t,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(e){throw this._skipEvents=!1,e}}}};var se=new m("AudioSystem"),M=class r{constructor(i){this.locks=[];if(!i)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=i,this.ai.audio=this,this.speechRecognition=new ie(this.ai),this.speechOutput=new H(this.ai)}static get isSupported(){return!(!S.lib||!C().AudioWorkletNode)}static async registerModules(i){await Promise.all([T.registerModule(i),E.registerModule(i)])}async beginAccess(i){se.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(se.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await r.registerModules(this.context))}endAccess(i){se.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(se.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var Ae=class{constructor(i,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!i)throw new Error(`Invalid array class: ${i}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=i,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((i,e)=>i+e.length,0)}feed(i){this.partialBuffers.push(i)}get canDrain(){return this.partialBuffers.reduce((e,t)=>e+t.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let i=this.ArrayClass,e=new i(this.outputBufferSize),t=0;for(;t!=e.length;){if(t>e.length)throw new Error(`Buffer overflow: ${t} > ${e.length}`);let s=e.length-t,n=this.partialBuffers[0],o=n.length-this.partialBufferOffset;o<s?(e.set(n.subarray(this.partialBufferOffset),t),t+=o,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(n.subarray(this.partialBufferOffset,this.partialBufferOffset+s),t),t+=s,this.partialBufferOffset+=s)}return e}pad(){let i=this.queuedSize%this.outputBufferSize;if(i==0)return;let e=this.ArrayClass,t=new e(i);this.feed(t)}};var Ne=class{constructor(i,e,t,s){if(!i||!e||!t)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=i,this.toSampleRate=e,this.channels=t||0,this.inputBufferSize=s,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=i=>i,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(i){try{return this.outputBuffer.subarray(0,i)}catch{try{return this.outputBuffer.length=i,this.outputBuffer}catch{return this.outputBuffer.slice(0,i)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=i=>{let e=i.length,t=this.channels,s,n,o,a,l,d,c,u,h;if(e%t!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,n=this.ratioWeight,o=this.lastWeight,a=0,l=0,d=0,c=0,u=this.outputBuffer;o<1;o+=n)for(l=o%1,a=1-l,this.lastWeight=o%1,h=0;h<this.channels;++h)u[c++]=this.lastOutput[h]*a+i[h]*l;for(o-=1,e-=t,d=Math.floor(o)*t;c<s&&d<e;){for(l=o%1,a=1-l,h=0;h<this.channels;++h)u[c++]=i[d+(h>0?h:0)]*a+i[d+(t+h)]*l;o+=n,d=Math.floor(o)*t}for(h=0;h<t;++h)this.lastOutput[h]=i[d++];return this.bufferSlice(c)}}multiTap(){this.resampler=i=>{let e=i.length,t,s,n=this.channels,o,a,l,d,c,u,h,y,N;if(e%n!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(t=this.outputBufferSize,s=[],o=this.ratioWeight,a=0,d=0,c=0,u=!this.tailExists,this.tailExists=!1,h=this.outputBuffer,y=0,N=0,l=0;l<n;++l)s[l]=0;do{if(u)for(a=o,l=0;l<n;++l)s[l]=0;else{for(a=this.lastWeight,l=0;l<n;++l)s[l]=this.lastOutput[l];u=!0}for(;a>0&&d<e;)if(c=1+d-N,a>=c){for(l=0;l<n;++l)s[l]+=i[d++]*c;N=d,a-=c}else{for(l=0;l<n;++l)s[l]+=i[d+(l>0?l:0)]*a;N+=a,a=0;break}if(a===0)for(l=0;l<n;++l)h[y++]=s[l]/o;else{for(this.lastWeight=a,l=0;l<n;++l)this.lastOutput[l]=s[l];this.tailExists=!0;break}}while(d<e&&y<t);return this.bufferSlice(y)}}resample(i){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(i)}};function Ei(r){let i=r.length,e=new Int16Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,r[i]));e[i]=t<0?t*32768:t*32767}return e}function Ri(r){let i=r.length,e=new BigInt64Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,r[i]));e[i]=BigInt(Math.floor(t<0?t*32768:t*32767))*0x100000000000n}return e}function Vi(r){let i=r.length,e=new Float32Array(i);for(;i--;){let t=r[i];e[i]=t>=32768?-(65536-t)/32768:t/32767}return e}import{countTokens as lt}from"gpt-tokenizer";import{countTokens as ne}from"gpt-tokenizer";import{v4 as rt}from"uuid";var oe=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new Se;return e.id=i,this.groups.push(e),e}group(i){return this.groups.find(e=>e.id===i)}countTokens(){return this.groups.reduce((i,e)=>i+e.tokenCount,0)}removeOverflow(){let i=this.countTokens(),e=this.groups.reduce((t,s)=>t+s.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((n,o)=>{let a=Math.floor(n.weight/e*this.size),l=Math.floor(o.weight/e*this.size),d=n.tokenCount-a;return o.tokenCount-l-d}),s=this.removeOneItem(t);if(!s)throw new Error("Too many items in the token window that cannot be removed.");i-=s.tokenCount}}removeOneItem(i){for(let e of i){let t=e.items.findIndex(n=>!n.cannotRemove);if(t===-1)continue;let s=e.items[t];return e.items.splice(t,1),e.tokenCount-=s.tokenCount,s}return null}},Se=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
10
10
|
`;this.itemPadding=0;this.sortFunction=(i,e)=>i.sortOrder!==e.sortOrder?i.sortOrder-e.sortOrder:i.dateAdded!==e.dateAdded?i.dateAdded-e.dateAdded:i.content.localeCompare(e.content)}setItemPadding(i){return this.itemPadding=i,this.recalculateTokens(),this}sortBy(i){return this.sortFunction=i,this.items.sort(this.sortFunction),this}setSeparator(i){return this.separator==i?this:(this.separator=i,this.recalculateTokens(),this)}setWeight(i){return this.weight=i,this}recalculateTokens(){this.tokenCount=this.items.reduce((i,e)=>(e.tokenCount=ne(e.content)+ne(this.separator)+this.itemPadding,i+e.tokenCount),0)}add(i){typeof i=="string"&&(i={content:i});let e=i;e.id===void 0&&(e.id=rt());let t=this.items.find(s=>s.id===e.id);return t?(this.tokenCount-=t.tokenCount,Object.assign(t,e),e=t):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.tokenCount=e.disabled?0:ne(i.content)+ne(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}getAllAsString(){return this.getAll().map(i=>i.content).join(this.separator)}getAll(){return this.items.filter(i=>!i.disabled)}empty(){this.items=[],this.tokenCount=0}};var B=class{constructor(i){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let i=new oe;return i.createGroup("context").setSeparator(`
|
|
11
11
|
|
|
12
12
|
`),i.createGroup("actions").setItemPadding(25),i.createGroup("messages").setItemPadding(10),i})();this.config=i,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(i){throw new Error("Not implemented")}addUserMessage(i){throw new Error("Not implemented")}addAssistantMessage(i){throw new Error("Not implemented")}onBeforeIncomingMessage(i){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(i){return this.toolGroup.add({id:i.name,customData:i,cannotRemove:i.isContext,sortOrder:101,disabled:i.disabled,content:JSON.stringify(i)})}};import{v4 as P}from"uuid";var Z=new m("ChatGPT"),ae=class extends B{async sendMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(e),customData:e}),await this.processMessages();let s=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return s?.role=="assistant"&&s.content||""}addAssistantMessage(i){let e={role:"assistant",content:i};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(e),customData:e})}addUserMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(i=>i.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),Z.debugEnabled&&Z.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(t=>t.customData),messages:this.messageGroup.items.map(t=>t.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let t of e.tool_calls)await this.processToolCall(t);await this.processMessages()}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendRequest(i){let e={};return e["Content-Type"]="application/json",this.config.apiKey&&(e.Authorization=`Bearer ${this.config.apiKey}`),await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:e,body:JSON.stringify(i)})}async sendToAPI(i){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let a=this.messageGroup.items.length-1;a>=0;a--){let l=this.messageGroup.items[a].customData;if(l.role=="assistant"&&l.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(l.role=="user")break}Z.debugEnabled&&Z.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(a=>a.customData),messages:this.messageGroup.items.map(a=>a.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(a=>a.customData)]};for(let a of this.toolGroup.getAll()){let l=a.customData;l.description&&l.description.length>1024&&Z.warn(`Tool description for "${l.name}" is too long, it will be truncated.`);let d={type:"function",function:{name:l.name,description:(l.description||"").substring(0,1024),parameters:l.params}};t.tools.push(d)}if(t.user||delete t.user,t.tools.length||delete t.tools,i)return t;let s=await this.sendRequest(t);if(!s.ok){let a=`${s.status} ${s.statusText}`;try{let d=await s.json();a=d.errorText||d.error?.message||d.error||a}catch{}let l=new Error(a);throw l.code=s.status,l}let n=null,o=null;if(this.config.stream){for await(let l of Te(s.body)){if(l.data=="[DONE]")break;if(!l.data)continue;let d=JSON.parse(l.data);if(o){for(let c in d.choices[0].delta)if(typeof d.choices[0].delta[c]=="string"){if(c=="role"&&o[c]==d.choices[0].delta[c])continue;o[c]=(o[c]||"")+d.choices[0].delta[c]}for(let c of d.choices[0].delta.tool_calls||[]){if(o.tool_calls||(o.tool_calls=[]),!o.tool_calls[c.index]){o.tool_calls[c.index]=c;continue}let u=o.tool_calls[c.index];u.function=u.function||{},u.function.name=(u.function.name||"")+(c.function?.name||""),u.function.arguments=(u.function.arguments||"")+(c.function?.arguments||"")}}else o={chunkID:d.id,...d.choices[0].delta};o?.content&&!o.content.startsWith("{")&&this.config.onAIMessage?.(o.content,!0)}let a=lt(JSON.stringify(t)+JSON.stringify(o)||"");this.stats.tokensUsed+=a,Z.debug(`Estimated ${a} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else n=await s.json(),this.stats.tokensUsed+=n?.usage?.total_tokens||0,Z.debug(`Used ${n?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),o=n?.choices?.[0]?.message;if(o||(Z.warn("No response block in API response."),o={role:"assistant",content:""}),o.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(o),this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(o),customData:o}),o.content&&this.config.onAIMessage?.(o.content,!1)}async processToolCall(i){try{let t=this.toolGroup.items.find(a=>a.id==i.function.name)?.customData;if(!t)throw new Error(`Tool "${i.function.name}" not found.`);let s=JSON.parse(i.function.arguments);this.config.onAIToolStart?.(i.function.name,s);let n=await t.callback(s);typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success");let o={role:"tool",content:n,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(o),customData:o})}catch(e){Z.warn(`Unable to process tool call for "${i?.function?.name}"`,e);let t={role:"tool",content:`Error: ${e.message}`,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(t),customData:t})}}};import ct from"@anthropic-ai/sdk";import{v4 as re}from"uuid";var le=new m("AnthropicChat"),ce=class extends B{addUserMessage(i){let e={role:"user",content:i||""};this.messageGroup.add({id:"msg-"+re(),content:JSON.stringify(e),customData:e})}addAssistantMessage(i){let e={role:"assistant",content:i||""};this.messageGroup.add({id:"msg-"+re(),content:JSON.stringify(e),customData:e})}async sendMessage(i){this.addUserMessage(i);let e=new ct({apiKey:this.config.apiKey,baseURL:this.config.endpoint,dangerouslyAllowBrowser:!0}),t=!0,s="",n="";for(;t;){t=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),le.debug("Before processing state",{messages:this.messageGroup.getAll().map(h=>h.customData),tools:this.toolGroup.getAll().map(h=>h.customData),context:this.contextGroup.getAll().map(h=>h.content)});let o=this.toolGroup.getAll().map(h=>({name:h.customData?.name||"",description:h.customData?.description||"",input_schema:{type:"object",required:h.customData?.params.required||[],properties:h.customData?.params.properties||{}}})),a;if(this.config.stream){let h=e.messages.stream({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(y=>y.customData),tools:o,stream:!0});h.on("text",y=>{n+=y,this.config.onAIMessage?.(n,!0)}),a=await h.finalMessage()}else a=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(h=>h.customData),tools:o});le.debug("Message received",a);let l=!0;Array.isArray(a.content)&&a.content.length==0&&(l=!1);let d={role:a.role,content:a.content};l&&this.messageGroup.add({id:"msg-"+re(),content:JSON.stringify(d),customData:d});let c=[];for(let h of a.content)h.type=="thinking"?le.debug(`AI is thinking: ${h.thinking}`):h.type=="text"?s+=h.text||`
|