@intelliweave/embedded 1.9.66 → 1.9.67
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 we}from"uuid";function me(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)})}};var I=1,x=new h("ChatGPT"),z=class extends k{async sendMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+I++,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-"+I++,content:JSON.stringify(e),customData:e})}addUserMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+I++,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 xe(s.body)){if(d.data=="[DONE]")break;if(!d.data)continue;let c=JSON.parse(d.data);if(o){for(let a in c.choices[0].delta)if(typeof c.choices[0].delta[a]=="string"){if(a=="role"&&o[a]==c.choices[0].delta[a])continue;o[a]=(o[a]||"")+c.choices[0].delta[a]}for(let a of c.choices[0].delta.tool_calls||[]){if(o.tool_calls||(o.tool_calls=[]),!o.tool_calls[a.index]){o.tool_calls[a.index]=a;continue}let u=o.tool_calls[a.index];u.function=u.function||{},u.function.name=(u.function.name||"")+(a.function?.name||""),u.function.arguments=(u.function.arguments||"")+(a.function?.arguments||"")}}else o={chunkID:c.id,...c.choices[0].delta};o?.content&&!o.content.startsWith("{")&&this.config.onAIMessage?.(o.content,!0)}let r=Be(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-"+I++,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-"+I++,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-"+I++,content:JSON.stringify(t),customData:t})}}};import Pe from"@anthropic-ai/sdk";var J=1,Y=new h("AnthropicChat"),H=class extends k{addUserMessage(i){let e={role:"user",content:i||""};this.messageGroup.add({id:"msg-"+J++,content:JSON.stringify(e),customData:e})}addAssistantMessage(i){let e={role:"assistant",content:i||""};this.messageGroup.add({id:"msg-"+J++,content:JSON.stringify(e),customData:e})}async sendMessage(i){this.addUserMessage(i);let e=new Pe({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(),Y.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(ue=>ue.customData),tools:o,stream:!0});m.on("text",ue=>{n+=ue,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});Y.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-"+J++,content:JSON.stringify(c),customData:c});let a=[];for(let m of r.content)m.type=="thinking"?Y.debug(`AI is thinking: ${m.thinking}`):m.type=="text"?s+=m.text||`
|
|
13
13
|
|
|
14
|
-
`:m.type=="tool_use"&&a.push(this.performToolCall(m));let u=await Promise.all(a);if(u.length>0){let m={role:"user",content:u};this.messageGroup.add({id:"msg-"+J++,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 Y.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 fe}from"uuid";import Je from"minisearch";var Ze=[{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(l,i)=>{let e=await i.knowledgeBase.search(l.query),t=i;t._lastKBsearch=l.query,t._nextRequestUseKBitems=e,i.submitAnalyticsEvent({type:"kb-search",query:l.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${n}.`}}];import{Client as Ce}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Ne}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as De}from"@modelcontextprotocol/sdk/client/sse.js";var S={name:"@intelliweave/embedded",version:"1.9.66",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.12.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 _e,ToolListChangedNotificationSchema as Ke}from"@modelcontextprotocol/sdk/types.js";var g=new h("MCPKnowledgeClient"),O=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 Ce({name:S.name,version:S.version}),t=new Ne(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Ce({name:S.name,version:S.version}),s=new De(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(_e,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(Ke,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 Fe}from"uuid";var ze=new h("Statistics"),V=[];async function f(l,i){let e={...i,event_id:Fe(),event_date:new Date().toISOString(),sdk_version:S.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(V.push(e),!l||(await new Promise(s=>setTimeout(s,5e3)),V.length===0))return;let t=V.slice();V.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){ze.warn("Failed to submit analytics event:",s),V.push(...t);return}}var C=new h("KnowledgeBase"),ge=1,U=class l{constructor(i){this._sources=[{id:"core.internal",query:async()=>Ze}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${ge++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return p().knowledgeBaseSources&&(i=i.concat(p().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();C.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 a=Date.now(),u=await c.query(i);return C.debug(`Source '${c.id}' took ${Date.now()-a}ms`),u||[]}catch(a){return C.warn(`Knowledge source '${c.id}' failed:`,a),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),p().knowledgeBase&&(n=n.concat(p().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let a=n[c];a.id=a.id||`temp.${c}`,a._functionID=a.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!a.action&&a.type=="tour"&&(a.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!a.action&&a.type=="info"&&(a.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 Je({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(a=>a.id==c.id));for(let c of n)c.isContext&&(d.find(a=>a.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}}),C.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${ge++}`),C.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{C.debug(`Calling remote knowledge base action: ${d.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:d.id,parameters:c},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let m=await u.json();return r(m.updateItems||[]),m.response},r=d=>{for(let c of d){if(!c.id){C.warn("KB item skipped since it has no ID.",c);continue}let a=t.find(u=>u.id==c.id);if(a){a.name=c.name||a.name||"",a.content=c.content||a.content||"",a.disabled=c.disabled??a.disabled,a.isContext=c.isContext??a.isContext,a.parameters=c.parameters||a.parameters||[],a.tags=c.tags||a.tags,a.type=c.type||a.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||"",extra:this.ai?.extra||{},query:d},a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let u=await a.json();return n=!u.noCache,s.includes(d)||s.push(d),r(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.${ge++}`);let e=new O(i);return this.registerSource(i.id,t=>e.search(t)),e}};var j=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
14
|
+
`:m.type=="tool_use"&&a.push(this.performToolCall(m));let u=await Promise.all(a);if(u.length>0){let m={role:"user",content:u};this.messageGroup.add({id:"msg-"+J++,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 Y.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 fe}from"uuid";import Je from"minisearch";var Ze=[{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(l,i)=>{let e=await i.knowledgeBase.search(l.query),t=i;t._lastKBsearch=l.query,t._nextRequestUseKBitems=e,i.submitAnalyticsEvent({type:"kb-search",query:l.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${n}.`}}];import{Client as Ce}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Ne}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as De}from"@modelcontextprotocol/sdk/client/sse.js";var S={name:"@intelliweave/embedded",version:"1.9.67",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.12.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 _e,ToolListChangedNotificationSchema as Ke}from"@modelcontextprotocol/sdk/types.js";var g=new h("MCPKnowledgeClient"),O=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 Ce({name:S.name,version:S.version}),t=new Ne(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Ce({name:S.name,version:S.version}),s=new De(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(_e,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(Ke,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 Fe}from"uuid";var ze=new h("Statistics"),V=[];async function f(l,i){let e={...i,event_id:Fe(),event_date:new Date().toISOString(),sdk_version:S.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(V.push(e),!l||(await new Promise(s=>setTimeout(s,5e3)),V.length===0))return;let t=V.slice();V.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){ze.warn("Failed to submit analytics event:",s),V.push(...t);return}}var C=new h("KnowledgeBase"),ge=1,U=class l{constructor(i){this._sources=[{id:"core.internal",query:async()=>Ze}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${ge++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return p().knowledgeBaseSources&&(i=i.concat(p().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();C.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 a=Date.now(),u=await c.query(i);return C.debug(`Source '${c.id}' took ${Date.now()-a}ms`),u||[]}catch(a){return C.warn(`Knowledge source '${c.id}' failed:`,a),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),p().knowledgeBase&&(n=n.concat(p().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let a=n[c];a.id=a.id||`temp.${c}`,a._functionID=a.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!a.action&&a.type=="tour"&&(a.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!a.action&&a.type=="info"&&(a.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 Je({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(a=>a.id==c.id));for(let c of n)c.isContext&&(d.find(a=>a.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}}),C.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${ge++}`),C.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{C.debug(`Calling remote knowledge base action: ${d.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:d.id,parameters:c},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let m=await u.json();return r(m.updateItems||[]),m.response},r=d=>{for(let c of d){if(!c.id){C.warn("KB item skipped since it has no ID.",c);continue}let a=t.find(u=>u.id==c.id);if(a){a.name=c.name||a.name||"",a.content=c.content||a.content||"",a.disabled=c.disabled??a.disabled,a.isContext=c.isContext??a.isContext,a.parameters=c.parameters||a.parameters||[],a.tags=c.tags||a.tags,a.type=c.type||a.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||"",extra:this.ai?.extra||{},query:d},a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let u=await a.json();return n=!u.noCache,s.includes(d)||s.push(d),r(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.${ge++}`);let e=new O(i);return this.registerSource(i.id,t=>e.search(t)),e}};var j=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 L}from"uuid";function R(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)})}};var I=1,w=new g("ChatGPT"),A=class extends k{async sendMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+I++,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-"+I++,content:JSON.stringify(e),customData:e})}addUserMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+I++,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 c=this.messageGroup.items.length-1;c>=0;c--){let o=this.messageGroup.items[c].customData;if(o.role=="assistant"&&o.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(o.role=="user")break}w.debugEnabled&&w.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(c=>c.customData),messages:this.messageGroup.items.map(c=>c.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(c=>c.customData)]};for(let c of this.toolGroup.getAll()){let o=c.customData;o.description&&o.description.length>1024&&w.warn(`Tool description for "${o.name}" is too long, it will be truncated.`);let l={type:"function",function:{name:o.name,description:(o.description||"").substring(0,1024),parameters:o.params}};s.tools.push(l)}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 c=`${n.status} ${n.statusText}`;try{let l=await n.json();c=l.errorText||l.error?.message||l.error||c}catch{}let o=new Error(c);throw o.code=n.status,o}let i=null,r=null;if(this.config.stream){for await(let o of z(n.body)){if(o.data=="[DONE]")break;if(!o.data)continue;let l=JSON.parse(o.data);if(r){for(let a in l.choices[0].delta)if(typeof l.choices[0].delta[a]=="string"){if(a=="role"&&r[a]==l.choices[0].delta[a])continue;r[a]=(r[a]||"")+l.choices[0].delta[a]}for(let a of l.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[a.index]){r.tool_calls[a.index]=a;continue}let m=r.tool_calls[a.index];m.function=m.function||{},m.function.name=(m.function.name||"")+(a.function?.name||""),m.function.arguments=(m.function.arguments||"")+(a.function?.arguments||"")}}else r={chunkID:l.id,...l.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}let c=re(JSON.stringify(s)+JSON.stringify(r)||"");this.stats.tokensUsed+=c,w.debug(`Estimated ${c} 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}`),r=i?.choices?.[0]?.message;if(r||(w.warn("No response block in API response."),r={role:"assistant",content:""}),r.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(r),this.messageGroup.add({id:"msg-"+I++,content:JSON.stringify(r),customData:r}),r.content&&this.config.onAIMessage?.(r.content,!1)}async processToolCall(t){try{let s=this.toolGroup.items.find(c=>c.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 r={role:"tool",content:i,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+I++,content:JSON.stringify(r),customData:r})}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-"+I++,content:JSON.stringify(s),customData:s})}}};import oe from"@anthropic-ai/sdk";var D=1,P=new g("AnthropicChat"),O=class extends k{addUserMessage(t){let e={role:"user",content:t||""};this.messageGroup.add({id:"msg-"+D++,content:JSON.stringify(e),customData:e})}addAssistantMessage(t){let e={role:"assistant",content:t||""};this.messageGroup.add({id:"msg-"+D++,content:JSON.stringify(e),customData:e})}async sendMessage(t){this.addUserMessage(t);let e=new oe({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(),P.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 r=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||{}}})),c;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:r,stream:!0});d.on("text",v=>{i+=v,this.config.onAIMessage?.(i,!0)}),c=await d.finalMessage()}else c=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(d=>d.customData),tools:r});P.debug("Message received",c);let o=!0;Array.isArray(c.content)&&c.content.length==0&&(o=!1);let l={role:c.role,content:c.content};o&&this.messageGroup.add({id:"msg-"+D++,content:JSON.stringify(l),customData:l});let a=[];for(let d of c.content)d.type=="thinking"?P.debug(`AI is thinking: ${d.thinking}`):d.type=="text"?n+=d.text||`
|
|
13
13
|
|
|
14
|
-
`:d.type=="tool_use"&&a.push(this.performToolCall(d));let m=await Promise.all(a);if(m.length>0){let d={role:"user",content:m};this.messageGroup.add({id:"msg-"+D++,content:JSON.stringify(d),customData:d}),s=!0}this.config.onAIMessage?.(n,!0),this.stats.tokensUsed+=c.usage.input_tokens+c.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 P.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=[{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(u,t)=>{let e=await t.knowledgeBase.search(u.query),s=t;s._lastKBsearch=u.query,s._nextRequestUseKBitems=e,t.submitAnalyticsEvent({type:"kb-search",query:u.query,results:e});let n=e.filter(r=>r.type!="action").map(r=>"id="+r.id).join(", ")||"(none)",i=e.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: ${i}.`}}];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:"1.9.66",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.12.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"),N=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:r=>this.performToolCall(n.name,r),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 r=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 r=="string"?r:JSON.stringify(r)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof 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"),T=[];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(T.push(e),!u||(await new Promise(n=>setTimeout(n,5e3)),T.length===0))return;let s=T.slice();T.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),T.push(...s);return}}var x=new g("KnowledgeBase"),F=1,W=class u{constructor(t){this._sources=[{id:"core.internal",query:async()=>Q}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${F++}`),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();x.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 l=>{try{let a=Date.now(),m=await l.query(t);return x.debug(`Source '${l.id}' took ${Date.now()-a}ms`),m||[]}catch(a){return x.warn(`Knowledge source '${l.id}' failed:`,a),[]}}))).flat();i=i.concat(s.entries),i=i.concat(this.manualEntries),p().knowledgeBase&&(i=i.concat(p().knowledgeBase)),i=i.filter(l=>l&&!l.disabled);for(let l=0;l<i.length;l++){let a=i[l];a.id=a.id||`temp.${l}`,a._functionID=a.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!a.action&&a.type=="tour"&&(a.action=m=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!a.action&&a.type=="info"&&(a.action=m=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let r=new ge({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});r.addAll(i);let o=r.search(t).map(l=>i.find(a=>a.id==l.id));for(let l of i)l.isContext&&(o.find(a=>a.id===l.id)||o.push(l));return this.lastResults=o,b(this.ai,{event_type:"kb_search",value:o.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),x.debug("Found results:",o),o}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${F++}`),x.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],i=!0,r=async(o,l)=>{x.debug(`Calling remote knowledge base action: ${o.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:o.id,parameters:l},m=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!m.ok)throw new Error(`HTTP Error ${m.status} ${m.statusText}`);let d=await m.json();return c(d.updateItems||[]),d.response},c=o=>{for(let l of o){if(!l.id){x.warn("KB item skipped since it has no ID.",l);continue}let a=s.find(m=>m.id==l.id);if(a){a.name=l.name||a.name||"",a.content=l.content||a.content||"",a.disabled=l.disabled??a.disabled,a.isContext=l.isContext??a.isContext,a.parameters=l.parameters||a.parameters||[],a.tags=l.tags||a.tags,a.type=l.type||a.type;continue}s.push({...l,action:m=>r(l,m)})}};this.registerSource(e,async o=>{if(i&&n.includes(o))return s;let l={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:o},a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let m=await a.json();return i=!m.noCache,n.includes(o)||n.push(o),c(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.${F++}`);let e=new N(t);return this.registerSource(t.id,s=>e.search(s)),e}};import{v4 as J}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"&&a.push(this.performToolCall(d));let m=await Promise.all(a);if(m.length>0){let d={role:"user",content:m};this.messageGroup.add({id:"msg-"+D++,content:JSON.stringify(d),customData:d}),s=!0}this.config.onAIMessage?.(n,!0),this.stats.tokensUsed+=c.usage.input_tokens+c.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 P.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=[{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(u,t)=>{let e=await t.knowledgeBase.search(u.query),s=t;s._lastKBsearch=u.query,s._nextRequestUseKBitems=e,t.submitAnalyticsEvent({type:"kb-search",query:u.query,results:e});let n=e.filter(r=>r.type!="action").map(r=>"id="+r.id).join(", ")||"(none)",i=e.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: ${i}.`}}];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:"1.9.67",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.12.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"),N=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:r=>this.performToolCall(n.name,r),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 r=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 r=="string"?r:JSON.stringify(r)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof 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"),T=[];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(T.push(e),!u||(await new Promise(n=>setTimeout(n,5e3)),T.length===0))return;let s=T.slice();T.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),T.push(...s);return}}var x=new g("KnowledgeBase"),F=1,W=class u{constructor(t){this._sources=[{id:"core.internal",query:async()=>Q}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${F++}`),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();x.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 l=>{try{let a=Date.now(),m=await l.query(t);return x.debug(`Source '${l.id}' took ${Date.now()-a}ms`),m||[]}catch(a){return x.warn(`Knowledge source '${l.id}' failed:`,a),[]}}))).flat();i=i.concat(s.entries),i=i.concat(this.manualEntries),p().knowledgeBase&&(i=i.concat(p().knowledgeBase)),i=i.filter(l=>l&&!l.disabled);for(let l=0;l<i.length;l++){let a=i[l];a.id=a.id||`temp.${l}`,a._functionID=a.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!a.action&&a.type=="tour"&&(a.action=m=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!a.action&&a.type=="info"&&(a.action=m=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let r=new ge({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});r.addAll(i);let o=r.search(t).map(l=>i.find(a=>a.id==l.id));for(let l of i)l.isContext&&(o.find(a=>a.id===l.id)||o.push(l));return this.lastResults=o,b(this.ai,{event_type:"kb_search",value:o.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),x.debug("Found results:",o),o}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${F++}`),x.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],i=!0,r=async(o,l)=>{x.debug(`Calling remote knowledge base action: ${o.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:o.id,parameters:l},m=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!m.ok)throw new Error(`HTTP Error ${m.status} ${m.statusText}`);let d=await m.json();return c(d.updateItems||[]),d.response},c=o=>{for(let l of o){if(!l.id){x.warn("KB item skipped since it has no ID.",l);continue}let a=s.find(m=>m.id==l.id);if(a){a.name=l.name||a.name||"",a.content=l.content||a.content||"",a.disabled=l.disabled??a.disabled,a.isContext=l.isContext??a.isContext,a.parameters=l.parameters||a.parameters||[],a.tags=l.tags||a.tags,a.type=l.type||a.type;continue}s.push({...l,action:m=>r(l,m)})}};this.registerSource(e,async o=>{if(i&&n.includes(o))return s;let l={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:o},a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let m=await a.json();return i=!m.noCache,n.includes(o)||n.push(o),c(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.${F++}`);let e=new N(t);return this.registerSource(t.id,s=>e.search(s)),e}};import{v4 as J}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 Be,{createContext as mt,useContext as pt,useEffect as ue,useMemo as gt,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)})}};var T=1,w=new u("ChatGPT"),z=class extends I{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?.(),w.debugEnabled&&w.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}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 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&&w.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 Ge(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 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=_e(JSON.stringify(t)+JSON.stringify(o)||"");this.stats.tokensUsed+=a,w.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,w.debug(`Used ${n?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),o=n?.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(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-"+T++,content:JSON.stringify(o),customData:o})}catch(e){w.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 Ke from"@anthropic-ai/sdk";var J=1,Y=new u("AnthropicChat"),H=class extends I{addUserMessage(i){let e={role:"user",content:i||""};this.messageGroup.add({id:"msg-"+J++,content:JSON.stringify(e),customData:e})}addAssistantMessage(i){let e={role:"assistant",content:i||""};this.messageGroup.add({id:"msg-"+J++,content:JSON.stringify(e),customData:e})}async sendMessage(i){this.addUserMessage(i);let e=new Ke({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(),Y.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(me=>me.customData),tools:o,stream:!0});p.on("text",me=>{n+=me,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});Y.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-"+J++,content:JSON.stringify(c),customData:c});let l=[];for(let p of a.content)p.type=="thinking"?Y.debug(`AI is thinking: ${p.thinking}`):p.type=="text"?s+=p.text||`
|
|
13
13
|
|
|
14
|
-
`:p.type=="tool_use"&&l.push(this.performToolCall(p));let m=await Promise.all(l);if(m.length>0){let p={role:"user",content:m};this.messageGroup.add({id:"msg-"+J++,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 Y.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 ye}from"uuid";import je from"minisearch";var ke=[{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(r,i)=>{let e=await i.knowledgeBase.search(r.query),t=i;t._lastKBsearch=r.query,t._nextRequestUseKBitems=e,i.submitAnalyticsEvent({type:"kb-search",query:r.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${n}.`}}];import{Client as Ie}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as ze}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Je}from"@modelcontextprotocol/sdk/client/sse.js";var x={name:"@intelliweave/embedded",version:"1.9.66",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.12.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 Ye,ToolListChangedNotificationSchema as He}from"@modelcontextprotocol/sdk/types.js";var g=new u("MCPKnowledgeClient"),O=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 Ie({name:x.name,version:x.version}),t=new ze(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Ie({name:x.name,version:x.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(Ye,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(He,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 Oe}from"uuid";var Ue=new u("Statistics"),V=[];async function f(r,i){let e={...i,event_id:Oe(),event_date:new Date().toISOString(),sdk_version:x.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(V.push(e),!r||(await new Promise(s=>setTimeout(s,5e3)),V.length===0))return;let t=V.slice();V.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){Ue.warn("Failed to submit analytics event:",s),V.push(...t);return}}var C=new u("KnowledgeBase"),fe=1,U=class r{constructor(i){this._sources=[{id:"core.internal",query:async()=>ke}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${fe++}`),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();C.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(),m=await c.query(i);return C.debug(`Source '${c.id}' took ${Date.now()-l}ms`),m||[]}catch(l){return C.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=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 je({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}}),C.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${fe++}`),C.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{C.debug(`Calling remote knowledge base action: ${d.id}`);let l={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:d.id,parameters:c},m=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!m.ok)throw new Error(`HTTP Error ${m.status} ${m.statusText}`);let p=await m.json();return a(p.updateItems||[]),p.response},a=d=>{for(let c of d){if(!c.id){C.warn("KB item skipped since it has no ID.",c);continue}let l=t.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}t.push({...c,action:m=>o(c,m)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},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 m=await l.json();return n=!m.noCache,s.includes(d)||s.push(d),a(m.items),t})}clone(){let i=new r(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${fe++}`);let e=new O(i);return this.registerSource(i.id,t=>e.search(t)),e}};var j=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
14
|
+
`:p.type=="tool_use"&&l.push(this.performToolCall(p));let m=await Promise.all(l);if(m.length>0){let p={role:"user",content:m};this.messageGroup.add({id:"msg-"+J++,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 Y.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 ye}from"uuid";import je from"minisearch";var ke=[{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(r,i)=>{let e=await i.knowledgeBase.search(r.query),t=i;t._lastKBsearch=r.query,t._nextRequestUseKBitems=e,i.submitAnalyticsEvent({type:"kb-search",query:r.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",n=e.filter(o=>o.type=="action").map(o=>"name="+o._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${n}.`}}];import{Client as Ie}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as ze}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Je}from"@modelcontextprotocol/sdk/client/sse.js";var x={name:"@intelliweave/embedded",version:"1.9.67",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.12.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 Ye,ToolListChangedNotificationSchema as He}from"@modelcontextprotocol/sdk/types.js";var g=new u("MCPKnowledgeClient"),O=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 Ie({name:x.name,version:x.version}),t=new ze(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Ie({name:x.name,version:x.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(Ye,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(He,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 Oe}from"uuid";var Ue=new u("Statistics"),V=[];async function f(r,i){let e={...i,event_id:Oe(),event_date:new Date().toISOString(),sdk_version:x.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(V.push(e),!r||(await new Promise(s=>setTimeout(s,5e3)),V.length===0))return;let t=V.slice();V.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){Ue.warn("Failed to submit analytics event:",s),V.push(...t);return}}var C=new u("KnowledgeBase"),fe=1,U=class r{constructor(i){this._sources=[{id:"core.internal",query:async()=>ke}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${fe++}`),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();C.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(),m=await c.query(i);return C.debug(`Source '${c.id}' took ${Date.now()-l}ms`),m||[]}catch(l){return C.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=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 je({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}}),C.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${fe++}`),C.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{C.debug(`Calling remote knowledge base action: ${d.id}`);let l={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:d.id,parameters:c},m=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!m.ok)throw new Error(`HTTP Error ${m.status} ${m.statusText}`);let p=await m.json();return a(p.updateItems||[]),p.response},a=d=>{for(let c of d){if(!c.id){C.warn("KB item skipped since it has no ID.",c);continue}let l=t.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}t.push({...c,action:m=>o(c,m)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},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 m=await l.json();return n=!m.noCache,s.includes(d)||s.push(d),a(m.items),t})}clone(){let i=new r(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${fe++}`);let e=new O(i);return this.registerSource(i.id,t=>e.search(t)),e}};var j=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
|
|
|
@@ -3278,7 +3278,7 @@ Assistant:`;He.DEFAULT_TIMEOUT=6e5;He.AnthropicError=te;He.APIError=nt;He.APICon
|
|
|
3278
3278
|
`;break;case"id":o=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?a(parseInt(y,10)):t(new Xo(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:b}));break;default:t(new Xo(`Unknown field "${f.length>20?`${f.slice(0,20)}\u2026`:f}"`,{type:"unknown-field",field:f,value:y,line:b}));break}}function d(){l.length>0&&e({id:o,event:c||void 0,data:l.endsWith(`
|
|
3279
3279
|
`)?l.slice(0,-1):l}),o=void 0,l="",c=""}function g(f={}){i&&f.consume&&p(i),s=!0,o=void 0,l="",c="",i=""}return{feed:u,reset:g}}function kC(r){let e=[],t="",a=0;for(;a<r.length;){let n=r.indexOf("\r",a),i=r.indexOf(`
|
|
3280
3280
|
`,a),s=-1;if(n!==-1&&i!==-1?s=Math.min(n,i):n!==-1?s=n:i!==-1&&(s=i),s===-1){t=r.slice(a);break}else{let o=r.slice(a,s);e.push(o),a=s+1,r[a-1]==="\r"&&r[a]===`
|
|
3281
|
-
`&&a++}}return[e,t]}var Jo=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:a}={}){let n;super({start(i){n=Yo({onEvent:s=>{i.enqueue(s)},onError(s){e==="terminate"?i.error(s):typeof e=="function"&&e(s)},onRetry:t,onComment:a})},transform(i){n.feed(i)}})}};var CC={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Vi=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Zo=class{constructor(e,t){var a;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._sessionId=t?.sessionId,this._reconnectionOptions=(a=t?.reconnectionOptions)!==null&&a!==void 0?a:CC}async _authThenStart(){var e;if(!this._authProvider)throw new Rt("No auth provider");let t;try{t=await dn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(t!=="AUTHORIZED")throw new Rt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let t={};if(this._authProvider){let a=await this._authProvider.tokens();a&&(t.Authorization=`Bearer ${a.access_token}`)}return this._sessionId&&(t["mcp-session-id"]=this._sessionId),new Headers({...t,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}async _startOrAuthSse(e){var t,a;let{resumptionToken:n}=e;try{let i=await this._commonHeaders();i.set("Accept","text/event-stream"),n&&i.set("last-event-id",n);let s=await fetch(this._url,{method:"GET",headers:i,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Vi(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e)}catch(i){throw(a=this.onerror)===null||a===void 0||a.call(this,i),i}}_getNextReconnectionDelay(e){let t=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(a,e),n)}_scheduleReconnection(e,t=0){var a;let n=this._reconnectionOptions.maxRetries;if(n>0&&t>=n){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t){if(!e)return;let{onresumptiontoken:a,replayMessageId:n}=t,i;(async()=>{var o,l,c,u;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new Jo).getReader();for(;;){let{value:m,done:d}=await p.read();if(d)break;if(m.id&&(i=m.id,a?.(m.id)),!m.event||m.event==="message")try{let g=$a.parse(JSON.parse(m.data));n!==void 0&&zi(g)&&(g.id=n),(o=this.onmessage)===null||o===void 0||o.call(this,g)}catch(g){(l=this.onerror)===null||l===void 0||l.call(this,g)}}}catch(p){if((c=this.onerror)===null||c===void 0||c.call(this,new Error(`SSE stream disconnected: ${p}`)),this._abortController&&!this._abortController.signal.aborted&&i!==void 0)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(m){(u=this.onerror)===null||u===void 0||u.call(this,new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}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 Rt("No auth provider");if(await dn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new Rt("Failed to authorize")}async close(){var e,t;(e=this._abortController)===null||e===void 0||e.abort(),(t=this.onclose)===null||t===void 0||t.call(this)}async send(e,t){var a,n,i;try{let{resumptionToken:s,onresumptiontoken:o}=t||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:vo(e)?e.id:void 0}).catch(f=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,f)});return}let l=await this._commonHeaders();l.set("content-type","application/json"),l.set("accept","application/json, text/event-stream");let c={...this._requestInit,method:"POST",headers:l,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},u=await fetch(this._url,c),p=u.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!u.ok){if(u.status===401&&this._authProvider){if(this._resourceMetadataUrl=Ko(u),await dn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new Rt;return this.send(e)}let f=await u.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${u.status}): ${f}`)}if(u.status===202){Sh(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,f)});return}let d=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,g=u.headers.get("content-type");if(d)if(g?.includes("text/event-stream"))this._handleSseStream(u.body,{onresumptiontoken:o});else if(g?.includes("application/json")){let f=await u.json(),y=Array.isArray(f)?f.map(b=>$a.parse(b)):[$a.parse(f)];for(let b of y)(n=this.onmessage)===null||n===void 0||n.call(this,b)}else throw new Vi(-1,`Unexpected content type: ${g}`)}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,t;if(this._sessionId)try{let a=await this._commonHeaders(),n={...this._requestInit,method:"DELETE",headers:a,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},i=await fetch(this._url,n);if(!i.ok&&i.status!==405)throw new Vi(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}}};var el=class extends Event{constructor(e,t){var a,n;super(e),this.code=(a=t?.code)!=null?a:void 0,this.message=(n=t?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,a){return a(Mf(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(Mf(this),t)}};function xC(r){let e=globalThis.DOMException;return typeof e=="function"?new e(r,"SyntaxError"):new SyntaxError(r)}function Xu(r){return r instanceof Error?"errors"in r&&Array.isArray(r.errors)?r.errors.map(Xu).join(", "):"cause"in r&&r.cause instanceof Error?`${r}: ${Xu(r.cause)}`:r.message:`${r}`}function Mf(r){return{type:r.type,message:r.message,code:r.code,defaultPrevented:r.defaultPrevented,cancelable:r.cancelable,timeStamp:r.timeStamp}}var Lf=r=>{throw TypeError(r)},nd=(r,e,t)=>e.has(r)||Lf("Cannot "+t),ye=(r,e,t)=>(nd(r,e,"read from private field"),t?t.call(r):e.get(r)),tt=(r,e,t)=>e.has(r)?Lf("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Ge=(r,e,t,a)=>(nd(r,e,"write to private field"),e.set(r,t),t),Hr=(r,e,t)=>(nd(r,e,"access private method"),t),Pt,Kn,Ka,Qo,tl,qi,Ja,$i,pn,Xa,Za,Ya,ji,dr,Yu,Ju,Zu,Of,Qu,ed,Wi,td,rd,Xn=class extends EventTarget{constructor(e,t){var a,n;super(),tt(this,dr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,tt(this,Pt),tt(this,Kn),tt(this,Ka),tt(this,Qo),tt(this,tl),tt(this,qi),tt(this,Ja),tt(this,$i,null),tt(this,pn),tt(this,Xa),tt(this,Za,null),tt(this,Ya,null),tt(this,ji,null),tt(this,Ju,async i=>{var s;ye(this,Xa).reset();let{body:o,redirected:l,status:c,headers:u}=i;if(c===204){Hr(this,dr,Wi).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Ge(this,Ka,new URL(i.url)):Ge(this,Ka,void 0),c!==200){Hr(this,dr,Wi).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Hr(this,dr,Wi).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(ye(this,Pt)===this.CLOSED)return;Ge(this,Pt,this.OPEN);let p=new Event("open");if((s=ye(this,ji))==null||s.call(this,p),this.dispatchEvent(p),typeof o!="object"||!o||!("getReader"in o)){Hr(this,dr,Wi).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let m=new TextDecoder,d=o.getReader(),g=!0;do{let{done:f,value:y}=await d.read();y&&ye(this,Xa).feed(m.decode(y,{stream:!f})),f&&(g=!1,ye(this,Xa).reset(),Hr(this,dr,td).call(this))}while(g)}),tt(this,Zu,i=>{Ge(this,pn,void 0),!(i.name==="AbortError"||i.type==="aborted")&&Hr(this,dr,td).call(this,Xu(i))}),tt(this,Qu,i=>{typeof i.id=="string"&&Ge(this,$i,i.id);let s=new MessageEvent(i.event||"message",{data:i.data,origin:ye(this,Ka)?ye(this,Ka).origin:ye(this,Kn).origin,lastEventId:i.id||""});ye(this,Ya)&&(!i.event||i.event==="message")&&ye(this,Ya).call(this,s),this.dispatchEvent(s)}),tt(this,ed,i=>{Ge(this,qi,i)}),tt(this,rd,()=>{Ge(this,Ja,void 0),ye(this,Pt)===this.CONNECTING&&Hr(this,dr,Yu).call(this)});try{if(e instanceof URL)Ge(this,Kn,e);else if(typeof e=="string")Ge(this,Kn,new URL(e,TC()));else throw new Error("Invalid URL")}catch{throw xC("An invalid or illegal string was specified")}Ge(this,Xa,Yo({onEvent:ye(this,Qu),onRetry:ye(this,ed)})),Ge(this,Pt,this.CONNECTING),Ge(this,qi,3e3),Ge(this,tl,(a=t?.fetch)!=null?a:globalThis.fetch),Ge(this,Qo,(n=t?.withCredentials)!=null?n:!1),Hr(this,dr,Yu).call(this)}get readyState(){return ye(this,Pt)}get url(){return ye(this,Kn).href}get withCredentials(){return ye(this,Qo)}get onerror(){return ye(this,Za)}set onerror(e){Ge(this,Za,e)}get onmessage(){return ye(this,Ya)}set onmessage(e){Ge(this,Ya,e)}get onopen(){return ye(this,ji)}set onopen(e){Ge(this,ji,e)}addEventListener(e,t,a){let n=t;super.addEventListener(e,n,a)}removeEventListener(e,t,a){let n=t;super.removeEventListener(e,n,a)}close(){ye(this,Ja)&&clearTimeout(ye(this,Ja)),ye(this,Pt)!==this.CLOSED&&(ye(this,pn)&&ye(this,pn).abort(),Ge(this,Pt,this.CLOSED),Ge(this,pn,void 0))}};Pt=new WeakMap,Kn=new WeakMap,Ka=new WeakMap,Qo=new WeakMap,tl=new WeakMap,qi=new WeakMap,Ja=new WeakMap,$i=new WeakMap,pn=new WeakMap,Xa=new WeakMap,Za=new WeakMap,Ya=new WeakMap,ji=new WeakMap,dr=new WeakSet,Yu=function(){Ge(this,Pt,this.CONNECTING),Ge(this,pn,new AbortController),ye(this,tl)(ye(this,Kn),Hr(this,dr,Of).call(this)).then(ye(this,Ju)).catch(ye(this,Zu))},Ju=new WeakMap,Zu=new WeakMap,Of=function(){var r;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...ye(this,$i)?{"Last-Event-ID":ye(this,$i)}:void 0},cache:"no-store",signal:(r=ye(this,pn))==null?void 0:r.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Qu=new WeakMap,ed=new WeakMap,Wi=function(r,e){var t;ye(this,Pt)!==this.CLOSED&&Ge(this,Pt,this.CLOSED);let a=new el("error",{code:e,message:r});(t=ye(this,Za))==null||t.call(this,a),this.dispatchEvent(a)},td=function(r,e){var t;if(ye(this,Pt)===this.CLOSED)return;Ge(this,Pt,this.CONNECTING);let a=new el("error",{code:e,message:r});(t=ye(this,Za))==null||t.call(this,a),this.dispatchEvent(a),Ge(this,Ja,setTimeout(ye(this,rd),ye(this,qi)))},rd=new WeakMap,Xn.CONNECTING=0,Xn.OPEN=1,Xn.CLOSED=2;function TC(){let r="document"in globalThis?globalThis.document:void 0;return r&&typeof r=="object"&&"baseURI"in r&&typeof r.baseURI=="string"?r.baseURI:void 0}var ad=class extends Error{constructor(e,t,a){super(`SSE error: ${t}`),this.code=e,this.event=a}},rl=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider}async _authThenStart(){var e;if(!this._authProvider)throw new Rt("No auth provider");let t;try{t=await dn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(t!=="AUTHORIZED")throw new Rt;return await this._startOrAuth()}async _commonHeaders(){var e;let t={...(e=this._requestInit)===null||e===void 0?void 0:e.headers};if(this._authProvider){let a=await this._authProvider.tokens();a&&(t.Authorization=`Bearer ${a.access_token}`)}return t}_startOrAuth(){return new Promise((e,t)=>{var a;this._eventSource=new Xn(this._url.href,(a=this._eventSourceInit)!==null&&a!==void 0?a:{fetch:(n,i)=>this._commonHeaders().then(s=>fetch(n,{...i,headers:{...s,Accept:"text/event-stream"}}))}),this._abortController=new AbortController,this._eventSource.onerror=n=>{var i;if(n.code===401&&this._authProvider){this._authThenStart().then(e,t);return}let s=new ad(n.code,n.message,n);t(s),(i=this.onerror)===null||i===void 0||i.call(this,s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",n=>{var i;let s=n;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(o){t(o),(i=this.onerror)===null||i===void 0||i.call(this,o),this.close();return}e()}),this._eventSource.onmessage=n=>{var i,s;let o=n,l;try{l=$a.parse(JSON.parse(o.data))}catch(c){(i=this.onerror)===null||i===void 0||i.call(this,c);return}(s=this.onmessage)===null||s===void 0||s.call(this,l)}})}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 Rt("No auth provider");if(await dn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new Rt("Failed to authorize")}async close(){var e,t,a;(e=this._abortController)===null||e===void 0||e.abort(),(t=this._eventSource)===null||t===void 0||t.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(e){var t,a,n;if(!this._endpoint)throw new Error("Not connected");try{let i=await this._commonHeaders(),s=new Headers({...i,...(t=this._requestInit)===null||t===void 0?void 0:t.headers});s.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},l=await fetch(this._endpoint,o);if(!l.ok){if(l.status===401&&this._authProvider){if(this._resourceMetadataUrl=Ko(l),await dn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new Rt;return this.send(e)}let c=await l.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}};var Vr={name:"@intelliweave/embedded",version:"1.9.66",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.12.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 rt=new ge("MCPKnowledgeClient"),nl=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(){rt.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new Hi({name:Vr.name,version:Vr.version}),a=new Zo(new URL(this.config.baseURL));return await t.connect(a),rt.debug("Connected with HTTP streaming mode"),t}).catch(async t=>{let a=new Hi({name:Vr.name,version:Vr.version}),n=new rl(new URL(this.config.baseURL));return await a.connect(n),rt.debug("Connected with SSE mode"),a});return await this.disconnect(),this.client=e,e.onerror=t=>{rt.error(`MCP client error: ${t.message}`)},e.onclose=()=>{rt.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(vu,t=>{t.params.level=="critical"?rt.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?rt.error(`[Server] ${t.params.data}`):t.params.level=="error"?rt.error(`[Server] ${t.params.data}`):t.params.level=="warning"?rt.warn(`[Server] ${t.params.data}`):t.params.level=="info"?rt.info(`[Server] ${t.params.data}`):t.params.level=="debug"?rt.debug(`[Server] ${t.params.data}`):rt.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(bu,t=>{rt.debug("Tool list changed",t),this.fetchTools()}),rt.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],t;for(;;){let n=await this.client.listTools({cursor:t});t=n.nextCursor;for(let i of n.tools||[])e.push(i);if(!n?.tools?.length||!t)break}let a=[];for(let n of e){let i=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);a.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:s=>this.performToolCall(n.name,s),disabled:i})}rt.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=a}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),a=await this.performSearchCall(e);return t=t.concat(a),this.lastSearchQuery=e,this.lastSearchResults=t,rt.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let a=this.tools.find(i=>i.name==this.config.searchToolName);if(!a)return rt.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let n;if(a.inputSchema.required?.length==1){let i=a.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[i]:e})}else if(a.inputSchema.properties&&Object.keys(a.inputSchema.properties).length==1){let i=Object.keys(a.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[i]:e})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let i=0;i<n.length;i++){let s=n[i];t.push({id:this.config.id+":"+this.config.searchToolName+":"+i,name:`Search result ${i+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else t.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 t}async performToolCall(e,t){await this.connect(),rt.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let a=await this.client.callTool({name:e,arguments:t});if(a.isError){let n=a.content?.[0]?.text||"Unknown error";throw rt.error(`Error calling tool ${e}: ${n}`),new Error(`Error calling tool ${e}: ${n}`)}if(Array.isArray(a.content)&&a.content.length==1&&a.content[0].type=="text")try{return JSON.parse(a.content[0].text)}catch{}return a.content||[]}};var IC=new ge("Statistics"),Ki=[];async function Et(r,e){let t={...e,event_id:$t(),event_date:new Date().toISOString(),sdk_version:Vr.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(Ki.push(t),!r||(await new Promise(n=>setTimeout(n,5e3)),Ki.length===0))return;let a=Ki.slice();Ki.length=0;try{let n=await fetch(r.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:a})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){IC.warn("Failed to submit analytics event:",n),Ki.push(...a);return}}var Yn=new ge("KnowledgeBase"),id=1,al=class r{constructor(e){this._sources=[{id:"core.internal",query:async()=>Zm}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,t){let a=e;return typeof e=="function"&&(t=e,a=`source.${id++}`),this._sources.push({id:a,query:t}),a}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return Be().knowledgeBaseSources&&(e=e.concat(Be().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(t=>!t.disabled),e}async search(e){let t=Date.now();Yn.debug(`Searching knowledge base for: ${e}`);let a=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});a.query=e,a.entries=[],a.sources=[],typeof document<"u"&&document.dispatchEvent(a),this._windowSources=a.sources;let i=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),p=await c.query(e);return Yn.debug(`Source '${c.id}' took ${Date.now()-u}ms`),p||[]}catch(u){return Yn.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();i=i.concat(a.entries),i=i.concat(this.manualEntries),Be().knowledgeBase&&(i=i.concat(Be().knowledgeBase)),i=i.filter(c=>c&&!c.disabled);for(let c=0;c<i.length;c++){let u=i[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!u.action&&u.type=="tour"&&(u.action=p=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!u.action&&u.type=="info"&&(u.action=p=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let s=new Jm({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(i);let l=s.search(e).map(c=>i.find(u=>u.id==c.id));for(let c of i)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Et(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),Yn.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${id++}`),Yn.debug(`Registering remote knowledge base source: ${e}`);let a=[],n=[],i=!0,s=async(l,c)=>{Yn.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:c},p=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw new Error(`HTTP Error ${p.status} ${p.statusText}`);let m=await p.json();return o(m.updateItems||[]),m.response},o=l=>{for(let c of l){if(!c.id){Yn.warn("KB item skipped since it has no ID.",c);continue}let u=a.find(p=>p.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}a.push({...c,action:p=>s(c,p)})}};this.registerSource(t,async l=>{if(i&&n.includes(l))return a;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},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 p=await u.json();return i=!p.noCache,n.includes(l)||n.push(l),o(p.items),a})}clone(){let e=new r(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${id++}`);let t=new nl(e);return this.registerSource(e.id,a=>t.search(a)),t}};var il=class{constructor(e){this.ai=e}async boolean(e){let t=await this.instruct({...e,instruction:`${e.instruction}
|
|
3281
|
+
`&&a++}}return[e,t]}var Jo=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:a}={}){let n;super({start(i){n=Yo({onEvent:s=>{i.enqueue(s)},onError(s){e==="terminate"?i.error(s):typeof e=="function"&&e(s)},onRetry:t,onComment:a})},transform(i){n.feed(i)}})}};var CC={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Vi=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Zo=class{constructor(e,t){var a;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._sessionId=t?.sessionId,this._reconnectionOptions=(a=t?.reconnectionOptions)!==null&&a!==void 0?a:CC}async _authThenStart(){var e;if(!this._authProvider)throw new Rt("No auth provider");let t;try{t=await dn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(t!=="AUTHORIZED")throw new Rt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let t={};if(this._authProvider){let a=await this._authProvider.tokens();a&&(t.Authorization=`Bearer ${a.access_token}`)}return this._sessionId&&(t["mcp-session-id"]=this._sessionId),new Headers({...t,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}async _startOrAuthSse(e){var t,a;let{resumptionToken:n}=e;try{let i=await this._commonHeaders();i.set("Accept","text/event-stream"),n&&i.set("last-event-id",n);let s=await fetch(this._url,{method:"GET",headers:i,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Vi(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e)}catch(i){throw(a=this.onerror)===null||a===void 0||a.call(this,i),i}}_getNextReconnectionDelay(e){let t=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(a,e),n)}_scheduleReconnection(e,t=0){var a;let n=this._reconnectionOptions.maxRetries;if(n>0&&t>=n){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t){if(!e)return;let{onresumptiontoken:a,replayMessageId:n}=t,i;(async()=>{var o,l,c,u;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new Jo).getReader();for(;;){let{value:m,done:d}=await p.read();if(d)break;if(m.id&&(i=m.id,a?.(m.id)),!m.event||m.event==="message")try{let g=$a.parse(JSON.parse(m.data));n!==void 0&&zi(g)&&(g.id=n),(o=this.onmessage)===null||o===void 0||o.call(this,g)}catch(g){(l=this.onerror)===null||l===void 0||l.call(this,g)}}}catch(p){if((c=this.onerror)===null||c===void 0||c.call(this,new Error(`SSE stream disconnected: ${p}`)),this._abortController&&!this._abortController.signal.aborted&&i!==void 0)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(m){(u=this.onerror)===null||u===void 0||u.call(this,new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}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 Rt("No auth provider");if(await dn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new Rt("Failed to authorize")}async close(){var e,t;(e=this._abortController)===null||e===void 0||e.abort(),(t=this.onclose)===null||t===void 0||t.call(this)}async send(e,t){var a,n,i;try{let{resumptionToken:s,onresumptiontoken:o}=t||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:vo(e)?e.id:void 0}).catch(f=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,f)});return}let l=await this._commonHeaders();l.set("content-type","application/json"),l.set("accept","application/json, text/event-stream");let c={...this._requestInit,method:"POST",headers:l,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},u=await fetch(this._url,c),p=u.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!u.ok){if(u.status===401&&this._authProvider){if(this._resourceMetadataUrl=Ko(u),await dn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new Rt;return this.send(e)}let f=await u.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${u.status}): ${f}`)}if(u.status===202){Sh(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>{var y;return(y=this.onerror)===null||y===void 0?void 0:y.call(this,f)});return}let d=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,g=u.headers.get("content-type");if(d)if(g?.includes("text/event-stream"))this._handleSseStream(u.body,{onresumptiontoken:o});else if(g?.includes("application/json")){let f=await u.json(),y=Array.isArray(f)?f.map(b=>$a.parse(b)):[$a.parse(f)];for(let b of y)(n=this.onmessage)===null||n===void 0||n.call(this,b)}else throw new Vi(-1,`Unexpected content type: ${g}`)}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,t;if(this._sessionId)try{let a=await this._commonHeaders(),n={...this._requestInit,method:"DELETE",headers:a,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},i=await fetch(this._url,n);if(!i.ok&&i.status!==405)throw new Vi(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}}};var el=class extends Event{constructor(e,t){var a,n;super(e),this.code=(a=t?.code)!=null?a:void 0,this.message=(n=t?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,a){return a(Mf(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(Mf(this),t)}};function xC(r){let e=globalThis.DOMException;return typeof e=="function"?new e(r,"SyntaxError"):new SyntaxError(r)}function Xu(r){return r instanceof Error?"errors"in r&&Array.isArray(r.errors)?r.errors.map(Xu).join(", "):"cause"in r&&r.cause instanceof Error?`${r}: ${Xu(r.cause)}`:r.message:`${r}`}function Mf(r){return{type:r.type,message:r.message,code:r.code,defaultPrevented:r.defaultPrevented,cancelable:r.cancelable,timeStamp:r.timeStamp}}var Lf=r=>{throw TypeError(r)},nd=(r,e,t)=>e.has(r)||Lf("Cannot "+t),ye=(r,e,t)=>(nd(r,e,"read from private field"),t?t.call(r):e.get(r)),tt=(r,e,t)=>e.has(r)?Lf("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Ge=(r,e,t,a)=>(nd(r,e,"write to private field"),e.set(r,t),t),Hr=(r,e,t)=>(nd(r,e,"access private method"),t),Pt,Kn,Ka,Qo,tl,qi,Ja,$i,pn,Xa,Za,Ya,ji,dr,Yu,Ju,Zu,Of,Qu,ed,Wi,td,rd,Xn=class extends EventTarget{constructor(e,t){var a,n;super(),tt(this,dr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,tt(this,Pt),tt(this,Kn),tt(this,Ka),tt(this,Qo),tt(this,tl),tt(this,qi),tt(this,Ja),tt(this,$i,null),tt(this,pn),tt(this,Xa),tt(this,Za,null),tt(this,Ya,null),tt(this,ji,null),tt(this,Ju,async i=>{var s;ye(this,Xa).reset();let{body:o,redirected:l,status:c,headers:u}=i;if(c===204){Hr(this,dr,Wi).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Ge(this,Ka,new URL(i.url)):Ge(this,Ka,void 0),c!==200){Hr(this,dr,Wi).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Hr(this,dr,Wi).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(ye(this,Pt)===this.CLOSED)return;Ge(this,Pt,this.OPEN);let p=new Event("open");if((s=ye(this,ji))==null||s.call(this,p),this.dispatchEvent(p),typeof o!="object"||!o||!("getReader"in o)){Hr(this,dr,Wi).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let m=new TextDecoder,d=o.getReader(),g=!0;do{let{done:f,value:y}=await d.read();y&&ye(this,Xa).feed(m.decode(y,{stream:!f})),f&&(g=!1,ye(this,Xa).reset(),Hr(this,dr,td).call(this))}while(g)}),tt(this,Zu,i=>{Ge(this,pn,void 0),!(i.name==="AbortError"||i.type==="aborted")&&Hr(this,dr,td).call(this,Xu(i))}),tt(this,Qu,i=>{typeof i.id=="string"&&Ge(this,$i,i.id);let s=new MessageEvent(i.event||"message",{data:i.data,origin:ye(this,Ka)?ye(this,Ka).origin:ye(this,Kn).origin,lastEventId:i.id||""});ye(this,Ya)&&(!i.event||i.event==="message")&&ye(this,Ya).call(this,s),this.dispatchEvent(s)}),tt(this,ed,i=>{Ge(this,qi,i)}),tt(this,rd,()=>{Ge(this,Ja,void 0),ye(this,Pt)===this.CONNECTING&&Hr(this,dr,Yu).call(this)});try{if(e instanceof URL)Ge(this,Kn,e);else if(typeof e=="string")Ge(this,Kn,new URL(e,TC()));else throw new Error("Invalid URL")}catch{throw xC("An invalid or illegal string was specified")}Ge(this,Xa,Yo({onEvent:ye(this,Qu),onRetry:ye(this,ed)})),Ge(this,Pt,this.CONNECTING),Ge(this,qi,3e3),Ge(this,tl,(a=t?.fetch)!=null?a:globalThis.fetch),Ge(this,Qo,(n=t?.withCredentials)!=null?n:!1),Hr(this,dr,Yu).call(this)}get readyState(){return ye(this,Pt)}get url(){return ye(this,Kn).href}get withCredentials(){return ye(this,Qo)}get onerror(){return ye(this,Za)}set onerror(e){Ge(this,Za,e)}get onmessage(){return ye(this,Ya)}set onmessage(e){Ge(this,Ya,e)}get onopen(){return ye(this,ji)}set onopen(e){Ge(this,ji,e)}addEventListener(e,t,a){let n=t;super.addEventListener(e,n,a)}removeEventListener(e,t,a){let n=t;super.removeEventListener(e,n,a)}close(){ye(this,Ja)&&clearTimeout(ye(this,Ja)),ye(this,Pt)!==this.CLOSED&&(ye(this,pn)&&ye(this,pn).abort(),Ge(this,Pt,this.CLOSED),Ge(this,pn,void 0))}};Pt=new WeakMap,Kn=new WeakMap,Ka=new WeakMap,Qo=new WeakMap,tl=new WeakMap,qi=new WeakMap,Ja=new WeakMap,$i=new WeakMap,pn=new WeakMap,Xa=new WeakMap,Za=new WeakMap,Ya=new WeakMap,ji=new WeakMap,dr=new WeakSet,Yu=function(){Ge(this,Pt,this.CONNECTING),Ge(this,pn,new AbortController),ye(this,tl)(ye(this,Kn),Hr(this,dr,Of).call(this)).then(ye(this,Ju)).catch(ye(this,Zu))},Ju=new WeakMap,Zu=new WeakMap,Of=function(){var r;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...ye(this,$i)?{"Last-Event-ID":ye(this,$i)}:void 0},cache:"no-store",signal:(r=ye(this,pn))==null?void 0:r.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Qu=new WeakMap,ed=new WeakMap,Wi=function(r,e){var t;ye(this,Pt)!==this.CLOSED&&Ge(this,Pt,this.CLOSED);let a=new el("error",{code:e,message:r});(t=ye(this,Za))==null||t.call(this,a),this.dispatchEvent(a)},td=function(r,e){var t;if(ye(this,Pt)===this.CLOSED)return;Ge(this,Pt,this.CONNECTING);let a=new el("error",{code:e,message:r});(t=ye(this,Za))==null||t.call(this,a),this.dispatchEvent(a),Ge(this,Ja,setTimeout(ye(this,rd),ye(this,qi)))},rd=new WeakMap,Xn.CONNECTING=0,Xn.OPEN=1,Xn.CLOSED=2;function TC(){let r="document"in globalThis?globalThis.document:void 0;return r&&typeof r=="object"&&"baseURI"in r&&typeof r.baseURI=="string"?r.baseURI:void 0}var ad=class extends Error{constructor(e,t,a){super(`SSE error: ${t}`),this.code=e,this.event=a}},rl=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider}async _authThenStart(){var e;if(!this._authProvider)throw new Rt("No auth provider");let t;try{t=await dn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(t!=="AUTHORIZED")throw new Rt;return await this._startOrAuth()}async _commonHeaders(){var e;let t={...(e=this._requestInit)===null||e===void 0?void 0:e.headers};if(this._authProvider){let a=await this._authProvider.tokens();a&&(t.Authorization=`Bearer ${a.access_token}`)}return t}_startOrAuth(){return new Promise((e,t)=>{var a;this._eventSource=new Xn(this._url.href,(a=this._eventSourceInit)!==null&&a!==void 0?a:{fetch:(n,i)=>this._commonHeaders().then(s=>fetch(n,{...i,headers:{...s,Accept:"text/event-stream"}}))}),this._abortController=new AbortController,this._eventSource.onerror=n=>{var i;if(n.code===401&&this._authProvider){this._authThenStart().then(e,t);return}let s=new ad(n.code,n.message,n);t(s),(i=this.onerror)===null||i===void 0||i.call(this,s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",n=>{var i;let s=n;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(o){t(o),(i=this.onerror)===null||i===void 0||i.call(this,o),this.close();return}e()}),this._eventSource.onmessage=n=>{var i,s;let o=n,l;try{l=$a.parse(JSON.parse(o.data))}catch(c){(i=this.onerror)===null||i===void 0||i.call(this,c);return}(s=this.onmessage)===null||s===void 0||s.call(this,l)}})}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 Rt("No auth provider");if(await dn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new Rt("Failed to authorize")}async close(){var e,t,a;(e=this._abortController)===null||e===void 0||e.abort(),(t=this._eventSource)===null||t===void 0||t.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(e){var t,a,n;if(!this._endpoint)throw new Error("Not connected");try{let i=await this._commonHeaders(),s=new Headers({...i,...(t=this._requestInit)===null||t===void 0?void 0:t.headers});s.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},l=await fetch(this._endpoint,o);if(!l.ok){if(l.status===401&&this._authProvider){if(this._resourceMetadataUrl=Ko(l),await dn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new Rt;return this.send(e)}let c=await l.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}}catch(i){throw(n=this.onerror)===null||n===void 0||n.call(this,i),i}}};var Vr={name:"@intelliweave/embedded",version:"1.9.67",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.12.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 rt=new ge("MCPKnowledgeClient"),nl=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(){rt.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new Hi({name:Vr.name,version:Vr.version}),a=new Zo(new URL(this.config.baseURL));return await t.connect(a),rt.debug("Connected with HTTP streaming mode"),t}).catch(async t=>{let a=new Hi({name:Vr.name,version:Vr.version}),n=new rl(new URL(this.config.baseURL));return await a.connect(n),rt.debug("Connected with SSE mode"),a});return await this.disconnect(),this.client=e,e.onerror=t=>{rt.error(`MCP client error: ${t.message}`)},e.onclose=()=>{rt.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(vu,t=>{t.params.level=="critical"?rt.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?rt.error(`[Server] ${t.params.data}`):t.params.level=="error"?rt.error(`[Server] ${t.params.data}`):t.params.level=="warning"?rt.warn(`[Server] ${t.params.data}`):t.params.level=="info"?rt.info(`[Server] ${t.params.data}`):t.params.level=="debug"?rt.debug(`[Server] ${t.params.data}`):rt.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(bu,t=>{rt.debug("Tool list changed",t),this.fetchTools()}),rt.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],t;for(;;){let n=await this.client.listTools({cursor:t});t=n.nextCursor;for(let i of n.tools||[])e.push(i);if(!n?.tools?.length||!t)break}let a=[];for(let n of e){let i=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);a.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:s=>this.performToolCall(n.name,s),disabled:i})}rt.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=a}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),a=await this.performSearchCall(e);return t=t.concat(a),this.lastSearchQuery=e,this.lastSearchResults=t,rt.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let a=this.tools.find(i=>i.name==this.config.searchToolName);if(!a)return rt.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let n;if(a.inputSchema.required?.length==1){let i=a.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[i]:e})}else if(a.inputSchema.properties&&Object.keys(a.inputSchema.properties).length==1){let i=Object.keys(a.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[i]:e})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let i=0;i<n.length;i++){let s=n[i];t.push({id:this.config.id+":"+this.config.searchToolName+":"+i,name:`Search result ${i+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else t.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 t}async performToolCall(e,t){await this.connect(),rt.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let a=await this.client.callTool({name:e,arguments:t});if(a.isError){let n=a.content?.[0]?.text||"Unknown error";throw rt.error(`Error calling tool ${e}: ${n}`),new Error(`Error calling tool ${e}: ${n}`)}if(Array.isArray(a.content)&&a.content.length==1&&a.content[0].type=="text")try{return JSON.parse(a.content[0].text)}catch{}return a.content||[]}};var IC=new ge("Statistics"),Ki=[];async function Et(r,e){let t={...e,event_id:$t(),event_date:new Date().toISOString(),sdk_version:Vr.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(Ki.push(t),!r||(await new Promise(n=>setTimeout(n,5e3)),Ki.length===0))return;let a=Ki.slice();Ki.length=0;try{let n=await fetch(r.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:a})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){IC.warn("Failed to submit analytics event:",n),Ki.push(...a);return}}var Yn=new ge("KnowledgeBase"),id=1,al=class r{constructor(e){this._sources=[{id:"core.internal",query:async()=>Zm}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,t){let a=e;return typeof e=="function"&&(t=e,a=`source.${id++}`),this._sources.push({id:a,query:t}),a}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return Be().knowledgeBaseSources&&(e=e.concat(Be().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(t=>!t.disabled),e}async search(e){let t=Date.now();Yn.debug(`Searching knowledge base for: ${e}`);let a=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});a.query=e,a.entries=[],a.sources=[],typeof document<"u"&&document.dispatchEvent(a),this._windowSources=a.sources;let i=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),p=await c.query(e);return Yn.debug(`Source '${c.id}' took ${Date.now()-u}ms`),p||[]}catch(u){return Yn.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();i=i.concat(a.entries),i=i.concat(this.manualEntries),Be().knowledgeBase&&(i=i.concat(Be().knowledgeBase)),i=i.filter(c=>c&&!c.disabled);for(let c=0;c<i.length;c++){let u=i[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!u.action&&u.type=="tour"&&(u.action=p=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!u.action&&u.type=="info"&&(u.action=p=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let s=new Jm({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(i);let l=s.search(e).map(c=>i.find(u=>u.id==c.id));for(let c of i)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Et(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),Yn.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${id++}`),Yn.debug(`Registering remote knowledge base source: ${e}`);let a=[],n=[],i=!0,s=async(l,c)=>{Yn.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:c},p=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw new Error(`HTTP Error ${p.status} ${p.statusText}`);let m=await p.json();return o(m.updateItems||[]),m.response},o=l=>{for(let c of l){if(!c.id){Yn.warn("KB item skipped since it has no ID.",c);continue}let u=a.find(p=>p.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}a.push({...c,action:p=>s(c,p)})}};this.registerSource(t,async l=>{if(i&&n.includes(l))return a;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},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 p=await u.json();return i=!p.noCache,n.includes(l)||n.push(l),o(p.items),a})}clone(){let e=new r(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${id++}`);let t=new nl(e);return this.registerSource(e.id,a=>t.search(a)),t}};var il=class{constructor(e){this.ai=e}async boolean(e){let t=await this.instruct({...e,instruction:`${e.instruction}
|
|
3282
3282
|
|
|
3283
3283
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(t.toLowerCase().includes("true"))return!0;if(t.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+t)}async choose(e){let t=await this.instruct({...e,instruction:`${e.instruction}
|
|
3284
3284
|
|
package/dist/webpack/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import{v4 as Ze}from"uuid";function ge(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 ke(){if(m().userID)return m().userID||"";if(typeof localStorage<"u"){let r=localStorage.getItem("intelliweave.uid")||"";return r||(r=Ze(),localStorage.setItem("intelliweave.uid",r),r)}else return Ze()}function Ie(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 F=class F{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return F.debug?!0:typeof window<"u"&&m().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)}};F.debug=!1;var p=F;var T=new p("ONNXModel"),w=class r{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,T.debug(`Model input parameters: ${i.inputNames.join(", ")}`),T.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||(T.debug("Loading ONNX runtime"),this.onnx=await r.lib()),T.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 T.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(){T.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var Te="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3IoO3IhPXQubGVuZ3RoOyl7aWYocj50Lmxlbmd0aCl0a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J1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var He=new p("PCMPlayerNode"),z=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})}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){He.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 p("SpeechOutput"),Me=.5,Oe=.8,Y=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-${Ue++}`;await this.ai.audio.beginAccess(t);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(t)}}async _speakWithLock(e){this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Oe);let t=this.ai?._voiceTracker||J.timer(`${this.ai.config.voice.providerID} voice`);t(`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 s=new z(this.ai.audio.context,24e3,"int16");this.currentPlayer=s,s.connect(this.analyserNode),s.addEventListener("end",o=>{let a=o;t(`PCM stream ${a.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==s&&!a.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let n;if(this.ai.config.voice.providerID=="openai")n=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")n=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(t(`Received response ${n.status} ${n.statusText}`),!n.ok){J.warn(`Failed to generate voice sample: ${n.status} ${n.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),t("Playing PCM stream"),await s.play(n.body),t("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=Me);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=Me)}},Ue=1;function H(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 O=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})}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 fe=16e3,U=256,W=8,L=new p("VoiceDetectionNode"),B=class B extends O{constructor(e){super(e,fe,"float32",U*W);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(!B.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 fe}get numberOfSamples(){return U}get numberOfSampleChunks(){return W}get outputBufferSize(){return U*W}get isModelLoaded(){return!!this.vad}async loadModel(){L.debug("Loading VAD model"),this.vad=await w.load(B.vadModelURL),this.vad.ignoreIfBusy=!0,L.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],fe),this.vad.makeState("h","hn","float32",[2,W,64]),this.vad.makeState("c","cn","float32",[2,W,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new w.onnx.Tensor(e,[W,U])});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(),L.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(),L.debug("Stopped speaking after timeout")),!n){let o=Date.now();o>this.nextVadReset&&(this.nextVadReset=o+5e3,this.vad.resetState())}}catch(t){L.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};B.vadModelURL="";var M=B;var Xe=new p("VoiceChunkOutputNode"),X=class extends M{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){Xe.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);Xe.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 j=new p("OpenAITranscriptionNode"),$=class extends X{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=j.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=H(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){j.error(`Failed to transcribe speech: ${o.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return j.debug("Transcription complete, but no text was found");j.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 v=new p("IntelliWeaveTranscriptionNode"),je="wss://speech.intelliweave.ai/api/v1/transcribe",ee=class ee extends X{constructor(e,t){super(e);this.apiAddress=je;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(v.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=()=>{v.debug("WebSocket connection opened")},this.ws.addEventListener("message",s=>{let n=JSON.parse(s.data);if(n.error)return v.warn("Error: "+n.error);if(n.type!="transcription")return v.warn("Invalid response type",n);if(n.streaming&&!n.final)return v.debug("Partial transcription: "+n.partialText);if(this.isTranscribing=!1,!n.text.trim())return v.warn(`Empty transcription (${n.processingTime}ms)`);v.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=>v.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{v.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),ee.debugExportWav){let t=H(this.sampleRate,e),s=document.createElement("a");s.href=URL.createObjectURL(t),s.download="recording.wav",s.click()}}onVoiceTranscription(e){}onSocketClose(){v.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};ee.debugExportWav=!1;var q=ee;var x={name:"@intelliweave/embedded",version:"1.9.66",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.12.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 Qe}from"uuid";var qe=new p("Statistics"),P=[];async function f(r,i){let e={...i,event_id:Qe(),event_date:new Date().toISOString(),sdk_version:x.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(P.push(e),!r||(await new Promise(s=>setTimeout(s,5e3)),P.length===0))return;let t=P.slice();P.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){qe.warn("Failed to submit analytics event:",s),P.push(...t);return}}var ye=new p("SpeechRecognition"),te=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(!w.lib||!this.ai?.vadModel||!Z().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))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),M.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new $(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new q(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=ye.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){ye.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;ye.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 ie=new p("AudioSystem"),C=class{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 te(this.ai),this.speechOutput=new Y(this.ai)}static get isSupported(){return!(!w.lib||!Z().AudioWorkletNode)}async beginAccess(i){ie.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(ie.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await Promise.all([this.context.audioWorklet.addModule(Te),this.context.audioWorklet.addModule(We)]))}endAccess(i){ie.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(ie.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var Ee=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 Re=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,G,K;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,G=0,K=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-K,a>=c){for(l=0;l<n;++l)s[l]+=i[d++]*c;K=d,a-=c}else{for(l=0;l<n;++l)s[l]+=i[d+(l>0?l:0)]*a;K+=a,a=0;break}if(a===0)for(l=0;l<n;++l)h[G++]=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&&G<t);return this.bufferSlice(G)}}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 xi(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 Si(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 Gi(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 tt}from"gpt-tokenizer";import{countTokens as se}from"gpt-tokenizer";import{v4 as et}from"uuid";var ne=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new ve;return e.id=i,this.groups.push(e),e}group(i){return this.groups.find(e=>e.id===i)}countTokens(){return this.groups.reduce((i,e)=>i+e.tokenCount,0)}removeOverflow(){let i=this.countTokens(),e=this.groups.reduce((t,s)=>t+s.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((n,o)=>{let 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}},ve=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
9
|
+
`,yield*e()}function ke(){if(m().userID)return m().userID||"";if(typeof localStorage<"u"){let r=localStorage.getItem("intelliweave.uid")||"";return r||(r=Ze(),localStorage.setItem("intelliweave.uid",r),r)}else return Ze()}function Ie(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 F=class F{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return F.debug?!0:typeof window<"u"&&m().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)}};F.debug=!1;var p=F;var T=new p("ONNXModel"),w=class r{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,T.debug(`Model input parameters: ${i.inputNames.join(", ")}`),T.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||(T.debug("Loading ONNX runtime"),this.onnx=await r.lib()),T.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 T.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(){T.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var Te="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3Ms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pO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var He=new p("PCMPlayerNode"),z=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})}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){He.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 p("SpeechOutput"),Me=.5,Oe=.8,Y=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-${Ue++}`;await this.ai.audio.beginAccess(t);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(t)}}async _speakWithLock(e){this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Oe);let t=this.ai?._voiceTracker||J.timer(`${this.ai.config.voice.providerID} voice`);t(`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 s=new z(this.ai.audio.context,24e3,"int16");this.currentPlayer=s,s.connect(this.analyserNode),s.addEventListener("end",o=>{let a=o;t(`PCM stream ${a.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==s&&!a.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let n;if(this.ai.config.voice.providerID=="openai")n=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")n=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(t(`Received response ${n.status} ${n.statusText}`),!n.ok){J.warn(`Failed to generate voice sample: ${n.status} ${n.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),t("Playing PCM stream"),await s.play(n.body),t("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=Me);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=Me)}},Ue=1;function H(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 O=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})}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 fe=16e3,U=256,W=8,L=new p("VoiceDetectionNode"),B=class B extends O{constructor(e){super(e,fe,"float32",U*W);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(!B.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 fe}get numberOfSamples(){return U}get numberOfSampleChunks(){return W}get outputBufferSize(){return U*W}get isModelLoaded(){return!!this.vad}async loadModel(){L.debug("Loading VAD model"),this.vad=await w.load(B.vadModelURL),this.vad.ignoreIfBusy=!0,L.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],fe),this.vad.makeState("h","hn","float32",[2,W,64]),this.vad.makeState("c","cn","float32",[2,W,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new w.onnx.Tensor(e,[W,U])});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(),L.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(),L.debug("Stopped speaking after timeout")),!n){let o=Date.now();o>this.nextVadReset&&(this.nextVadReset=o+5e3,this.vad.resetState())}}catch(t){L.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};B.vadModelURL="";var M=B;var Xe=new p("VoiceChunkOutputNode"),X=class extends M{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){Xe.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);Xe.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 j=new p("OpenAITranscriptionNode"),$=class extends X{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=j.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=H(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){j.error(`Failed to transcribe speech: ${o.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return j.debug("Transcription complete, but no text was found");j.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 v=new p("IntelliWeaveTranscriptionNode"),je="wss://speech.intelliweave.ai/api/v1/transcribe",ee=class ee extends X{constructor(e,t){super(e);this.apiAddress=je;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(v.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=()=>{v.debug("WebSocket connection opened")},this.ws.addEventListener("message",s=>{let n=JSON.parse(s.data);if(n.error)return v.warn("Error: "+n.error);if(n.type!="transcription")return v.warn("Invalid response type",n);if(n.streaming&&!n.final)return v.debug("Partial transcription: "+n.partialText);if(this.isTranscribing=!1,!n.text.trim())return v.warn(`Empty transcription (${n.processingTime}ms)`);v.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=>v.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{v.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),ee.debugExportWav){let t=H(this.sampleRate,e),s=document.createElement("a");s.href=URL.createObjectURL(t),s.download="recording.wav",s.click()}}onVoiceTranscription(e){}onSocketClose(){v.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};ee.debugExportWav=!1;var q=ee;var x={name:"@intelliweave/embedded",version:"1.9.67",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.12.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 Qe}from"uuid";var qe=new p("Statistics"),P=[];async function f(r,i){let e={...i,event_id:Qe(),event_date:new Date().toISOString(),sdk_version:x.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(P.push(e),!r||(await new Promise(s=>setTimeout(s,5e3)),P.length===0))return;let t=P.slice();P.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){qe.warn("Failed to submit analytics event:",s),P.push(...t);return}}var ye=new p("SpeechRecognition"),te=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(!w.lib||!this.ai?.vadModel||!Z().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))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),M.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new $(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new q(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=ye.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){ye.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;ye.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 ie=new p("AudioSystem"),C=class{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 te(this.ai),this.speechOutput=new Y(this.ai)}static get isSupported(){return!(!w.lib||!Z().AudioWorkletNode)}async beginAccess(i){ie.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(ie.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await Promise.all([this.context.audioWorklet.addModule(Te),this.context.audioWorklet.addModule(We)]))}endAccess(i){ie.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(ie.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var Ee=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 Re=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,G,K;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,G=0,K=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-K,a>=c){for(l=0;l<n;++l)s[l]+=i[d++]*c;K=d,a-=c}else{for(l=0;l<n;++l)s[l]+=i[d+(l>0?l:0)]*a;K+=a,a=0;break}if(a===0)for(l=0;l<n;++l)h[G++]=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&&G<t);return this.bufferSlice(G)}}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 xi(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 Si(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 Gi(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 tt}from"gpt-tokenizer";import{countTokens as se}from"gpt-tokenizer";import{v4 as et}from"uuid";var ne=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new ve;return e.id=i,this.groups.push(e),e}group(i){return this.groups.find(e=>e.id===i)}countTokens(){return this.groups.reduce((i,e)=>i+e.tokenCount,0)}removeOverflow(){let i=this.countTokens(),e=this.groups.reduce((t,s)=>t+s.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((n,o)=>{let 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}},ve=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=se(e.content)+se(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=et());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:se(i.content)+se(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 E=class{constructor(i){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let i=new ne;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)})}};var R=1,S=new p("ChatGPT"),oe=class extends E{async sendMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+R++,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-"+R++,content:JSON.stringify(e),customData:e})}addUserMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+R++,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 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}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 l=a.customData;l.description&&l.description.length>1024&&S.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 Ce(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=tt(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-"+R++,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-"+R++,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-"+R++,content:JSON.stringify(t),customData:t})}}};import it from"@anthropic-ai/sdk";var re=1,ae=new p("AnthropicChat"),le=class extends E{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 it({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(),ae.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(G=>G.customData),tools:o,stream:!0});h.on("text",G=>{n+=G,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});ae.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"?ae.debug(`AI is thinking: ${h.thinking}`):h.type=="text"?s+=h.text||`
|