@intelliweave/embedded 2.2.83 → 2.2.84

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.
@@ -110,7 +110,7 @@ ${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"ope
110
110
  `;break;case"id":a=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new yb(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:g}));break;default:r(new yb(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:y,line:g}));break}}function p(){l.length>0&&e({id:a,event:c||void 0,data:l.endsWith(`
111
111
  `)?l.slice(0,-1):l}),a=void 0,l="",c=""}function m(h={}){o&&h.consume&&d(o),s=!0,a=void 0,l="",c="",o=""}return{feed:u,reset:m}}function p7(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
112
112
  `,n),s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?s=i:o!==-1&&(s=o),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
113
- `&&n++}}return[e,r]}var bb=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=Mj({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var f7={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ns=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},vb=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=wj(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??f7}async _authThenStart(){if(!this._authProvider)throw new zo("No auth provider");let e;try{e=await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new zo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=gb(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let i=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Ns(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},i)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new bb({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:m}=await u.read();if(m)break;if(p.id&&(s=p.id,a=!0,i?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let h=Zg.parse(JSON.parse(p.data));Ra(h)&&(l=!0,o!==void 0&&(h.id=o)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new zo("No auth provider");if(await lm(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:i}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Mp(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,s),l=a.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ns(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:p,scope:m}=SI(a);if(this._resourceMetadataUrl=p,this._scope=m,await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zo;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:p,scope:m,error:h}=SI(a);if(h==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Ns(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=y??void 0,await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new zo;return this.send(e)}}throw new Ns(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),sz(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let u=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:i},!1);else if(d?.includes("application/json")){let f=await a.json(),p=Array.isArray(f)?f.map(m=>Zg.parse(m)):[Zg.parse(f)];for(let m of p)this.onmessage?.(m)}else throw await a.body?.cancel(),new Ns(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Ns(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Os={name:"@intelliweave/embedded",version:"2.2.83",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};var ur=new Oe("MCPKnowledgeClient"),h7="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",_b=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){ur.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=r.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",r=new URL(this.config.proxy.url||h7));let i=new hb({name:Os.name,version:Os.version}),o=new vb(r,{requestInit:{headers:n}});return await i.connect(o),ur.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=e,e.onerror=r=>{ur.error(`MCP client error: ${r.message}`)},e.onclose=()=>{ur.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(U0,r=>{r.params.level=="critical"?ur.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?ur.error(`[Server] ${r.params.data}`):r.params.level=="error"?ur.error(`[Server] ${r.params.data}`):r.params.level=="warning"?ur.warn(`[Server] ${r.params.data}`):r.params.level=="info"?ur.info(`[Server] ${r.params.data}`):r.params.level=="debug"?ur.debug(`[Server] ${r.params.data}`):ur.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Vp,r=>{ur.debug("Tool list changed",r),this.fetchTools()}),ur.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let o=await this.client.listTools({cursor:r});r=o.nextCursor;for(let s of o.tools||[])e.push(s);if(!o?.tools?.length||!r)break}let n=[],i=this.config.id||"mcp";for(let o of e){let s=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),a=`${i}_${o.name}`;n.push({id:a,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:s})}ur.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,ur.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return ur.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else r.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return r}async performToolCall(e,r){await this.connect(),ur.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw ur.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var g7=new Oe("Statistics"),cm=[];async function Hr(t,e){let r={...e,event_id:hr(),event_date:new Date().toISOString(),sdk_version:Os.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(cm.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),cm.length===0))return;let n=cm.slice();cm.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){g7.warn("Failed to submit analytics event:",i),cm.push(...n);return}}var Rs=new Oe("KnowledgeBase"),y7=8*1024,EI=1,wb=class t{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>zT(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${EI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&Et().knowledgeBaseSources&&(e=e.concat(Et().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Rs.debug(`Searching knowledge base for: ${e}`);let r=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async d=>{try{let f=Date.now(),p=await d.query(e);return Rs.debug(`Source '${d.id}' took ${Date.now()-f}ms`),p||[]}catch(f){return Rs.warn(`Knowledge source '${d.id}' failed:`,f),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&Et().knowledgeBase&&(o=o.concat(Et().knowledgeBase)),o=o.filter(d=>d&&!d.disabled);let s=new Map;for(let d of o)d.id&&s.set(d.id,(s.get(d.id)||0)+1);for(let[d,f]of s)if(f>1){Rs.warn(`Duplicate knowledge base item ID detected: '${d}' appears ${f} times. Adding suffixes to make them unique.`);let p=1,m=!0;for(let h of o)if(h.id===d){if(m){m=!1;continue}h.id=`${d}(${p})`,p++}}for(let d=0;d<o.length;d++){let f=o[d];f.id=f.id||`temp.${d}`,f._functionID=f.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let a=new dp({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});a.addAll(o);let c=a.search(e).map(d=>o.find(f=>f.id==d.id)).filter(Boolean),u=0;c=c.filter(d=>{if(d.isContext)return!0;let f=(d.content||"").length;return u+f>y7?!1:(u+=f,!0)});for(let d of o)d.isContext&&(c.find(f=>f.id===d.id)||c.push(d));return this.lastResults=c,Hr(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Rs.debug("Found results:",c),c}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${EI++}`),Rs.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Rs.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let f=await d.json();return a(f.updateItems||[]),f.response},a=l=>{for(let c of l){if(!c.id){Rs.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(e){let r=new t(e);return r._sources=this._sources.slice(),r._windowSources=this._windowSources.slice(),r.manualEntries=this.manualEntries.slice(),r.allowGlobalConfigSources=this.allowGlobalConfigSources,r.allowWindowSources=this.allowWindowSources,r.allowRagSearch=this.allowRagSearch,r.ensureInternalKnowledge(),r}registerMCPSource(e){e.id||(e.id=`external.${EI++}`);let r=new _b(e);return this.registerSource(e.id,n=>r.search(n)),r}};var xb=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
113
+ `&&n++}}return[e,r]}var bb=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=Mj({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var f7={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ns=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},vb=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=wj(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??f7}async _authThenStart(){if(!this._authProvider)throw new zo("No auth provider");let e;try{e=await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new zo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=gb(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let i=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Ns(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},i)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new bb({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:m}=await u.read();if(m)break;if(p.id&&(s=p.id,a=!0,i?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let h=Zg.parse(JSON.parse(p.data));Ra(h)&&(l=!0,o!==void 0&&(h.id=o)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new zo("No auth provider");if(await lm(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:i}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Mp(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,s),l=a.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ns(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:p,scope:m}=SI(a);if(this._resourceMetadataUrl=p,this._scope=m,await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zo;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:p,scope:m,error:h}=SI(a);if(h==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Ns(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=y??void 0,await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new zo;return this.send(e)}}throw new Ns(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),sz(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let u=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:i},!1);else if(d?.includes("application/json")){let f=await a.json(),p=Array.isArray(f)?f.map(m=>Zg.parse(m)):[Zg.parse(f)];for(let m of p)this.onmessage?.(m)}else throw await a.body?.cancel(),new Ns(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Ns(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Os={name:"@intelliweave/embedded",version:"2.2.84",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};var ur=new Oe("MCPKnowledgeClient"),h7="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",_b=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){ur.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=r.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",r=new URL(this.config.proxy.url||h7));let i=new hb({name:Os.name,version:Os.version}),o=new vb(r,{requestInit:{headers:n}});return await i.connect(o),ur.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=e,e.onerror=r=>{ur.error(`MCP client error: ${r.message}`)},e.onclose=()=>{ur.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(U0,r=>{r.params.level=="critical"?ur.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?ur.error(`[Server] ${r.params.data}`):r.params.level=="error"?ur.error(`[Server] ${r.params.data}`):r.params.level=="warning"?ur.warn(`[Server] ${r.params.data}`):r.params.level=="info"?ur.info(`[Server] ${r.params.data}`):r.params.level=="debug"?ur.debug(`[Server] ${r.params.data}`):ur.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Vp,r=>{ur.debug("Tool list changed",r),this.fetchTools()}),ur.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let o=await this.client.listTools({cursor:r});r=o.nextCursor;for(let s of o.tools||[])e.push(s);if(!o?.tools?.length||!r)break}let n=[],i=this.config.id||"mcp";for(let o of e){let s=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),a=`${i}_${o.name}`;n.push({id:a,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:s})}ur.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,ur.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return ur.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else r.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return r}async performToolCall(e,r){await this.connect(),ur.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw ur.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var g7=new Oe("Statistics"),cm=[];async function Hr(t,e){let r={...e,event_id:hr(),event_date:new Date().toISOString(),sdk_version:Os.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(cm.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),cm.length===0))return;let n=cm.slice();cm.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){g7.warn("Failed to submit analytics event:",i),cm.push(...n);return}}var Rs=new Oe("KnowledgeBase"),y7=8*1024,EI=1,wb=class t{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>zT(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${EI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&Et().knowledgeBaseSources&&(e=e.concat(Et().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Rs.debug(`Searching knowledge base for: ${e}`);let r=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async d=>{try{let f=Date.now(),p=await d.query(e);return Rs.debug(`Source '${d.id}' took ${Date.now()-f}ms`),p||[]}catch(f){return Rs.warn(`Knowledge source '${d.id}' failed:`,f),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&Et().knowledgeBase&&(o=o.concat(Et().knowledgeBase)),o=o.filter(d=>d&&!d.disabled);let s=new Map;for(let d of o)d.id&&s.set(d.id,(s.get(d.id)||0)+1);for(let[d,f]of s)if(f>1){Rs.warn(`Duplicate knowledge base item ID detected: '${d}' appears ${f} times. Adding suffixes to make them unique.`);let p=1,m=!0;for(let h of o)if(h.id===d){if(m){m=!1;continue}h.id=`${d}(${p})`,p++}}for(let d=0;d<o.length;d++){let f=o[d];f.id=f.id||`temp.${d}`,f._functionID=f.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let a=new dp({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});a.addAll(o);let c=a.search(e).map(d=>o.find(f=>f.id==d.id)).filter(Boolean),u=0;c=c.filter(d=>{if(d.isContext)return!0;let f=(d.content||"").length;return u+f>y7?!1:(u+=f,!0)});for(let d of o)d.isContext&&(c.find(f=>f.id===d.id)||c.push(d));return this.lastResults=c,Hr(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Rs.debug("Found results:",c),c}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${EI++}`),Rs.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Rs.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let f=await d.json();return a(f.updateItems||[]),f.response},a=l=>{for(let c of l){if(!c.id){Rs.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(e){let r=new t(e);return r._sources=this._sources.slice(),r._windowSources=this._windowSources.slice(),r.manualEntries=this.manualEntries.slice(),r.allowGlobalConfigSources=this.allowGlobalConfigSources,r.allowWindowSources=this.allowWindowSources,r.allowRagSearch=this.allowRagSearch,r.ensureInternalKnowledge(),r}registerMCPSource(e){e.id||(e.id=`external.${EI++}`);let r=new _b(e);return this.registerSource(e.id,n=>r.search(n)),r}};var xb=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
114
114
 
115
115
  Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(r.toLowerCase().includes("true"))return!0;if(r.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+r)}async choose(e){let r=await this.instruct({...e,instruction:`${e.instruction}
116
116
 
@@ -1416,6 +1416,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
1416
1416
  flex-direction: unset;
1417
1417
  gap: 10px;
1418
1418
  }
1419
+
1419
1420
  #root.container-mode #web-weaver-embed-inner {
1420
1421
  flex: 1 1 auto;
1421
1422
  min-height: 0;
@@ -1687,6 +1688,21 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
1687
1688
  overflow: hidden;
1688
1689
  text-overflow: ellipsis;
1689
1690
  }
1691
+ #root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner {
1692
+ flex: 1 1 auto;
1693
+ min-height: 0;
1694
+ max-height: none;
1695
+ height: auto;
1696
+ overflow-x: hidden;
1697
+ overflow-y: auto;
1698
+ width: 100%;
1699
+ max-width: none;
1700
+ margin: 2px;
1701
+ padding: 12px;
1702
+ align-content: start;
1703
+ flex-direction: unset;
1704
+ gap: 10px;
1705
+ }
1690
1706
  }
1691
1707
 
1692
1708
  </style>
Binary file
package/dist/node/node.js CHANGED
@@ -18,7 +18,7 @@ New information found:
18
18
  ${o}
19
19
 
20
20
  New tools available:
21
- ${r}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let n=new URL(e.path,window.location.origin).pathname;return window.location.href=n,`Changed route to: ${n}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let n=encodeURIComponent(e.email_address),s=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),r=`mailto:${n}?subject=${s}&body=${o}`;try{window.location.href=r}catch(c){throw new Error(`Failed to open email client: ${c instanceof Error?c.message:String(c)}`)}return`Email opened in default mail client. Recipient: ${e.email_address}, Subject: ${e.subject}`}}];import{Client as de}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as pe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var v={name:"@intelliweave/embedded",version:"2.2.83",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{LoggingMessageNotificationSchema as he,ToolListChangedNotificationSchema as ge}from"@modelcontextprotocol/sdk/types.js";var m=new g("MCPKnowledgeClient"),me="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",W=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){m.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=t.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",t=new URL(this.config.proxy.url||me));let s=new de({name:v.name,version:v.version}),o=new pe(t,{requestInit:{headers:n}});return await s.connect(o),m.debug("Connected with HTTP streaming mode"),s});return await this.disconnect(),this.client=e,e.onerror=t=>{m.error(`MCP client error: ${t.message}`)},e.onclose=()=>{m.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(he,t=>{t.params.level=="critical"?m.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?m.error(`[Server] ${t.params.data}`):t.params.level=="error"?m.error(`[Server] ${t.params.data}`):t.params.level=="warning"?m.warn(`[Server] ${t.params.data}`):t.params.level=="info"?m.info(`[Server] ${t.params.data}`):t.params.level=="debug"?m.debug(`[Server] ${t.params.data}`):m.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(ge,t=>{m.debug("Tool list changed",t),this.fetchTools()}),m.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],t;for(;;){let o=await this.client.listTools({cursor:t});t=o.nextCursor;for(let r of o.tools||[])e.push(r);if(!o?.tools?.length||!t)break}let n=[],s=this.config.id||"mcp";for(let o of e){let r=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),c=`${s}_${o.name}`;n.push({id:c,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:r})}m.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),n=await this.performSearchCall(e);return t=t.concat(n),this.lastSearchQuery=e,this.lastSearchResults=t,m.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return m.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let s;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[o]:e})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let o=0;o<s.length;o++){let r=s[o];t.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof r=="string"?r:JSON.stringify(r)})}else t.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return t}async performToolCall(e,t){await this.connect(),m.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:t});if(n.isError){let s=n.content?.[0]?.text||"Unknown error";throw m.error(`Error calling tool ${e}: ${s}`),new Error(`Error calling tool ${e}: ${s}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};import{v4 as fe}from"uuid";var we=new g("Statistics"),E=[];async function I(u,e){let t={...e,event_id:fe(),event_date:new Date().toISOString(),sdk_version:v.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(E.push(t),!u||(await new Promise(s=>setTimeout(s,5e3)),E.length===0))return;let n=E.slice();E.length=0;try{let s=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){we.warn("Failed to submit analytics event:",s),E.push(...n);return}}var k=new g("KnowledgeBase"),be=8*1024,L=1,O=class u{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>Q(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,t){let n=e;return typeof e=="function"&&(t=e,n=`source.${L++}`),this._sources.push({id:n,query:t}),n}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&y().knowledgeBaseSources&&(e=e.concat(y().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(t=>!t.disabled),e}async search(e){k.debug(`Searching knowledge base for: ${e}`);let t=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async i=>{try{let p=Date.now(),h=await i.query(e);return k.debug(`Source '${i.id}' took ${Date.now()-p}ms`),h||[]}catch(p){return k.warn(`Knowledge source '${i.id}' failed:`,p),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&y().knowledgeBase&&(o=o.concat(y().knowledgeBase)),o=o.filter(i=>i&&!i.disabled);let r=new Map;for(let i of o)i.id&&r.set(i.id,(r.get(i.id)||0)+1);for(let[i,p]of r)if(p>1){k.warn(`Duplicate knowledge base item ID detected: '${i}' appears ${p} times. Adding suffixes to make them unique.`);let h=1,f=!0;for(let S of o)if(S.id===i){if(f){f=!1;continue}S.id=`${i}(${h})`,h++}}for(let i=0;i<o.length;i++){let p=o[i];p.id=p.id||`temp.${i}`,p._functionID=p.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let c=new ye({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});c.addAll(o);let d=c.search(e).map(i=>o.find(p=>p.id==i.id)).filter(Boolean),a=0;d=d.filter(i=>{if(i.isContext)return!0;let p=(i.content||"").length;return a+p>be?!1:(a+=p,!0)});for(let i of o)i.isContext&&(d.find(p=>p.id===i.id)||d.push(i));return this.lastResults=d,I(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),k.debug("Found results:",d),d}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${L++}`),k.debug(`Registering remote knowledge base source: ${e}`);let n=[],s=[],o=!0,r=async(l,d)=>{k.debug(`Calling remote knowledge base action: ${l.id}`);let a={type:"action",userID:this.ai.userID,actionID:l.id,parameters:d},i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let p=await i.json();return c(p.updateItems||[]),p.response},c=l=>{for(let d of l){if(!d.id){k.warn("KB item skipped since it has no ID.",d);continue}let a=n.find(i=>i.id==d.id);if(a){a.name=d.name||a.name||"",a.content=d.content||a.content||"",a.disabled=d.disabled??a.disabled,a.isContext=d.isContext??a.isContext,a.parameters=d.parameters||a.parameters||[],a.tags=d.tags||a.tags,a.type=d.type||a.type;continue}n.push({...d,action:i=>r(d,i)})}};this.registerSource(t,async l=>{if(o&&s.includes(l))return n;let d={type:"search",userID:this.ai?.userID||"",query:l},a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let i=await a.json();return o=!i.noCache,s.includes(l)||s.push(l),c(i.items),n})}clone(e){let t=new u(e);return t._sources=this._sources.slice(),t._windowSources=this._windowSources.slice(),t.manualEntries=this.manualEntries.slice(),t.allowGlobalConfigSources=this.allowGlobalConfigSources,t.allowWindowSources=this.allowWindowSources,t.allowRagSearch=this.allowRagSearch,t.ensureInternalKnowledge(),t}registerMCPSource(e){e.id||(e.id=`external.${L++}`);let t=new W(e);return this.registerSource(e.id,n=>t.search(n)),t}};function ve(u){let e="",t=[],n=0;for(;n<u.length;){let s=u.indexOf("<[[",n);if(s===-1){e+=u.slice(n);break}e+=u.slice(n,s);let o=u.indexOf("]]>",s+3);if(o===-1)break;let r=u.slice(s,o+3),c=u.slice(s+3,o).trim(),l={raw:r,content:c};try{let d=JSON.parse(c);d&&typeof d=="object"&&!Array.isArray(d)&&(l.action=d)}catch{}t.push(l),n=o+3}return{visibleText:e,actions:t.flatMap(s=>s.action?[s.action]:[]),blocks:t}}function Z(u){return ve(u).visibleText}var R=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>Z(e?.text||""))?.filter(e=>!!e)?.join(`
21
+ ${r}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let n=new URL(e.path,window.location.origin).pathname;return window.location.href=n,`Changed route to: ${n}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let n=encodeURIComponent(e.email_address),s=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),r=`mailto:${n}?subject=${s}&body=${o}`;try{window.location.href=r}catch(c){throw new Error(`Failed to open email client: ${c instanceof Error?c.message:String(c)}`)}return`Email opened in default mail client. Recipient: ${e.email_address}, Subject: ${e.subject}`}}];import{Client as de}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as pe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var v={name:"@intelliweave/embedded",version:"2.2.84",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{LoggingMessageNotificationSchema as he,ToolListChangedNotificationSchema as ge}from"@modelcontextprotocol/sdk/types.js";var m=new g("MCPKnowledgeClient"),me="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",W=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){m.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=t.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",t=new URL(this.config.proxy.url||me));let s=new de({name:v.name,version:v.version}),o=new pe(t,{requestInit:{headers:n}});return await s.connect(o),m.debug("Connected with HTTP streaming mode"),s});return await this.disconnect(),this.client=e,e.onerror=t=>{m.error(`MCP client error: ${t.message}`)},e.onclose=()=>{m.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(he,t=>{t.params.level=="critical"?m.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?m.error(`[Server] ${t.params.data}`):t.params.level=="error"?m.error(`[Server] ${t.params.data}`):t.params.level=="warning"?m.warn(`[Server] ${t.params.data}`):t.params.level=="info"?m.info(`[Server] ${t.params.data}`):t.params.level=="debug"?m.debug(`[Server] ${t.params.data}`):m.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(ge,t=>{m.debug("Tool list changed",t),this.fetchTools()}),m.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],t;for(;;){let o=await this.client.listTools({cursor:t});t=o.nextCursor;for(let r of o.tools||[])e.push(r);if(!o?.tools?.length||!t)break}let n=[],s=this.config.id||"mcp";for(let o of e){let r=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),c=`${s}_${o.name}`;n.push({id:c,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:r})}m.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),n=await this.performSearchCall(e);return t=t.concat(n),this.lastSearchQuery=e,this.lastSearchResults=t,m.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return m.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let s;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[o]:e})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let o=0;o<s.length;o++){let r=s[o];t.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof r=="string"?r:JSON.stringify(r)})}else t.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return t}async performToolCall(e,t){await this.connect(),m.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:t});if(n.isError){let s=n.content?.[0]?.text||"Unknown error";throw m.error(`Error calling tool ${e}: ${s}`),new Error(`Error calling tool ${e}: ${s}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};import{v4 as fe}from"uuid";var we=new g("Statistics"),E=[];async function I(u,e){let t={...e,event_id:fe(),event_date:new Date().toISOString(),sdk_version:v.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(E.push(t),!u||(await new Promise(s=>setTimeout(s,5e3)),E.length===0))return;let n=E.slice();E.length=0;try{let s=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){we.warn("Failed to submit analytics event:",s),E.push(...n);return}}var k=new g("KnowledgeBase"),be=8*1024,L=1,O=class u{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>Q(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,t){let n=e;return typeof e=="function"&&(t=e,n=`source.${L++}`),this._sources.push({id:n,query:t}),n}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&y().knowledgeBaseSources&&(e=e.concat(y().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(t=>!t.disabled),e}async search(e){k.debug(`Searching knowledge base for: ${e}`);let t=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async i=>{try{let p=Date.now(),h=await i.query(e);return k.debug(`Source '${i.id}' took ${Date.now()-p}ms`),h||[]}catch(p){return k.warn(`Knowledge source '${i.id}' failed:`,p),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&y().knowledgeBase&&(o=o.concat(y().knowledgeBase)),o=o.filter(i=>i&&!i.disabled);let r=new Map;for(let i of o)i.id&&r.set(i.id,(r.get(i.id)||0)+1);for(let[i,p]of r)if(p>1){k.warn(`Duplicate knowledge base item ID detected: '${i}' appears ${p} times. Adding suffixes to make them unique.`);let h=1,f=!0;for(let S of o)if(S.id===i){if(f){f=!1;continue}S.id=`${i}(${h})`,h++}}for(let i=0;i<o.length;i++){let p=o[i];p.id=p.id||`temp.${i}`,p._functionID=p.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let c=new ye({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});c.addAll(o);let d=c.search(e).map(i=>o.find(p=>p.id==i.id)).filter(Boolean),a=0;d=d.filter(i=>{if(i.isContext)return!0;let p=(i.content||"").length;return a+p>be?!1:(a+=p,!0)});for(let i of o)i.isContext&&(d.find(p=>p.id===i.id)||d.push(i));return this.lastResults=d,I(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),k.debug("Found results:",d),d}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${L++}`),k.debug(`Registering remote knowledge base source: ${e}`);let n=[],s=[],o=!0,r=async(l,d)=>{k.debug(`Calling remote knowledge base action: ${l.id}`);let a={type:"action",userID:this.ai.userID,actionID:l.id,parameters:d},i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let p=await i.json();return c(p.updateItems||[]),p.response},c=l=>{for(let d of l){if(!d.id){k.warn("KB item skipped since it has no ID.",d);continue}let a=n.find(i=>i.id==d.id);if(a){a.name=d.name||a.name||"",a.content=d.content||a.content||"",a.disabled=d.disabled??a.disabled,a.isContext=d.isContext??a.isContext,a.parameters=d.parameters||a.parameters||[],a.tags=d.tags||a.tags,a.type=d.type||a.type;continue}n.push({...d,action:i=>r(d,i)})}};this.registerSource(t,async l=>{if(o&&s.includes(l))return n;let d={type:"search",userID:this.ai?.userID||"",query:l},a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let i=await a.json();return o=!i.noCache,s.includes(l)||s.push(l),c(i.items),n})}clone(e){let t=new u(e);return t._sources=this._sources.slice(),t._windowSources=this._windowSources.slice(),t.manualEntries=this.manualEntries.slice(),t.allowGlobalConfigSources=this.allowGlobalConfigSources,t.allowWindowSources=this.allowWindowSources,t.allowRagSearch=this.allowRagSearch,t.ensureInternalKnowledge(),t}registerMCPSource(e){e.id||(e.id=`external.${L++}`);let t=new W(e);return this.registerSource(e.id,n=>t.search(n)),t}};function ve(u){let e="",t=[],n=0;for(;n<u.length;){let s=u.indexOf("<[[",n);if(s===-1){e+=u.slice(n);break}e+=u.slice(n,s);let o=u.indexOf("]]>",s+3);if(o===-1)break;let r=u.slice(s,o+3),c=u.slice(s+3,o).trim(),l={raw:r,content:c};try{let d=JSON.parse(c);d&&typeof d=="object"&&!Array.isArray(d)&&(l.action=d)}catch{}t.push(l),n=o+3}return{visibleText:e,actions:t.flatMap(s=>s.action?[s.action]:[]),blocks:t}}function Z(u){return ve(u).visibleText}var R=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>Z(e?.text||""))?.filter(e=>!!e)?.join(`
22
22
 
23
23
  `)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,t)=>e+(t.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(t=>t.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(t=>t.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(t=>!!t)[0]||null}};import{v4 as ee}from"uuid";var K=class{constructor(e){this.ai=e}async boolean(e){let t=await this.instruct({...e,instruction:`${e.instruction}
24
24
 
@@ -12,7 +12,7 @@ New information found:
12
12
  ${o}
13
13
 
14
14
  New tools available:
15
- ${r}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(n,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!n.url||typeof n.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(n.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${n.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(n,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!n.path||typeof n.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(n.path,window.location.origin).pathname;return window.location.href=t,`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(n,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!n.email_address||typeof n.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!n.subject||typeof n.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!n.body||typeof n.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(n.email_address),i=encodeURIComponent(n.subject),o=encodeURIComponent(n.body),r=`mailto:${t}?subject=${i}&body=${o}`;try{window.location.href=r}catch(s){throw new Error(`Failed to open email client: ${s instanceof Error?s.message:String(s)}`)}return`Email opened in default mail client. Recipient: ${n.email_address}, Subject: ${n.subject}`}}];import{Client as Jt}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as $t}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var Y={name:"@intelliweave/embedded",version:"2.2.83",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{LoggingMessageNotificationSchema as Qt,ToolListChangedNotificationSchema as qt}from"@modelcontextprotocol/sdk/types.js";var I=new f("MCPKnowledgeClient"),ei="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",Ne=class{constructor(n){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=n}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(){I.debug("Connecting to MCP client");let n=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new URL(this.config.baseURL),t={};this.config.headers&&(t={...t,...this.config.headers}),this.config.proxy?.enabled&&(t["Mcp-Target-Url"]=e.toString(),t["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",e=new URL(this.config.proxy.url||ei));let i=new Jt({name:Y.name,version:Y.version}),o=new $t(e,{requestInit:{headers:t}});return await i.connect(o),I.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=n,n.onerror=e=>{I.error(`MCP client error: ${e.message}`)},n.onclose=()=>{I.debug("MCP client connection closed"),this.client=void 0},n.setNotificationHandler(Qt,e=>{e.params.level=="critical"?I.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?I.error(`[Server] ${e.params.data}`):e.params.level=="error"?I.error(`[Server] ${e.params.data}`):e.params.level=="warning"?I.warn(`[Server] ${e.params.data}`):e.params.level=="info"?I.info(`[Server] ${e.params.data}`):e.params.level=="debug"?I.debug(`[Server] ${e.params.data}`):I.log(`[Server] ${e.params.data}`)}),n.setNotificationHandler(qt,e=>{I.debug("Tool list changed",e),this.fetchTools()}),I.debug("Fetching tools from MCP server..."),await this.fetchTools(),n}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let n=[],e;for(;;){let o=await this.client.listTools({cursor:e});e=o.nextCursor;for(let r of o.tools||[])n.push(r);if(!o?.tools?.length||!e)break}let t=[],i=this.config.id||"mcp";for(let o of n){let r=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),s=`${i}_${o.name}`;t.push({id:s,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:r})}I.debug(`Fetched ${n.length} tools from MCP server.`),this.tools=n,this.iwActions=t}async search(n){if(n==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(n);return e=e.concat(t),this.lastSearchQuery=n,this.lastSearchResults=e,I.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(n){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(o=>o.name==this.config.searchToolName);if(!t)return I.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let i;if(t.inputSchema.required?.length==1){let o=t.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:n})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let o=Object.keys(t.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:n})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let r=i[o];e.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+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 i=="string"?i:JSON.stringify(i)});return e}async performToolCall(n,e){await this.connect(),I.debug(`Performing tool call for ${n} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:n,arguments:e});if(t.isError){let i=t.content?.[0]?.text||"Unknown error";throw I.error(`Error calling tool ${n}: ${i}`),new Error(`Error calling tool ${n}: ${i}`)}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 ti}from"uuid";var ii=new f("Statistics"),ge=[];async function C(a,n){let e={...n,event_id:ti(),event_date:new Date().toISOString(),sdk_version:Y.version,conversation_id:a?.conversationID||"",api_key:a?.apiKey||"",user_id:a?.userID||""};if(ge.push(e),!a||(await new Promise(i=>setTimeout(i,5e3)),ge.length===0))return;let t=ge.slice();ge.length=0;try{let i=await fetch(a.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){ii.warn("Failed to submit analytics event:",i),ge.push(...t);return}}var F=new f("KnowledgeBase"),oi=8*1024,Qe=1,Ae=class a{constructor(n){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=n,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(n=>n.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>ft(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(n,e){let t=n;return typeof n=="function"&&(e=n,t=`source.${Qe++}`),this._sources.push({id:t,query:e}),t}removeSource(n){this._sources=this.sources.filter(e=>e.id!==n&&e.query!==n)}addEntry(n){this.manualEntries.push(n)}removeEntry(n){this.manualEntries=this.manualEntries.filter(e=>e.id!==n)}get sources(){let n=this._sources;return this.allowGlobalConfigSources&&b().knowledgeBaseSources&&(n=n.concat(b().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(n=n.concat(this._windowSources)),n=n.filter(e=>!e.disabled),n}async search(n){F.debug(`Searching knowledge base for: ${n}`);let e=Date.now(),t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=n,t.entries=[],t.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(t),this._windowSources=t.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async d=>{try{let h=Date.now(),p=await d.query(n);return F.debug(`Source '${d.id}' took ${Date.now()-h}ms`),p||[]}catch(h){return F.warn(`Knowledge source '${d.id}' failed:`,h),[]}}))).flat();o=o.concat(t.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&b().knowledgeBase&&(o=o.concat(b().knowledgeBase)),o=o.filter(d=>d&&!d.disabled);let r=new Map;for(let d of o)d.id&&r.set(d.id,(r.get(d.id)||0)+1);for(let[d,h]of r)if(h>1){F.warn(`Duplicate knowledge base item ID detected: '${d}' appears ${h} times. Adding suffixes to make them unique.`);let p=1,m=!0;for(let g of o)if(g.id===d){if(m){m=!1;continue}g.id=`${d}(${p})`,p++}}for(let d=0;d<o.length;d++){let h=o[d];h.id=h.id||`temp.${d}`,h._functionID=h.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new ni({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let u=s.search(n).map(d=>o.find(h=>h.id==d.id)).filter(Boolean),c=0;u=u.filter(d=>{if(d.isContext)return!0;let h=(d.content||"").length;return c+h>oi?!1:(c+=h,!0)});for(let d of o)d.isContext&&(u.find(h=>h.id===d.id)||u.push(d));return this.lastResults=u,C(this.ai,{event_type:"kb_search",value:u.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),F.debug("Found results:",u),u}getCachedEntry(n){return this.lastResults.find(e=>e.id==n||e._functionID==n)}registerSourceFromURL(n,e){e||(e=`external.${Qe++}`),F.debug(`Registering remote knowledge base source: ${n}`);let t=[],i=[],o=!0,r=async(l,u)=>{F.debug(`Calling remote knowledge base action: ${l.id}`);let c={type:"action",userID:this.ai.userID,actionID:l.id,parameters:u},d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let h=await d.json();return s(h.updateItems||[]),h.response},s=l=>{for(let u of l){if(!u.id){F.warn("KB item skipped since it has no ID.",u);continue}let c=t.find(d=>d.id==u.id);if(c){c.name=u.name||c.name||"",c.content=u.content||c.content||"",c.disabled=u.disabled??c.disabled,c.isContext=u.isContext??c.isContext,c.parameters=u.parameters||c.parameters||[],c.tags=u.tags||c.tags,c.type=u.type||c.type;continue}t.push({...u,action:d=>r(u,d)})}};this.registerSource(e,async l=>{if(o&&i.includes(l))return t;let u={type:"search",userID:this.ai?.userID||"",query:l},c=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let d=await c.json();return o=!d.noCache,i.includes(l)||i.push(l),s(d.items),t})}clone(n){let e=new a(n);return e._sources=this._sources.slice(),e._windowSources=this._windowSources.slice(),e.manualEntries=this.manualEntries.slice(),e.allowGlobalConfigSources=this.allowGlobalConfigSources,e.allowWindowSources=this.allowWindowSources,e.allowRagSearch=this.allowRagSearch,e.ensureInternalKnowledge(),e}registerMCPSource(n){n.id||(n.id=`external.${Qe++}`);let e=new Ne(n);return this.registerSource(n.id,t=>e.search(t)),e}};var Le=class{constructor(n){this.ai=n}async boolean(n){let e=await this.instruct({...n,instruction:`${n.instruction}
15
+ ${r}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(n,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!n.url||typeof n.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(n.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${n.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(n,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!n.path||typeof n.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(n.path,window.location.origin).pathname;return window.location.href=t,`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!a?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(n,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!n.email_address||typeof n.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!n.subject||typeof n.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!n.body||typeof n.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(n.email_address),i=encodeURIComponent(n.subject),o=encodeURIComponent(n.body),r=`mailto:${t}?subject=${i}&body=${o}`;try{window.location.href=r}catch(s){throw new Error(`Failed to open email client: ${s instanceof Error?s.message:String(s)}`)}return`Email opened in default mail client. Recipient: ${n.email_address}, Subject: ${n.subject}`}}];import{Client as Jt}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as $t}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var Y={name:"@intelliweave/embedded",version:"2.2.84",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{LoggingMessageNotificationSchema as Qt,ToolListChangedNotificationSchema as qt}from"@modelcontextprotocol/sdk/types.js";var I=new f("MCPKnowledgeClient"),ei="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",Ne=class{constructor(n){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=n}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(){I.debug("Connecting to MCP client");let n=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new URL(this.config.baseURL),t={};this.config.headers&&(t={...t,...this.config.headers}),this.config.proxy?.enabled&&(t["Mcp-Target-Url"]=e.toString(),t["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",e=new URL(this.config.proxy.url||ei));let i=new Jt({name:Y.name,version:Y.version}),o=new $t(e,{requestInit:{headers:t}});return await i.connect(o),I.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=n,n.onerror=e=>{I.error(`MCP client error: ${e.message}`)},n.onclose=()=>{I.debug("MCP client connection closed"),this.client=void 0},n.setNotificationHandler(Qt,e=>{e.params.level=="critical"?I.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?I.error(`[Server] ${e.params.data}`):e.params.level=="error"?I.error(`[Server] ${e.params.data}`):e.params.level=="warning"?I.warn(`[Server] ${e.params.data}`):e.params.level=="info"?I.info(`[Server] ${e.params.data}`):e.params.level=="debug"?I.debug(`[Server] ${e.params.data}`):I.log(`[Server] ${e.params.data}`)}),n.setNotificationHandler(qt,e=>{I.debug("Tool list changed",e),this.fetchTools()}),I.debug("Fetching tools from MCP server..."),await this.fetchTools(),n}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let n=[],e;for(;;){let o=await this.client.listTools({cursor:e});e=o.nextCursor;for(let r of o.tools||[])n.push(r);if(!o?.tools?.length||!e)break}let t=[],i=this.config.id||"mcp";for(let o of n){let r=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),s=`${i}_${o.name}`;t.push({id:s,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:r})}I.debug(`Fetched ${n.length} tools from MCP server.`),this.tools=n,this.iwActions=t}async search(n){if(n==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(n);return e=e.concat(t),this.lastSearchQuery=n,this.lastSearchResults=e,I.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(n){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(o=>o.name==this.config.searchToolName);if(!t)return I.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let i;if(t.inputSchema.required?.length==1){let o=t.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:n})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let o=Object.keys(t.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:n})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let r=i[o];e.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+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 i=="string"?i:JSON.stringify(i)});return e}async performToolCall(n,e){await this.connect(),I.debug(`Performing tool call for ${n} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:n,arguments:e});if(t.isError){let i=t.content?.[0]?.text||"Unknown error";throw I.error(`Error calling tool ${n}: ${i}`),new Error(`Error calling tool ${n}: ${i}`)}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 ti}from"uuid";var ii=new f("Statistics"),ge=[];async function C(a,n){let e={...n,event_id:ti(),event_date:new Date().toISOString(),sdk_version:Y.version,conversation_id:a?.conversationID||"",api_key:a?.apiKey||"",user_id:a?.userID||""};if(ge.push(e),!a||(await new Promise(i=>setTimeout(i,5e3)),ge.length===0))return;let t=ge.slice();ge.length=0;try{let i=await fetch(a.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){ii.warn("Failed to submit analytics event:",i),ge.push(...t);return}}var F=new f("KnowledgeBase"),oi=8*1024,Qe=1,Ae=class a{constructor(n){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=n,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(n=>n.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>ft(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(n,e){let t=n;return typeof n=="function"&&(e=n,t=`source.${Qe++}`),this._sources.push({id:t,query:e}),t}removeSource(n){this._sources=this.sources.filter(e=>e.id!==n&&e.query!==n)}addEntry(n){this.manualEntries.push(n)}removeEntry(n){this.manualEntries=this.manualEntries.filter(e=>e.id!==n)}get sources(){let n=this._sources;return this.allowGlobalConfigSources&&b().knowledgeBaseSources&&(n=n.concat(b().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(n=n.concat(this._windowSources)),n=n.filter(e=>!e.disabled),n}async search(n){F.debug(`Searching knowledge base for: ${n}`);let e=Date.now(),t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=n,t.entries=[],t.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(t),this._windowSources=t.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async d=>{try{let h=Date.now(),p=await d.query(n);return F.debug(`Source '${d.id}' took ${Date.now()-h}ms`),p||[]}catch(h){return F.warn(`Knowledge source '${d.id}' failed:`,h),[]}}))).flat();o=o.concat(t.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&b().knowledgeBase&&(o=o.concat(b().knowledgeBase)),o=o.filter(d=>d&&!d.disabled);let r=new Map;for(let d of o)d.id&&r.set(d.id,(r.get(d.id)||0)+1);for(let[d,h]of r)if(h>1){F.warn(`Duplicate knowledge base item ID detected: '${d}' appears ${h} times. Adding suffixes to make them unique.`);let p=1,m=!0;for(let g of o)if(g.id===d){if(m){m=!1;continue}g.id=`${d}(${p})`,p++}}for(let d=0;d<o.length;d++){let h=o[d];h.id=h.id||`temp.${d}`,h._functionID=h.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new ni({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let u=s.search(n).map(d=>o.find(h=>h.id==d.id)).filter(Boolean),c=0;u=u.filter(d=>{if(d.isContext)return!0;let h=(d.content||"").length;return c+h>oi?!1:(c+=h,!0)});for(let d of o)d.isContext&&(u.find(h=>h.id===d.id)||u.push(d));return this.lastResults=u,C(this.ai,{event_type:"kb_search",value:u.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),F.debug("Found results:",u),u}getCachedEntry(n){return this.lastResults.find(e=>e.id==n||e._functionID==n)}registerSourceFromURL(n,e){e||(e=`external.${Qe++}`),F.debug(`Registering remote knowledge base source: ${n}`);let t=[],i=[],o=!0,r=async(l,u)=>{F.debug(`Calling remote knowledge base action: ${l.id}`);let c={type:"action",userID:this.ai.userID,actionID:l.id,parameters:u},d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let h=await d.json();return s(h.updateItems||[]),h.response},s=l=>{for(let u of l){if(!u.id){F.warn("KB item skipped since it has no ID.",u);continue}let c=t.find(d=>d.id==u.id);if(c){c.name=u.name||c.name||"",c.content=u.content||c.content||"",c.disabled=u.disabled??c.disabled,c.isContext=u.isContext??c.isContext,c.parameters=u.parameters||c.parameters||[],c.tags=u.tags||c.tags,c.type=u.type||c.type;continue}t.push({...u,action:d=>r(u,d)})}};this.registerSource(e,async l=>{if(o&&i.includes(l))return t;let u={type:"search",userID:this.ai?.userID||"",query:l},c=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let d=await c.json();return o=!d.noCache,i.includes(l)||i.push(l),s(d.items),t})}clone(n){let e=new a(n);return e._sources=this._sources.slice(),e._windowSources=this._windowSources.slice(),e.manualEntries=this.manualEntries.slice(),e.allowGlobalConfigSources=this.allowGlobalConfigSources,e.allowWindowSources=this.allowWindowSources,e.allowRagSearch=this.allowRagSearch,e.ensureInternalKnowledge(),e}registerMCPSource(n){n.id||(n.id=`external.${Qe++}`);let e=new Ne(n);return this.registerSource(n.id,t=>e.search(t)),e}};var Le=class{constructor(n){this.ai=n}async boolean(n){let e=await this.instruct({...n,instruction:`${n.instruction}
16
16
 
17
17
  Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(e.toLowerCase().includes("true"))return!0;if(e.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+e)}async choose(n){let e=await this.instruct({...n,instruction:`${n.instruction}
18
18
 
@@ -1278,6 +1278,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
1278
1278
  flex-direction: unset;
1279
1279
  gap: 10px;
1280
1280
  }
1281
+
1281
1282
  #root.container-mode #web-weaver-embed-inner {
1282
1283
  flex: 1 1 auto;
1283
1284
  min-height: 0;
@@ -1549,6 +1550,21 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
1549
1550
  overflow: hidden;
1550
1551
  text-overflow: ellipsis;
1551
1552
  }
1553
+ #root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner {
1554
+ flex: 1 1 auto;
1555
+ min-height: 0;
1556
+ max-height: none;
1557
+ height: auto;
1558
+ overflow-x: hidden;
1559
+ overflow-y: auto;
1560
+ width: 100%;
1561
+ max-width: none;
1562
+ margin: 2px;
1563
+ padding: 12px;
1564
+ align-content: start;
1565
+ flex-direction: unset;
1566
+ gap: 10px;
1567
+ }
1552
1568
  }
1553
1569
 
1554
1570
  </style>
@@ -110,7 +110,7 @@ ${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"ope
110
110
  `;break;case"id":a=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new yb(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:g}));break;default:r(new yb(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:y,line:g}));break}}function p(){l.length>0&&e({id:a,event:c||void 0,data:l.endsWith(`
111
111
  `)?l.slice(0,-1):l}),a=void 0,l="",c=""}function m(h={}){o&&h.consume&&d(o),s=!0,a=void 0,l="",c="",o=""}return{feed:u,reset:m}}function p7(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
112
112
  `,n),s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?s=i:o!==-1&&(s=o),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
113
- `&&n++}}return[e,r]}var bb=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=Mj({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var f7={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ns=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},vb=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=wj(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??f7}async _authThenStart(){if(!this._authProvider)throw new zo("No auth provider");let e;try{e=await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new zo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=gb(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let i=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Ns(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},i)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new bb({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:m}=await u.read();if(m)break;if(p.id&&(s=p.id,a=!0,i?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let h=Zg.parse(JSON.parse(p.data));Ra(h)&&(l=!0,o!==void 0&&(h.id=o)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new zo("No auth provider");if(await lm(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:i}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Mp(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,s),l=a.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ns(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:p,scope:m}=SI(a);if(this._resourceMetadataUrl=p,this._scope=m,await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zo;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:p,scope:m,error:h}=SI(a);if(h==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Ns(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=y??void 0,await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new zo;return this.send(e)}}throw new Ns(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),sz(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let u=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:i},!1);else if(d?.includes("application/json")){let f=await a.json(),p=Array.isArray(f)?f.map(m=>Zg.parse(m)):[Zg.parse(f)];for(let m of p)this.onmessage?.(m)}else throw await a.body?.cancel(),new Ns(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Ns(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Os={name:"@intelliweave/embedded",version:"2.2.83",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};var ur=new Oe("MCPKnowledgeClient"),h7="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",_b=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){ur.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=r.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",r=new URL(this.config.proxy.url||h7));let i=new hb({name:Os.name,version:Os.version}),o=new vb(r,{requestInit:{headers:n}});return await i.connect(o),ur.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=e,e.onerror=r=>{ur.error(`MCP client error: ${r.message}`)},e.onclose=()=>{ur.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(U0,r=>{r.params.level=="critical"?ur.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?ur.error(`[Server] ${r.params.data}`):r.params.level=="error"?ur.error(`[Server] ${r.params.data}`):r.params.level=="warning"?ur.warn(`[Server] ${r.params.data}`):r.params.level=="info"?ur.info(`[Server] ${r.params.data}`):r.params.level=="debug"?ur.debug(`[Server] ${r.params.data}`):ur.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Vp,r=>{ur.debug("Tool list changed",r),this.fetchTools()}),ur.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let o=await this.client.listTools({cursor:r});r=o.nextCursor;for(let s of o.tools||[])e.push(s);if(!o?.tools?.length||!r)break}let n=[],i=this.config.id||"mcp";for(let o of e){let s=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),a=`${i}_${o.name}`;n.push({id:a,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:s})}ur.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,ur.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return ur.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else r.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return r}async performToolCall(e,r){await this.connect(),ur.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw ur.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var g7=new Oe("Statistics"),cm=[];async function Hr(t,e){let r={...e,event_id:hr(),event_date:new Date().toISOString(),sdk_version:Os.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(cm.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),cm.length===0))return;let n=cm.slice();cm.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){g7.warn("Failed to submit analytics event:",i),cm.push(...n);return}}var Rs=new Oe("KnowledgeBase"),y7=8*1024,EI=1,wb=class t{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>zT(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${EI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&Et().knowledgeBaseSources&&(e=e.concat(Et().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Rs.debug(`Searching knowledge base for: ${e}`);let r=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async d=>{try{let f=Date.now(),p=await d.query(e);return Rs.debug(`Source '${d.id}' took ${Date.now()-f}ms`),p||[]}catch(f){return Rs.warn(`Knowledge source '${d.id}' failed:`,f),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&Et().knowledgeBase&&(o=o.concat(Et().knowledgeBase)),o=o.filter(d=>d&&!d.disabled);let s=new Map;for(let d of o)d.id&&s.set(d.id,(s.get(d.id)||0)+1);for(let[d,f]of s)if(f>1){Rs.warn(`Duplicate knowledge base item ID detected: '${d}' appears ${f} times. Adding suffixes to make them unique.`);let p=1,m=!0;for(let h of o)if(h.id===d){if(m){m=!1;continue}h.id=`${d}(${p})`,p++}}for(let d=0;d<o.length;d++){let f=o[d];f.id=f.id||`temp.${d}`,f._functionID=f.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let a=new dp({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});a.addAll(o);let c=a.search(e).map(d=>o.find(f=>f.id==d.id)).filter(Boolean),u=0;c=c.filter(d=>{if(d.isContext)return!0;let f=(d.content||"").length;return u+f>y7?!1:(u+=f,!0)});for(let d of o)d.isContext&&(c.find(f=>f.id===d.id)||c.push(d));return this.lastResults=c,Hr(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Rs.debug("Found results:",c),c}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${EI++}`),Rs.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Rs.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let f=await d.json();return a(f.updateItems||[]),f.response},a=l=>{for(let c of l){if(!c.id){Rs.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(e){let r=new t(e);return r._sources=this._sources.slice(),r._windowSources=this._windowSources.slice(),r.manualEntries=this.manualEntries.slice(),r.allowGlobalConfigSources=this.allowGlobalConfigSources,r.allowWindowSources=this.allowWindowSources,r.allowRagSearch=this.allowRagSearch,r.ensureInternalKnowledge(),r}registerMCPSource(e){e.id||(e.id=`external.${EI++}`);let r=new _b(e);return this.registerSource(e.id,n=>r.search(n)),r}};var xb=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
113
+ `&&n++}}return[e,r]}var bb=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=Mj({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var f7={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ns=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},vb=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=wj(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??f7}async _authThenStart(){if(!this._authProvider)throw new zo("No auth provider");let e;try{e=await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new zo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=gb(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let i=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Ns(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},i)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new bb({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:m}=await u.read();if(m)break;if(p.id&&(s=p.id,a=!0,i?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let h=Zg.parse(JSON.parse(p.data));Ra(h)&&(l=!0,o!==void 0&&(h.id=o)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new zo("No auth provider");if(await lm(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:i}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Mp(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,s),l=a.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ns(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:p,scope:m}=SI(a);if(this._resourceMetadataUrl=p,this._scope=m,await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zo;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:p,scope:m,error:h}=SI(a);if(h==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Ns(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=y??void 0,await lm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new zo;return this.send(e)}}throw new Ns(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),sz(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let u=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:i},!1);else if(d?.includes("application/json")){let f=await a.json(),p=Array.isArray(f)?f.map(m=>Zg.parse(m)):[Zg.parse(f)];for(let m of p)this.onmessage?.(m)}else throw await a.body?.cancel(),new Ns(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Ns(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Os={name:"@intelliweave/embedded",version:"2.2.84",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};var ur=new Oe("MCPKnowledgeClient"),h7="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",_b=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){ur.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=r.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",r=new URL(this.config.proxy.url||h7));let i=new hb({name:Os.name,version:Os.version}),o=new vb(r,{requestInit:{headers:n}});return await i.connect(o),ur.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=e,e.onerror=r=>{ur.error(`MCP client error: ${r.message}`)},e.onclose=()=>{ur.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(U0,r=>{r.params.level=="critical"?ur.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?ur.error(`[Server] ${r.params.data}`):r.params.level=="error"?ur.error(`[Server] ${r.params.data}`):r.params.level=="warning"?ur.warn(`[Server] ${r.params.data}`):r.params.level=="info"?ur.info(`[Server] ${r.params.data}`):r.params.level=="debug"?ur.debug(`[Server] ${r.params.data}`):ur.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Vp,r=>{ur.debug("Tool list changed",r),this.fetchTools()}),ur.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let o=await this.client.listTools({cursor:r});r=o.nextCursor;for(let s of o.tools||[])e.push(s);if(!o?.tools?.length||!r)break}let n=[],i=this.config.id||"mcp";for(let o of e){let s=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),a=`${i}_${o.name}`;n.push({id:a,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:s})}ur.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,ur.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return ur.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else r.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return r}async performToolCall(e,r){await this.connect(),ur.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw ur.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var g7=new Oe("Statistics"),cm=[];async function Hr(t,e){let r={...e,event_id:hr(),event_date:new Date().toISOString(),sdk_version:Os.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(cm.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),cm.length===0))return;let n=cm.slice();cm.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){g7.warn("Failed to submit analytics event:",i),cm.push(...n);return}}var Rs=new Oe("KnowledgeBase"),y7=8*1024,EI=1,wb=class t{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>zT(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${EI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&Et().knowledgeBaseSources&&(e=e.concat(Et().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Rs.debug(`Searching knowledge base for: ${e}`);let r=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async d=>{try{let f=Date.now(),p=await d.query(e);return Rs.debug(`Source '${d.id}' took ${Date.now()-f}ms`),p||[]}catch(f){return Rs.warn(`Knowledge source '${d.id}' failed:`,f),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&Et().knowledgeBase&&(o=o.concat(Et().knowledgeBase)),o=o.filter(d=>d&&!d.disabled);let s=new Map;for(let d of o)d.id&&s.set(d.id,(s.get(d.id)||0)+1);for(let[d,f]of s)if(f>1){Rs.warn(`Duplicate knowledge base item ID detected: '${d}' appears ${f} times. Adding suffixes to make them unique.`);let p=1,m=!0;for(let h of o)if(h.id===d){if(m){m=!1;continue}h.id=`${d}(${p})`,p++}}for(let d=0;d<o.length;d++){let f=o[d];f.id=f.id||`temp.${d}`,f._functionID=f.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let a=new dp({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});a.addAll(o);let c=a.search(e).map(d=>o.find(f=>f.id==d.id)).filter(Boolean),u=0;c=c.filter(d=>{if(d.isContext)return!0;let f=(d.content||"").length;return u+f>y7?!1:(u+=f,!0)});for(let d of o)d.isContext&&(c.find(f=>f.id===d.id)||c.push(d));return this.lastResults=c,Hr(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Rs.debug("Found results:",c),c}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${EI++}`),Rs.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Rs.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let f=await d.json();return a(f.updateItems||[]),f.response},a=l=>{for(let c of l){if(!c.id){Rs.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(e){let r=new t(e);return r._sources=this._sources.slice(),r._windowSources=this._windowSources.slice(),r.manualEntries=this.manualEntries.slice(),r.allowGlobalConfigSources=this.allowGlobalConfigSources,r.allowWindowSources=this.allowWindowSources,r.allowRagSearch=this.allowRagSearch,r.ensureInternalKnowledge(),r}registerMCPSource(e){e.id||(e.id=`external.${EI++}`);let r=new _b(e);return this.registerSource(e.id,n=>r.search(n)),r}};var xb=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
114
114
 
115
115
  Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(r.toLowerCase().includes("true"))return!0;if(r.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+r)}async choose(e){let r=await this.instruct({...e,instruction:`${e.instruction}
116
116
 
@@ -1416,6 +1416,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
1416
1416
  flex-direction: unset;
1417
1417
  gap: 10px;
1418
1418
  }
1419
+
1419
1420
  #root.container-mode #web-weaver-embed-inner {
1420
1421
  flex: 1 1 auto;
1421
1422
  min-height: 0;
@@ -1687,6 +1688,21 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
1687
1688
  overflow: hidden;
1688
1689
  text-overflow: ellipsis;
1689
1690
  }
1691
+ #root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner {
1692
+ flex: 1 1 auto;
1693
+ min-height: 0;
1694
+ max-height: none;
1695
+ height: auto;
1696
+ overflow-x: hidden;
1697
+ overflow-y: auto;
1698
+ width: 100%;
1699
+ max-width: none;
1700
+ margin: 2px;
1701
+ padding: 12px;
1702
+ align-content: start;
1703
+ flex-direction: unset;
1704
+ gap: 10px;
1705
+ }
1690
1706
  }
1691
1707
 
1692
1708
  </style>
@@ -9,7 +9,7 @@ import{v4 as ut}from"uuid";function Se(l){let i=(l||"").split(`
9
9
  `,yield*e()}function pt(){if(b().userID)return b().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let l=localStorage.getItem("intelliweave.uid")||"";return l||(l=ut(),localStorage.setItem("intelliweave.uid",l),l)}else return ut()}function ht(l){let i=l;if(i?.type=="object"&&i.properties)return l;let e={type:"object",properties:{},required:[]};if(l&&Array.isArray(l)){let t=l;for(let n of t)e.properties[n.name]={type:n.type||"string",description:n.description||""}}return e}var Te=class Te{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return Te.debug?!0:typeof window<"u"&&b().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...n)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...n)}};Te.debug=!1;var f=Te;var ne=new f("ONNXModel"),X=class l{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,ne.debug(`Model input parameters: ${i.inputNames.join(", ")}`),ne.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!l.lib}static async load(i){if(!l.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(ne.debug("Loading ONNX runtime"),this.onnx=await l.lib()),ne.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new l(e)}makeTensor(i,e,t=0){let n=1;for(let r of e)n*=r;let o;if(i=="float32")o=new l.onnx.Tensor(new Float32Array(n),e);else if(i=="int8")o=new l.onnx.Tensor(new Int8Array(n),e);else if(i=="int16")o=new l.onnx.Tensor(new Int16Array(n),e);else if(i=="int32")o=new l.onnx.Tensor(new Int32Array(n),e);else if(i=="int64")o=new l.onnx.Tensor(new BigInt64Array(n),e);else if(i=="uint8")o=new l.onnx.Tensor(new Uint8Array(n),e);else if(i=="uint16")o=new l.onnx.Tensor(new Uint16Array(n),e);else if(i=="uint32")o=new l.onnx.Tensor(new Uint32Array(n),e);else if(i=="uint64")o=new l.onnx.Tensor(new BigUint64Array(n),e);else throw new Error(`Invalid type: ${i}`);return t!==0&&(i=="int64"||i=="uint64")?o.data.fill(BigInt(t)):t!==0&&o.data.fill(t),o}registerConstant(i,e){if(!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);return this.constantTensors[i]=e,e}makeConstant(i,e,t,n=0){return this.registerConstant(i,this.makeTensor(e,t,n))}registerState(i,e,t){if(e||(e=i),!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[i]={outputName:e,tensor:t},t}makeState(i,e,t,n,o=0){return this.registerState(i,e,this.makeTensor(t,n,o))}async run(i={}){if(this._runActive&&this.ignoreIfBusy)return ne.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)i[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)i[e]=this.constantTensors[e];try{let e=await this.session.run(i);for(let t in this.stateTensors){let n=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=n}return e}finally{this._runActive=!1}}resetState(){ne.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var mt="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3I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HIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var Ft=new f("PCMPlayerNode"),oe=class extends AudioWorkletNode{constructor(e,t,n){super(e,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!n||n!="int16"&&n!="float32")throw new Error(`Invalid format: ${n}`);this.sampleRate=t,this.format=n,this.port.onmessage=o=>this.onWorkletMessage(o),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:n})}static async registerModule(e){await e.audioWorklet.addModule(mt)}feed(e){this.port.postMessage({action:"data",buffer:e.buffer},[e.buffer])}async play(e){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(t=>this._playPromiseResolve=t),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:e}}));try{let t=e.getReader();for(;!this.isCancelled;){let{done:n,value:o}=await t.read();if(n||!o)break;this.feed(o)}}catch(t){Ft.warn("Stream error:",t),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:e,error:t}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(e){e.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};import{v4 as Ut}from"uuid";var V=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new Je;return e.id=i,this.groups.push(e),e}group(i){return this.groups.find(e=>e.id===i)}static countTokensInText(i){return i==null?i="":typeof i=="number"?i=i+"":typeof i!="string"&&(i=JSON.stringify(i)),Math.ceil(i.length/3)}countTokens(){return this.groups.reduce((i,e)=>i+e.tokenCount,0)}removeOverflow(){let i=this.countTokens(),e=this.groups.reduce((t,n)=>t+n.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((o,r)=>{let s=Math.floor(o.weight/e*this.size),a=Math.floor(r.weight/e*this.size),u=o.tokenCount-s;return r.tokenCount-a-u}),n=this.removeOneItem(t);if(!n)throw new Error("Too many items in the token window that cannot be removed.");i-=n.tokenCount}}removeOneItem(i){for(let e of i){let t=e.items.findIndex(o=>!o.cannotRemove);if(t===-1)continue;let n=e.items[t];return e.items.splice(t,1),e.tokenCount-=n.tokenCount,n}return null}},Je=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
10
10
  `;this.itemPadding=0;this.sortFunction=(i,e)=>i.sortOrder!==e.sortOrder?i.sortOrder-e.sortOrder:i.dateAdded!==e.dateAdded?i.dateAdded-e.dateAdded:0}setItemPadding(i){return this.itemPadding=i,this.recalculateTokens(),this}sortBy(i){return this.sortFunction=i,this.items.sort(this.sortFunction),this}setSeparator(i){return this.separator==i?this:(this.separator=i,this.recalculateTokens(),this)}setWeight(i){return this.weight=i,this}recalculateTokens(){this.tokenCount=this.items.reduce((i,e)=>(e.tokenCount=V.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+V.countTokensInText(this.separator)+this.itemPadding,i+e.tokenCount),0)}add(i){typeof i=="string"&&(i={source:"user",data:i});let e=i;e.id===void 0&&(e.id=Ut()),!e.sections?.length&&typeof e.data=="string"?e.text=e.data:e.text=e.sections?.map(n=>{if(n.type==="text")return n.text||"";if(n.type==="tool_call")return`[Tool Call: ${n.toolKbName||n.toolName}] `;if(n.type==="tool_result"&&n.toolErrorResponse)return`[Tool Error: ${n.toolErrorResponse}] `}).filter(n=>!!n).join(`
11
11
 
12
- `)||"";let t=this.items.find(n=>n.id===e.id);return t?(this.tokenCount-=t.tokenCount,Object.assign(t,e),e=t):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.source===void 0&&(e.source="user"),e.sections===void 0&&(e.sections=[]),e.tokenCount=e.disabled?0:V.countTokensInText(typeof i.data=="string"?i.data:JSON.stringify(i.data))+V.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}remove(i){let e=this.items.findIndex(t=>t.id===i);return e===-1?!1:(this.tokenCount-=this.items[e].tokenCount||0,this.items.splice(e,1),!0)}getAllAsString(){return this.getAll().map(i=>i.text).join(this.separator)}getAll(){return this.items.filter(i=>!i.disabled)}empty(){this.items=[],this.tokenCount=0}},Y=(o=>(o.Text="text",o.ToolCall="tool_call",o.ToolResult="tool_result",o.Thinking="thinking",o.Other="other",o))(Y||{});var D=new f("ElevenLabs");function $e(l,i,e="pcm_24000"){let t=[],n=Date.now(),o=!1,r,s;return{stream:new ReadableStream({start:c=>{r=c,s=new WebSocket(`wss://api.elevenlabs.io/v1/text-to-speech/${i}/stream-input?inactivity_timeout=120&output_format=${e}`),s.addEventListener("open",()=>{D.debug(`[at ${Date.now()-n}ms] WebSocket connected`),s.send(JSON.stringify({text:" ","xi-api-key":l}));for(let p of t)s.send(JSON.stringify({text:p}));t.length=0}),s.addEventListener("close",()=>{D.debug(`[at ${Date.now()-n}ms] WebSocket closed`),r?.close(),o=!0}),s.addEventListener("message",p=>{let h=JSON.parse(p.data);if(h.final){s.close(),r?.close();return}if(D.debug(`[at ${Date.now()-n}ms] Message received: ${h.audio?.length||0} bytes of audio data`),!h.audio)return;let m=Uint8Array.from(atob(h.audio),g=>g.charCodeAt(0));r?.enqueue(m)})},cancel:()=>{D.debug(`[at ${Date.now()-n}ms] Stream cancelled`),s?.close(),o=!0}}),sendText:c=>{c&&(D.debug(`[at ${Date.now()-n}ms] Sending text: "${c}"`),s?.readyState===WebSocket.OPEN?s.send(JSON.stringify({text:c})):t.push(c))},endText:()=>{s?.readyState===WebSocket.OPEN?s.send(JSON.stringify({text:""})):t.push("")},get isClosed(){return o}}}function gt(l,i="pcm_16000",e=16e3,t="vad"){let n=[],o=Date.now(),r=!1,s,a;return{stream:new ReadableStream({start:async h=>{s=h;let m=await fetch("https://api.elevenlabs.io/v1/single-use-token/realtime_scribe",{method:"POST",headers:{"xi-api-key":l}});if(!m.ok)throw new Error(`Failed to generate single-use token: ${m.status} ${m.statusText}`);let g=await m.json(),y=g.token;if(!y)throw new Error(`No token found in response: ${JSON.stringify(g)}`);a=new WebSocket(`wss://api.elevenlabs.io/v1/speech-to-text/realtime?token=${encodeURIComponent(y)}&audio_format=${i}&commit_strategy=${t}`),a.addEventListener("open",()=>{D.debug(`[at ${Date.now()-o}ms] WebSocket connected`);for(let w of n)a.send(w);n.length=0}),a.addEventListener("close",()=>{D.debug(`[at ${Date.now()-o}ms] WebSocket closed`),s?.close(),r=!0}),a.addEventListener("message",w=>{let k=JSON.parse(w.data);k.message_type=="committed_transcript"?(D.debug(`[at ${Date.now()-o}ms] Committed transcript received: "${k.text}"`),s?.enqueue(k.text)):k.error&&(D.warn(`[at ${Date.now()-o}ms] Error received: ${k.error}`),s?.error(new Error(k.error)),a?.close(),r=!0)})},cancel:()=>{D.debug(`[at ${Date.now()-o}ms] Stream cancelled`),a?.close(),r=!0}}),sendAudio:h=>{let m=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:btoa(String.fromCharCode(...new Uint8Array(h))),commit:!1,sample_rate:e});D.debug(`[at ${Date.now()-o}ms] Sending audio: ${h.byteLength} bytes`),a?.readyState===WebSocket.OPEN?a.send(m):n.push(m)},commit:()=>{let h=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:e});a?.readyState===WebSocket.OPEN?a.send(h):n.push(h)},close:()=>{D.debug("Closing connection"),a?.close(),r=!0,setTimeout(()=>{s?.close()},1e3)},get isClosed(){return r}}}var Ce=new f("SpeechOutput"),ft=.5,Kt=.8,Ee=class extends EventTarget{constructor(e){super();this.autoSpeak=!0;this.preemptiveConnection=!0;this.processedMessages=new Set;this.maxVolumeHeard=0;this._queuedText=[];this._queueActive=!1;this.ai=e,this.ai.addEventListener("output",t=>this.onOutputFromAI(t)),this.ai.audio?.speechRecognition.addEventListener("speechstart",t=>this.interrupt())}onOutputFromAI(e){let t=e.detail.messages,n=e.detail.isPartial;if(!(!this.ai?.audio?.speechRecognition.isRunning||!this.autoSpeak)){for(let o of t)if(!o.streamingInProgress&&!(!o.id||this.processedMessages.has(o.id))){this.processedMessages.add(o.id);for(let r of o.sections||[])r.type=="text"&&r.text&&this.speak(r.text)}n||this.processedMessages.clear()}}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let n of this.analyserBuffer)e+=n*n;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}async speak(e){if(!this.ai?.config?.voice?.providerID)return Ce.warn("No voice provider configured");this.ai._voiceTracker?.(`Added text to queue: ${e}`),this._queuedText.push(e),this._runQueue()}async _runQueue(){if(this._queueActive)return;let e=this._queuedText.shift();if(!e)return;this._queueActive=!0;let t=`speech-${Ht++}`;try{await this.ai.audio.beginAccess(t),await this._speakWithLock(e)}finally{this._queueActive=!1,this.ai.audio.endAccess(t)}this._queuedText.length?await this._runQueue():this.onSpeechEnd()}_getElevenLabsConnection(){let e=this._elevenLabsPrecachedConnection;return(!e||e.isClosed)&&(e=$e(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),this.preemptiveConnection&&(this._elevenLabsPrecachedConnection=$e(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),e}async _speakWithLock(e){let t=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:e}});if(this.dispatchEvent(t),e=t.detail.message,t.defaultPrevented||!e)return;this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Kt);let n=this.ai?._voiceTracker||Ce.timer(`${this.ai.config.voice.providerID} voice`);n(`Speak: ${e}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let o=new oe(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",a=>{let u=a;n(`PCM stream ${u.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!u.detail.interrupted&&(this.currentPlayer=void 0)});let r=Date.now(),s=null;if(this.ai.config.voice.providerID=="openai"){let a=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:e,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});if(!a.ok){Ce.warn(`Failed to generate voice sample: ${a.status} ${a.statusText}`);return}s=a.body}else if(this.ai.config.voice.providerID=="elevenlabs"){let a=this._getElevenLabsConnection();a.sendText(e),a.endText(),s=a.stream}else{Ce.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}n(`Received response in ${Date.now()-r}ms`),this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),n("Playing PCM stream"),await o.play(s),n("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(this._queuedText=[],!this.currentPlayerVolume)return;this.ai._voiceTracker?.("Interrupted");let e=this.currentPlayerVolume,t=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=ft);let n=400;e.gain.linearRampToValueAtTime(0,n/1e3),await new Promise(o=>setTimeout(o,n+250)),e.disconnect(),t?.stop(),t?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=ft)}},Ht=1;function Ne(l,i){let e=i.reduce((a,u)=>a+u.byteLength,0),t=new DataView(new ArrayBuffer(44));t.setUint8(0,82),t.setUint8(1,73),t.setUint8(2,70),t.setUint8(3,70),t.setUint32(4,44+e,!0),t.setUint8(8,87),t.setUint8(9,65),t.setUint8(10,86),t.setUint8(11,69);let n=1,o=32,r=n*o/8,s=l*r;return t.setUint8(12,102),t.setUint8(13,109),t.setUint8(14,116),t.setUint8(15,32),t.setUint32(16,16,!0),t.setUint16(20,3,!0),t.setUint16(22,n,!0),t.setUint32(24,l,!0),t.setUint32(28,s,!0),t.setUint16(32,r,!0),t.setUint16(34,o,!0),t.setUint8(36,100),t.setUint8(37,97),t.setUint8(38,116),t.setUint8(39,97),t.setUint32(40,e,!0),new File([t,...i],"audio.wav",{type:"audio/wav"})}var bt="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZS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LmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var re=class extends AudioWorkletNode{constructor(e,t,n,o){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=n;let r=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!r.includes(n))throw new Error(`Invalid format ${n}, must be one of: ${r.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=s=>this.onWorkletMessage(s),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:n,bufferSize:o})}static async registerModule(e){await e.audioWorklet.addModule(bt)}onWorkletMessage(e){if(e.data.action=="data"){let t=null;if(this.format=="int16"&&(t=new Int16Array(e.data.buffer)),this.format=="int64"&&(t=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(t=new Float32Array(e.data.buffer)),!t)throw new Error(`Invalid format: ${this.format}`);this.onData(t),this.dispatchEvent(new CustomEvent("data",{detail:{data:t}}))}}onData(e){}};var Qe=16e3,Ae=256,se=8,ge=new f("VoiceDetectionNode"),fe=class fe extends re{constructor(e){super(e,Qe,"float32",Ae*se);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!fe.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return Qe}get numberOfSamples(){return Ae}get numberOfSampleChunks(){return se}get outputBufferSize(){return Ae*se}get isModelLoaded(){return!!this.vad}async loadModel(){ge.debug("Loading VAD model"),this.vad=await X.load(fe.vadModelURL),this.vad.ignoreIfBusy=!0,ge.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],Qe),this.vad.makeState("h","hn","float32",[2,se,64]),this.vad.makeState("c","cn","float32",[2,se,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new X.onnx.Tensor(e,[se,Ae])});if(!t)return;this.currentProbability=0;for(let r=0;r<t.output.data.length;r++)t.output.data[r]>this.currentProbability&&(this.currentProbability=t.output.data[r]);let n=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>n;if(!o&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=o,o&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),ge.debug("Started speaking")):o?this.lastVoiceActiveDate=Date.now():!o&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!o&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),ge.debug("Stopped speaking after timeout")),!o){let r=Date.now();r>this.nextVadReset&&(this.nextVadReset=r+5e3,this.vad.resetState())}}catch(t){ge.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};fe.vadModelURL="";var ae=fe;var yt=new f("VoiceChunkOutputNode"),F=class extends ae{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((e,t)=>e+t.length,0)/8e3}async onData(e){if(await super.onData(e),this.isVoiceActive&&!this._voiceRecording){yt.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let t of this.buffers)this.recordedBuffers.push(t),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:t,isFinal:!1}})),this.onVoiceChunk(t);this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!0}})),this.onVoiceChunk(e),this._voiceRecording=!1;let t=this.recordedBuffers.reduce((n,o)=>n+o.length,0);yt.debug(`Voice complete, recorded ${(t/8e3).toFixed(2)} seconds of audio, ${t*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(e);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(e){}onVoiceEnd(e){}};var Le=new f("OpenAITranscriptionNode"),De=class extends F{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=Le.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let n=Ne(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let r=new FormData;r.append("file",n),r.append("model","whisper-1"),r.append("response_format","text");let s=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:r,signal:this.lastRequestAbortController.signal});if(!s.ok)throw new Error(`Failed to generate voice sample: ${s.status} ${s.statusText}`);t("Response received"),o=await s.text(),t("Content received: "+o),this.lastRequestAbortController=void 0}catch(r){Le.error(`Failed to transcribe speech: ${r.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return Le.debug("Transcription complete, but no text was found");Le.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(e){}};var We=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var P=new f("IntelliWeaveTranscriptionNode"),$t="wss://speech.intelliweave.ai/api/v1/transcribe",Pe=class Pe extends F{constructor(e,t){super(e);this.apiAddress=$t;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(P.debug("Opening WebSocket connection"),this.ws=new We(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(e.buffer),this.ws.onopen=()=>{P.debug("WebSocket connection opened")},this.ws.addEventListener("message",n=>{let o=JSON.parse(n.data);if(o.error)return P.warn("Error: "+o.error);if(o.type!="transcription")return P.warn("Invalid response type",o);if(o.streaming&&!o.final)return P.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return P.warn(`Empty transcription (${o.processingTime}ms)`);P.debug(`Transcription: ${o.text} (${o.processingTime}ms)`),this.onVoiceTranscription(o.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",n=>P.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{P.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),Pe.debugExportWav){let t=Ne(this.sampleRate,e),n=document.createElement("a");n.href=URL.createObjectURL(t),n.download="recording.wav",n.click()}}onVoiceTranscription(e){}onSocketClose(){P.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};Pe.debugExportWav=!1;var Ge=Pe;var U={name:"@intelliweave/embedded",version:"2.2.83",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{v4 as qt}from"uuid";var ei=new f("Statistics"),be=[];async function C(l,i){let e={...i,event_id:qt(),event_date:new Date().toISOString(),sdk_version:U.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(be.push(e),!l||(await new Promise(n=>setTimeout(n,5e3)),be.length===0))return;let t=be.slice();be.length=0;try{let n=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){ei.warn("Failed to submit analytics event:",n),be.push(...t);return}}var le=new f("ElevenLabsTranscriptionNode"),Ze=class extends F{constructor(e,t){super(e);this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0;let t=new Int16Array(e.length);for(let o=0;o<e.length;o++)t[o]=e[o]*32767;!this.connection||this.connection.isClosed?(this.connection?.close(),this.connection=void 0,le.debug(`Opening connection. sampleRate: ${this.sampleRate} format=${this.format}`),this.connection=gt(this.apiKey,"pcm_"+this.sampleRate,this.sampleRate,"manual"),this.startReading(this.connection),this.connection.sendAudio(t.buffer)):this.connection.sendAudio(t.buffer);let n=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{le.debug("Shutting down WebSocket connection"),this.connection?.close(),this.connection=void 0},n)}async startReading(e){let t=e.stream.getReader();try{for(;;){let{value:n,done:o}=await t.read();if(o){le.debug("Stream closed");break}if(!n?.trim()){le.warn("Empty transcription received");continue}this.isTranscribing=!1,le.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}}catch(n){le.error(`Failed to read transcription stream: ${n.message}`),this.connection==e&&(this.connection=void 0);return}}async onVoiceEnd(e){this.connection?.commit()}onVoiceTranscription(e){}};var qe=new f("SpeechRecognition"),Re=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e}get isSupported(){if(!X.lib||!this.ai?.vadModel||!O().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey)){if(!(this.ai?.config?.transcription?.providerID=="elevenlabs"&&this.ai.config?.transcription?.apiKey))return!1}}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let e=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,e.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),ae.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new De(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):this.ai?.config?.transcription?.providerID=="elevenlabs"?(this.voiceDetection=new Ze(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new Ge(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",t=>{this.ai._voiceTracker=qe.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),C(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("speechend",t=>{this.ai._voiceTracker?.("Speech ended");let n=this.recordingStartTime?Date.now()-this.recordingStartTime:0;C(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:n}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),C(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:t.detail.confidence||void 0}}),this.onTranscription(t)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){qe.error("Failed to start speech recognition:",e),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(e=>e.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let n of this.analyserBuffer)e+=n*n;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(e){let t=e.detail.text;qe.debug("Heard:",t),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:t,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(e){throw this._skipEvents=!1,e}}}};var Xe=new f("AudioSystem"),K=class l{constructor(i){this.locks=[];if(!i)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=i,this.ai.audio=this,this.speechRecognition=new Re(this.ai),this.speechOutput=new Ee(this.ai)}static get isSupported(){return!(!X.lib||!O().AudioWorkletNode)}static async registerModules(i){await Promise.all([oe.registerModule(i),re.registerModule(i)])}async beginAccess(i){Xe.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(Xe.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await l.registerModules(this.context))}endAccess(i){Xe.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(Xe.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var wt=class{constructor(i,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!i)throw new Error(`Invalid array class: ${i}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=i,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((i,e)=>i+e.length,0)}feed(i){this.partialBuffers.push(i)}get canDrain(){return this.partialBuffers.reduce((e,t)=>e+t.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let i=this.ArrayClass,e=new i(this.outputBufferSize),t=0;for(;t!=e.length;){if(t>e.length)throw new Error(`Buffer overflow: ${t} > ${e.length}`);let n=e.length-t,o=this.partialBuffers[0],r=o.length-this.partialBufferOffset;r<n?(e.set(o.subarray(this.partialBufferOffset),t),t+=r,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+n),t),t+=n,this.partialBufferOffset+=n)}return e}pad(){let i=this.queuedSize%this.outputBufferSize;if(i==0)return;let e=this.ArrayClass,t=new e(i);this.feed(t)}};var vt=class{constructor(i,e,t,n){if(!i||!e||!t)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=i,this.toSampleRate=e,this.channels=t||0,this.inputBufferSize=n,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=i=>i,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(i){try{return this.outputBuffer.subarray(0,i)}catch{try{return this.outputBuffer.length=i,this.outputBuffer}catch{return this.outputBuffer.slice(0,i)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=i=>{let e=i.length,t=this.channels,n,o,r,s,a,u,d,c,p;if(e%t!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(n=this.outputBufferSize,o=this.ratioWeight,r=this.lastWeight,s=0,a=0,u=0,d=0,c=this.outputBuffer;r<1;r+=o)for(a=r%1,s=1-a,this.lastWeight=r%1,p=0;p<this.channels;++p)c[d++]=this.lastOutput[p]*s+i[p]*a;for(r-=1,e-=t,u=Math.floor(r)*t;d<n&&u<e;){for(a=r%1,s=1-a,p=0;p<this.channels;++p)c[d++]=i[u+(p>0?p:0)]*s+i[u+(t+p)]*a;r+=o,u=Math.floor(r)*t}for(p=0;p<t;++p)this.lastOutput[p]=i[u++];return this.bufferSlice(d)}}multiTap(){this.resampler=i=>{let e=i.length,t,n,o=this.channels,r,s,a,u,d,c,p,h,m;if(e%o!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(t=this.outputBufferSize,n=[],r=this.ratioWeight,s=0,u=0,d=0,c=!this.tailExists,this.tailExists=!1,p=this.outputBuffer,h=0,m=0,a=0;a<o;++a)n[a]=0;do{if(c)for(s=r,a=0;a<o;++a)n[a]=0;else{for(s=this.lastWeight,a=0;a<o;++a)n[a]=this.lastOutput[a];c=!0}for(;s>0&&u<e;)if(d=1+u-m,s>=d){for(a=0;a<o;++a)n[a]+=i[u++]*d;m=u,s-=d}else{for(a=0;a<o;++a)n[a]+=i[u+(a>0?a:0)]*s;m+=s,s=0;break}if(s===0)for(a=0;a<o;++a)p[h++]=n[a]/r;else{for(this.lastWeight=s,a=0;a<o;++a)this.lastOutput[a]=n[a];this.tailExists=!0;break}}while(u<e&&h<t);return this.bufferSlice(h)}}resample(i){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(i)}};function Vn(l){let i=l.length,e=new Int16Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,l[i]));e[i]=t<0?t*32768:t*32767}return e}function Yn(l){let i=l.length,e=new BigInt64Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,l[i]));e[i]=BigInt(Math.floor(t<0?t*32768:t*32767))*0x100000000000n}return e}function Fn(l){let i=l.length,e=new Float32Array(i);for(;i--;){let t=l[i];e[i]=t>=32768?-(65536-t)/32768:t/32767}return e}import ii from"openai";import{v4 as ti}from"uuid";var xt=new f("ChatBase"),de=class{constructor(i){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let i=new V;return i.createGroup("context").setSeparator(`
12
+ `)||"";let t=this.items.find(n=>n.id===e.id);return t?(this.tokenCount-=t.tokenCount,Object.assign(t,e),e=t):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.source===void 0&&(e.source="user"),e.sections===void 0&&(e.sections=[]),e.tokenCount=e.disabled?0:V.countTokensInText(typeof i.data=="string"?i.data:JSON.stringify(i.data))+V.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}remove(i){let e=this.items.findIndex(t=>t.id===i);return e===-1?!1:(this.tokenCount-=this.items[e].tokenCount||0,this.items.splice(e,1),!0)}getAllAsString(){return this.getAll().map(i=>i.text).join(this.separator)}getAll(){return this.items.filter(i=>!i.disabled)}empty(){this.items=[],this.tokenCount=0}},Y=(o=>(o.Text="text",o.ToolCall="tool_call",o.ToolResult="tool_result",o.Thinking="thinking",o.Other="other",o))(Y||{});var D=new f("ElevenLabs");function $e(l,i,e="pcm_24000"){let t=[],n=Date.now(),o=!1,r,s;return{stream:new ReadableStream({start:c=>{r=c,s=new WebSocket(`wss://api.elevenlabs.io/v1/text-to-speech/${i}/stream-input?inactivity_timeout=120&output_format=${e}`),s.addEventListener("open",()=>{D.debug(`[at ${Date.now()-n}ms] WebSocket connected`),s.send(JSON.stringify({text:" ","xi-api-key":l}));for(let p of t)s.send(JSON.stringify({text:p}));t.length=0}),s.addEventListener("close",()=>{D.debug(`[at ${Date.now()-n}ms] WebSocket closed`),r?.close(),o=!0}),s.addEventListener("message",p=>{let h=JSON.parse(p.data);if(h.final){s.close(),r?.close();return}if(D.debug(`[at ${Date.now()-n}ms] Message received: ${h.audio?.length||0} bytes of audio data`),!h.audio)return;let m=Uint8Array.from(atob(h.audio),g=>g.charCodeAt(0));r?.enqueue(m)})},cancel:()=>{D.debug(`[at ${Date.now()-n}ms] Stream cancelled`),s?.close(),o=!0}}),sendText:c=>{c&&(D.debug(`[at ${Date.now()-n}ms] Sending text: "${c}"`),s?.readyState===WebSocket.OPEN?s.send(JSON.stringify({text:c})):t.push(c))},endText:()=>{s?.readyState===WebSocket.OPEN?s.send(JSON.stringify({text:""})):t.push("")},get isClosed(){return o}}}function gt(l,i="pcm_16000",e=16e3,t="vad"){let n=[],o=Date.now(),r=!1,s,a;return{stream:new ReadableStream({start:async h=>{s=h;let m=await fetch("https://api.elevenlabs.io/v1/single-use-token/realtime_scribe",{method:"POST",headers:{"xi-api-key":l}});if(!m.ok)throw new Error(`Failed to generate single-use token: ${m.status} ${m.statusText}`);let g=await m.json(),y=g.token;if(!y)throw new Error(`No token found in response: ${JSON.stringify(g)}`);a=new WebSocket(`wss://api.elevenlabs.io/v1/speech-to-text/realtime?token=${encodeURIComponent(y)}&audio_format=${i}&commit_strategy=${t}`),a.addEventListener("open",()=>{D.debug(`[at ${Date.now()-o}ms] WebSocket connected`);for(let w of n)a.send(w);n.length=0}),a.addEventListener("close",()=>{D.debug(`[at ${Date.now()-o}ms] WebSocket closed`),s?.close(),r=!0}),a.addEventListener("message",w=>{let k=JSON.parse(w.data);k.message_type=="committed_transcript"?(D.debug(`[at ${Date.now()-o}ms] Committed transcript received: "${k.text}"`),s?.enqueue(k.text)):k.error&&(D.warn(`[at ${Date.now()-o}ms] Error received: ${k.error}`),s?.error(new Error(k.error)),a?.close(),r=!0)})},cancel:()=>{D.debug(`[at ${Date.now()-o}ms] Stream cancelled`),a?.close(),r=!0}}),sendAudio:h=>{let m=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:btoa(String.fromCharCode(...new Uint8Array(h))),commit:!1,sample_rate:e});D.debug(`[at ${Date.now()-o}ms] Sending audio: ${h.byteLength} bytes`),a?.readyState===WebSocket.OPEN?a.send(m):n.push(m)},commit:()=>{let h=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:e});a?.readyState===WebSocket.OPEN?a.send(h):n.push(h)},close:()=>{D.debug("Closing connection"),a?.close(),r=!0,setTimeout(()=>{s?.close()},1e3)},get isClosed(){return r}}}var Ce=new f("SpeechOutput"),ft=.5,Kt=.8,Ee=class extends EventTarget{constructor(e){super();this.autoSpeak=!0;this.preemptiveConnection=!0;this.processedMessages=new Set;this.maxVolumeHeard=0;this._queuedText=[];this._queueActive=!1;this.ai=e,this.ai.addEventListener("output",t=>this.onOutputFromAI(t)),this.ai.audio?.speechRecognition.addEventListener("speechstart",t=>this.interrupt())}onOutputFromAI(e){let t=e.detail.messages,n=e.detail.isPartial;if(!(!this.ai?.audio?.speechRecognition.isRunning||!this.autoSpeak)){for(let o of t)if(!o.streamingInProgress&&!(!o.id||this.processedMessages.has(o.id))){this.processedMessages.add(o.id);for(let r of o.sections||[])r.type=="text"&&r.text&&this.speak(r.text)}n||this.processedMessages.clear()}}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let n of this.analyserBuffer)e+=n*n;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}async speak(e){if(!this.ai?.config?.voice?.providerID)return Ce.warn("No voice provider configured");this.ai._voiceTracker?.(`Added text to queue: ${e}`),this._queuedText.push(e),this._runQueue()}async _runQueue(){if(this._queueActive)return;let e=this._queuedText.shift();if(!e)return;this._queueActive=!0;let t=`speech-${Ht++}`;try{await this.ai.audio.beginAccess(t),await this._speakWithLock(e)}finally{this._queueActive=!1,this.ai.audio.endAccess(t)}this._queuedText.length?await this._runQueue():this.onSpeechEnd()}_getElevenLabsConnection(){let e=this._elevenLabsPrecachedConnection;return(!e||e.isClosed)&&(e=$e(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),this.preemptiveConnection&&(this._elevenLabsPrecachedConnection=$e(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),e}async _speakWithLock(e){let t=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:e}});if(this.dispatchEvent(t),e=t.detail.message,t.defaultPrevented||!e)return;this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Kt);let n=this.ai?._voiceTracker||Ce.timer(`${this.ai.config.voice.providerID} voice`);n(`Speak: ${e}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let o=new oe(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",a=>{let u=a;n(`PCM stream ${u.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!u.detail.interrupted&&(this.currentPlayer=void 0)});let r=Date.now(),s=null;if(this.ai.config.voice.providerID=="openai"){let a=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:e,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});if(!a.ok){Ce.warn(`Failed to generate voice sample: ${a.status} ${a.statusText}`);return}s=a.body}else if(this.ai.config.voice.providerID=="elevenlabs"){let a=this._getElevenLabsConnection();a.sendText(e),a.endText(),s=a.stream}else{Ce.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}n(`Received response in ${Date.now()-r}ms`),this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),n("Playing PCM stream"),await o.play(s),n("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(this._queuedText=[],!this.currentPlayerVolume)return;this.ai._voiceTracker?.("Interrupted");let e=this.currentPlayerVolume,t=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=ft);let n=400;e.gain.linearRampToValueAtTime(0,n/1e3),await new Promise(o=>setTimeout(o,n+250)),e.disconnect(),t?.stop(),t?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=ft)}},Ht=1;function Ne(l,i){let e=i.reduce((a,u)=>a+u.byteLength,0),t=new DataView(new ArrayBuffer(44));t.setUint8(0,82),t.setUint8(1,73),t.setUint8(2,70),t.setUint8(3,70),t.setUint32(4,44+e,!0),t.setUint8(8,87),t.setUint8(9,65),t.setUint8(10,86),t.setUint8(11,69);let n=1,o=32,r=n*o/8,s=l*r;return t.setUint8(12,102),t.setUint8(13,109),t.setUint8(14,116),t.setUint8(15,32),t.setUint32(16,16,!0),t.setUint16(20,3,!0),t.setUint16(22,n,!0),t.setUint32(24,l,!0),t.setUint32(28,s,!0),t.setUint16(32,r,!0),t.setUint16(34,o,!0),t.setUint8(36,100),t.setUint8(37,97),t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W1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var re=class extends AudioWorkletNode{constructor(e,t,n,o){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=n;let r=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!r.includes(n))throw new Error(`Invalid format ${n}, must be one of: ${r.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=s=>this.onWorkletMessage(s),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:n,bufferSize:o})}static async registerModule(e){await e.audioWorklet.addModule(bt)}onWorkletMessage(e){if(e.data.action=="data"){let t=null;if(this.format=="int16"&&(t=new Int16Array(e.data.buffer)),this.format=="int64"&&(t=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(t=new Float32Array(e.data.buffer)),!t)throw new Error(`Invalid format: ${this.format}`);this.onData(t),this.dispatchEvent(new CustomEvent("data",{detail:{data:t}}))}}onData(e){}};var Qe=16e3,Ae=256,se=8,ge=new f("VoiceDetectionNode"),fe=class fe extends re{constructor(e){super(e,Qe,"float32",Ae*se);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!fe.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return Qe}get numberOfSamples(){return Ae}get numberOfSampleChunks(){return se}get outputBufferSize(){return Ae*se}get isModelLoaded(){return!!this.vad}async loadModel(){ge.debug("Loading VAD model"),this.vad=await X.load(fe.vadModelURL),this.vad.ignoreIfBusy=!0,ge.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],Qe),this.vad.makeState("h","hn","float32",[2,se,64]),this.vad.makeState("c","cn","float32",[2,se,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new X.onnx.Tensor(e,[se,Ae])});if(!t)return;this.currentProbability=0;for(let r=0;r<t.output.data.length;r++)t.output.data[r]>this.currentProbability&&(this.currentProbability=t.output.data[r]);let n=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>n;if(!o&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=o,o&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),ge.debug("Started speaking")):o?this.lastVoiceActiveDate=Date.now():!o&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!o&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),ge.debug("Stopped speaking after timeout")),!o){let r=Date.now();r>this.nextVadReset&&(this.nextVadReset=r+5e3,this.vad.resetState())}}catch(t){ge.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};fe.vadModelURL="";var ae=fe;var yt=new f("VoiceChunkOutputNode"),F=class extends ae{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((e,t)=>e+t.length,0)/8e3}async onData(e){if(await super.onData(e),this.isVoiceActive&&!this._voiceRecording){yt.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let t of this.buffers)this.recordedBuffers.push(t),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:t,isFinal:!1}})),this.onVoiceChunk(t);this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!0}})),this.onVoiceChunk(e),this._voiceRecording=!1;let t=this.recordedBuffers.reduce((n,o)=>n+o.length,0);yt.debug(`Voice complete, recorded ${(t/8e3).toFixed(2)} seconds of audio, ${t*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(e);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(e){}onVoiceEnd(e){}};var Le=new f("OpenAITranscriptionNode"),De=class extends F{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=Le.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let n=Ne(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let r=new FormData;r.append("file",n),r.append("model","whisper-1"),r.append("response_format","text");let s=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:r,signal:this.lastRequestAbortController.signal});if(!s.ok)throw new Error(`Failed to generate voice sample: ${s.status} ${s.statusText}`);t("Response received"),o=await s.text(),t("Content received: "+o),this.lastRequestAbortController=void 0}catch(r){Le.error(`Failed to transcribe speech: ${r.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return Le.debug("Transcription complete, but no text was found");Le.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(e){}};var We=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var P=new f("IntelliWeaveTranscriptionNode"),$t="wss://speech.intelliweave.ai/api/v1/transcribe",Pe=class Pe extends F{constructor(e,t){super(e);this.apiAddress=$t;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(P.debug("Opening WebSocket connection"),this.ws=new We(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(e.buffer),this.ws.onopen=()=>{P.debug("WebSocket connection opened")},this.ws.addEventListener("message",n=>{let o=JSON.parse(n.data);if(o.error)return P.warn("Error: "+o.error);if(o.type!="transcription")return P.warn("Invalid response type",o);if(o.streaming&&!o.final)return P.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return P.warn(`Empty transcription (${o.processingTime}ms)`);P.debug(`Transcription: ${o.text} (${o.processingTime}ms)`),this.onVoiceTranscription(o.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",n=>P.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{P.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),Pe.debugExportWav){let t=Ne(this.sampleRate,e),n=document.createElement("a");n.href=URL.createObjectURL(t),n.download="recording.wav",n.click()}}onVoiceTranscription(e){}onSocketClose(){P.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};Pe.debugExportWav=!1;var Ge=Pe;var U={name:"@intelliweave/embedded",version:"2.2.84",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{v4 as qt}from"uuid";var ei=new f("Statistics"),be=[];async function C(l,i){let e={...i,event_id:qt(),event_date:new Date().toISOString(),sdk_version:U.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(be.push(e),!l||(await new Promise(n=>setTimeout(n,5e3)),be.length===0))return;let t=be.slice();be.length=0;try{let n=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){ei.warn("Failed to submit analytics event:",n),be.push(...t);return}}var le=new f("ElevenLabsTranscriptionNode"),Ze=class extends F{constructor(e,t){super(e);this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0;let t=new Int16Array(e.length);for(let o=0;o<e.length;o++)t[o]=e[o]*32767;!this.connection||this.connection.isClosed?(this.connection?.close(),this.connection=void 0,le.debug(`Opening connection. sampleRate: ${this.sampleRate} format=${this.format}`),this.connection=gt(this.apiKey,"pcm_"+this.sampleRate,this.sampleRate,"manual"),this.startReading(this.connection),this.connection.sendAudio(t.buffer)):this.connection.sendAudio(t.buffer);let n=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{le.debug("Shutting down WebSocket connection"),this.connection?.close(),this.connection=void 0},n)}async startReading(e){let t=e.stream.getReader();try{for(;;){let{value:n,done:o}=await t.read();if(o){le.debug("Stream closed");break}if(!n?.trim()){le.warn("Empty transcription received");continue}this.isTranscribing=!1,le.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}}catch(n){le.error(`Failed to read transcription stream: ${n.message}`),this.connection==e&&(this.connection=void 0);return}}async onVoiceEnd(e){this.connection?.commit()}onVoiceTranscription(e){}};var qe=new f("SpeechRecognition"),Re=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e}get isSupported(){if(!X.lib||!this.ai?.vadModel||!O().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey)){if(!(this.ai?.config?.transcription?.providerID=="elevenlabs"&&this.ai.config?.transcription?.apiKey))return!1}}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let e=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,e.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),ae.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new De(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):this.ai?.config?.transcription?.providerID=="elevenlabs"?(this.voiceDetection=new Ze(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new Ge(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",t=>{this.ai._voiceTracker=qe.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),C(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("speechend",t=>{this.ai._voiceTracker?.("Speech ended");let n=this.recordingStartTime?Date.now()-this.recordingStartTime:0;C(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:n}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),C(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:t.detail.confidence||void 0}}),this.onTranscription(t)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){qe.error("Failed to start speech recognition:",e),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(e=>e.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let n of this.analyserBuffer)e+=n*n;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(e){let t=e.detail.text;qe.debug("Heard:",t),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:t,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(e){throw this._skipEvents=!1,e}}}};var Xe=new f("AudioSystem"),K=class l{constructor(i){this.locks=[];if(!i)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=i,this.ai.audio=this,this.speechRecognition=new Re(this.ai),this.speechOutput=new Ee(this.ai)}static get isSupported(){return!(!X.lib||!O().AudioWorkletNode)}static async registerModules(i){await Promise.all([oe.registerModule(i),re.registerModule(i)])}async beginAccess(i){Xe.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(Xe.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await l.registerModules(this.context))}endAccess(i){Xe.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(Xe.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var wt=class{constructor(i,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!i)throw new Error(`Invalid array class: ${i}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=i,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((i,e)=>i+e.length,0)}feed(i){this.partialBuffers.push(i)}get canDrain(){return this.partialBuffers.reduce((e,t)=>e+t.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let i=this.ArrayClass,e=new i(this.outputBufferSize),t=0;for(;t!=e.length;){if(t>e.length)throw new Error(`Buffer overflow: ${t} > ${e.length}`);let n=e.length-t,o=this.partialBuffers[0],r=o.length-this.partialBufferOffset;r<n?(e.set(o.subarray(this.partialBufferOffset),t),t+=r,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+n),t),t+=n,this.partialBufferOffset+=n)}return e}pad(){let i=this.queuedSize%this.outputBufferSize;if(i==0)return;let e=this.ArrayClass,t=new e(i);this.feed(t)}};var vt=class{constructor(i,e,t,n){if(!i||!e||!t)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=i,this.toSampleRate=e,this.channels=t||0,this.inputBufferSize=n,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=i=>i,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(i){try{return this.outputBuffer.subarray(0,i)}catch{try{return this.outputBuffer.length=i,this.outputBuffer}catch{return this.outputBuffer.slice(0,i)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=i=>{let e=i.length,t=this.channels,n,o,r,s,a,u,d,c,p;if(e%t!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(n=this.outputBufferSize,o=this.ratioWeight,r=this.lastWeight,s=0,a=0,u=0,d=0,c=this.outputBuffer;r<1;r+=o)for(a=r%1,s=1-a,this.lastWeight=r%1,p=0;p<this.channels;++p)c[d++]=this.lastOutput[p]*s+i[p]*a;for(r-=1,e-=t,u=Math.floor(r)*t;d<n&&u<e;){for(a=r%1,s=1-a,p=0;p<this.channels;++p)c[d++]=i[u+(p>0?p:0)]*s+i[u+(t+p)]*a;r+=o,u=Math.floor(r)*t}for(p=0;p<t;++p)this.lastOutput[p]=i[u++];return this.bufferSlice(d)}}multiTap(){this.resampler=i=>{let e=i.length,t,n,o=this.channels,r,s,a,u,d,c,p,h,m;if(e%o!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(t=this.outputBufferSize,n=[],r=this.ratioWeight,s=0,u=0,d=0,c=!this.tailExists,this.tailExists=!1,p=this.outputBuffer,h=0,m=0,a=0;a<o;++a)n[a]=0;do{if(c)for(s=r,a=0;a<o;++a)n[a]=0;else{for(s=this.lastWeight,a=0;a<o;++a)n[a]=this.lastOutput[a];c=!0}for(;s>0&&u<e;)if(d=1+u-m,s>=d){for(a=0;a<o;++a)n[a]+=i[u++]*d;m=u,s-=d}else{for(a=0;a<o;++a)n[a]+=i[u+(a>0?a:0)]*s;m+=s,s=0;break}if(s===0)for(a=0;a<o;++a)p[h++]=n[a]/r;else{for(this.lastWeight=s,a=0;a<o;++a)this.lastOutput[a]=n[a];this.tailExists=!0;break}}while(u<e&&h<t);return this.bufferSlice(h)}}resample(i){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(i)}};function Vn(l){let i=l.length,e=new Int16Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,l[i]));e[i]=t<0?t*32768:t*32767}return e}function Yn(l){let i=l.length,e=new BigInt64Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,l[i]));e[i]=BigInt(Math.floor(t<0?t*32768:t*32767))*0x100000000000n}return e}function Fn(l){let i=l.length,e=new Float32Array(i);for(;i--;){let t=l[i];e[i]=t>=32768?-(65536-t)/32768:t/32767}return e}import ii from"openai";import{v4 as ti}from"uuid";var xt=new f("ChatBase"),de=class{constructor(i){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let i=new V;return i.createGroup("context").setSeparator(`
13
13
 
14
14
  `),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")}getBaseURL(){if(!this.config.endpoint)return;let i=this.config.endpoint;return i.endsWith("/chat/completions")&&(i=i.substring(0,i.length-17)),i}async sendMessage(i,e){throw new Error("Not implemented")}addUserMessage(i){throw new Error("Not implemented")}addAssistantMessage(i){throw new Error("Not implemented")}addTextMessage(i,e,t){this.messageGroup.add({id:"msg-"+ti(),source:e,data:t,sections:[{type:"text",text:i}]})}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,data:i,cannotRemove:!i.canRemove,sortOrder:101,disabled:!!i.kbItem?.disabled})}findToolBySafeName(i){return this.toolGroup.getAll().find(e=>e.id==i||e.data?.kbItem?.name==i)?.data}async executeTool(i,e){if(!i)throw new Error("Tool not found");xt.debug(`Executing tool '${i.name}'`,e,i),this.config.onAIToolStart?.(i.kbItem?.name||i.name,e);let t;try{t=await i.callback(e)}catch(n){throw xt.error(`Error executing tool '${i.name}'`,n),n}return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),t}};import{v4 as ni}from"uuid";var et=new f("ChatGPT"),Be=class extends de{addUserMessage(i){this.addTextMessage(i,"user",{role:"user",content:i||""})}addAssistantMessage(i){this.addTextMessage(i,"assistant",{role:"assistant",content:i||""})}createOpenAIClient(){return new ii({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(i,e){this.addUserMessage(i);let t=this.createOpenAIClient(),n=!0,o=[];for(;n;){let r="msg-"+ni();n=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),et.debug("Before processing state",{messages:this.messageGroup.getAll().map(c=>c.data),tools:this.toolGroup.getAll().map(c=>c.data),context:this.contextGroup.getAll().map(c=>c.text)});let s=this.toolGroup.getAll().filter(c=>!!c?.data).map(c=>({type:"function",function:{name:c.data.name,description:c.data.description||"",parameters:{type:"object",...c.data?.params}}})),a,u;if(this.config.stream){let c=t.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:s,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let p of c){let h=c.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!h)continue;let m=this.parseMessageBlock(r,h,void 0,!0);this.config.onAIMessage?.([...o,m],!0),e?.([...o,m])}a=await c.finalMessage(),u=await c.totalUsage()}else{let c=await t.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:s,parallel_tool_calls:!0});a=c.choices[0].message,u=c.usage}a.role=="assistant"&&!a.content&&!a.tool_calls?.length&&(a.content=""),et.debug("Message received",a);let d=this.messageGroup.add(this.parseMessageBlock(r,a,u,!1));o.push(d),await Promise.all((a.tool_calls||[]).map(async c=>{if(c.type!="function")return;let p=this.findToolBySafeName(c.function.name);try{let h=null;try{h=c.function.arguments?JSON.parse(c.function.arguments):null}catch(y){throw new Error(`The AI provided invalid JSON arguments for tool call ${c.function.name}: ${y.message}`)}let m=await this.executeTool(p,h),g=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:c.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolSuccessResponse:m,toolCallInstanceID:c.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:c.id,content:m}});o.push(g)}catch(h){let m=h?.message||"An unknown error occurred",g=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:c.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolErrorResponse:m,toolCallInstanceID:c.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:c.id,content:`Error performing tool call ${c.function.name}: ${m}`}});o.push(g)}n=!0,this.config.onAIMessage?.(o,!0),e?.(o)})),this.stats.tokensUsed+=u?.total_tokens||0}return this.config.onAIMessage?.(o,!1),e?.(o),o}parseMessageBlock(i,e,t,n){let o=[];e.reasoning&&o.push({type:"thinking",text:e.reasoning});for(let r of e.tool_calls||[]){if(r.type!="function")continue;let s=this.findToolBySafeName(r.function.name),a=null;if(r.function.arguments)try{a=JSON.parse(r.function.arguments)}catch(u){n||et.error(`Failed to parse tool parameters for tool call ${r.function.name}:`,u)}o.push({type:"tool_call",toolName:r.function.name,toolKbID:s?.kbItem?.id,toolKbName:s?.kbItem?.name,toolCallInstanceID:r.id,toolCallHiddenInUI:s?.kbItem?.hideActionInUI,toolParameters:a})}return typeof e.content=="string"&&o.push({type:"text",text:e.content||""}),{id:i,data:e,sections:o,source:"assistant",streamingInProgress:n,usage:{inputTokens:t?.prompt_tokens||0,outputTokens:t?.completion_tokens||0,cachedInputTokens:0,totalTokens:(t?.prompt_tokens||0)+(t?.completion_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].data?.role=="tool";)this.messageGroup.items.shift()}};import oi from"@anthropic-ai/sdk";import{v4 as ri}from"uuid";var Mt=new f("AnthropicChat"),je=class extends de{addUserMessage(i){this.addTextMessage(i,"user",{role:"user",content:i||""})}addAssistantMessage(i){this.addTextMessage(i,"assistant",{role:"assistant",content:i||""})}async sendMessage(i,e){this.addUserMessage(i);let t=new oi({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),n=!0,o=[];for(;n;){n=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),Mt.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.data),tools:this.toolGroup.getAll().map(d=>d.data),context:this.contextGroup.getAll().map(d=>d.text)});let r=this.toolGroup.getAll().map(d=>({name:d.data?.name||"",description:d.data?.description||"",input_schema:{...d.data?.params,type:"object"}})),s;if(this.config.stream){let d=t.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(c=>c.data),tools:r,stream:!0});d.on("streamEvent",(c,p)=>{let h=this.parseMessageBlock(p,!0);this.config.onAIMessage?.([...o,h],!0),e?.([...o,h])});try{s=await d.finalMessage()}catch(c){throw c?.error?.error?.message?c.error.error:c}}else try{s=await t.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(d=>d.data),tools:r})}catch(d){throw d?.error?.error?.message?d.error.error:d}if(Mt.debug("Message received",s),s.content?.length){let d=this.messageGroup.add(this.parseMessageBlock(s,!1));o.push(d)}let a=[],u=[];if(await Promise.all(s.content.map(async d=>{if(d.type!="tool_use")return;let c=this.findToolBySafeName(d.name);try{let p=await this.executeTool(c,d.input);u.push({type:"tool_result",tool_use_id:d.id,content:p}),a.push({type:"tool_result",toolKbID:c?.kbItem?.id,toolKbName:c?.kbItem?.name,toolName:d.name,toolSuccessResponse:p,toolCallInstanceID:d.id,toolCallHiddenInUI:c?.kbItem?.hideActionInUI})}catch(p){let h=p?.message||"An unknown error occurred";u.push({type:"tool_result",tool_use_id:d.id,content:`Error performing tool call ${d.name}: ${h}`}),a.push({type:"tool_result",toolKbID:c?.kbItem?.id,toolKbName:c?.kbItem?.name,toolName:d.name,toolErrorResponse:h,toolCallInstanceID:d.id,toolCallHiddenInUI:c?.kbItem?.hideActionInUI})}})),u.length>0){let d=this.messageGroup.add({id:"msg-"+ri(),sections:a,data:{role:"user",content:u}});o.push(d),n=!0,this.config.onAIMessage?.(o,!0),e?.(o)}this.stats.tokensUsed+=s.usage.input_tokens+s.usage.output_tokens}return this.config.onAIMessage?.(o,!1),e?.(o),o}parseMessageBlock(i,e){let t=[];for(let n of i.content)if(n.type=="thinking")t.push({type:"thinking",text:n.thinking||""});else if(n.type=="text")t.push({type:"text",text:n.text||""});else if(n.type=="tool_use"){let o=this.findToolBySafeName(n.name);t.push({type:"tool_call",toolName:n.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:n.input,toolCallInstanceID:n.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:i.id,data:{role:i.role,content:i.content},sections:t,source:"assistant",streamingInProgress:e,usage:{inputTokens:i.usage?.input_tokens||0,outputTokens:i.usage?.output_tokens||0,cachedInputTokens:i.usage?.cache_read_input_tokens||0,totalTokens:(i.usage?.input_tokens||0)+(i.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import ui from"minisearch";var It=l=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,hideActionInUI:"after-complete",disabled:!l?.knowledgeBase?.allowRagSearch,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(i,e)=>{let t=await e.knowledgeBase.search(i.query),n=e;n._lastKBsearch=i.query,n._nextRequestUseKBitems=t;let o=t.filter(s=>s.type!="action").map(s=>"- "+s.name).join(`
15
15
  `)||"- (none)",r=t.filter(s=>s.type=="action").map(s=>"- "+s._functionID).join(`
@@ -1284,6 +1284,7 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
1284
1284
  flex-direction: unset;
1285
1285
  gap: 10px;
1286
1286
  }
1287
+
1287
1288
  #root.container-mode #web-weaver-embed-inner {
1288
1289
  flex: 1 1 auto;
1289
1290
  min-height: 0;
@@ -1555,6 +1556,21 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
1555
1556
  overflow: hidden;
1556
1557
  text-overflow: ellipsis;
1557
1558
  }
1559
+ #root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner {
1560
+ flex: 1 1 auto;
1561
+ min-height: 0;
1562
+ max-height: none;
1563
+ height: auto;
1564
+ overflow-x: hidden;
1565
+ overflow-y: auto;
1566
+ width: 100%;
1567
+ max-width: none;
1568
+ margin: 2px;
1569
+ padding: 12px;
1570
+ align-content: start;
1571
+ flex-direction: unset;
1572
+ gap: 10px;
1573
+ }
1558
1574
  }
1559
1575
 
1560
1576
  </style>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intelliweave/embedded",
3
- "version": "2.2.83",
3
+ "version": "2.2.84",
4
4
  "description": "Integrate IntelliWeave into your app or website.",
5
5
  "main": "./dist/webpack/index.js",
6
6
  "types": "./dist/webpack/index.d.ts",