@intelliweave/embedded 1.9.65-beta.0 → 1.9.66

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.65-beta.0",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.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}
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.65-beta.0",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.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}
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
 
@@ -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.65-beta.0",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.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}
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