@intelliweave/embedded 2.1.74 → 2.1.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/component/component.d.ts +1 -1
- package/dist/component/component.js +2 -2
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.d.ts +1 -1
- package/dist/node/node.js +2 -2
- package/dist/react/react.d.ts +1 -1
- package/dist/react/react.js +2 -2
- package/dist/script-tag/script-tag.js +2 -2
- package/dist/webpack/index.d.ts +1 -1
- package/dist/webpack/index.js +2 -2
- package/package.json +1 -1
- package/.github/workflows/test-pr.yml +0 -31
- package/examples/react-test/index.html +0 -14
- package/examples/react-test/package-lock.json +0 -1844
- package/examples/react-test/package.json +0 -25
- package/examples/react-test/src/App.tsx +0 -69
- package/examples/react-test/src/main.tsx +0 -10
- package/examples/react-test/vite.config.ts +0 -8
|
@@ -1088,7 +1088,7 @@ interface SubAgentConfig {
|
|
|
1088
1088
|
/** Extra knowledge base sources for the sub-agent */
|
|
1089
1089
|
knowledge?: KnowledgeFetcher;
|
|
1090
1090
|
/** Optional extra configuration for the subagent instance */
|
|
1091
|
-
config?: Partial<
|
|
1091
|
+
config?: Partial<IntelliWeaveConfig>;
|
|
1092
1092
|
/** Called when the subagent is loaded */
|
|
1093
1093
|
onAgentLoaded?: (agent: IntelliWeave) => Promise<void> | void;
|
|
1094
1094
|
}
|
|
@@ -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=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?n(parseInt(g,10)):r(new t_(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:y}));break;default:r(new t_(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:g,line:y}));break}}function p(){c.length>0&&e({id:a,event:l||void 0,data:c.endsWith(`
|
|
111
111
|
`)?c.slice(0,-1):c}),a=void 0,c="",l=""}function m(h={}){o&&h.consume&&d(o),s=!0,a=void 0,c="",l="",o=""}return{feed:u,reset:m}}function EJ(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 r_=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=MM({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 PJ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Is=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},n_=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=wM(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??PJ}async _authThenStart(){if(!this._authProvider)throw new Io("No auth provider");let e;try{e=await qf(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 Io;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=e_(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 Is(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,c=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new r_({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=Ig.parse(JSON.parse(p.data));Sa(h)&&(c=!0,o!==void 0&&(h.id=o)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(n||a)&&!c&&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)&&!c&&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 Io("No auth provider");if(await qf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Io("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:_p(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),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Is(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:p,scope:m}=nI(a);if(this._resourceMetadataUrl=p,this._scope=m,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Io;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:p,scope:m,error:h}=nI(a);if(h==="insufficient_scope"){let g=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===g)throw new Is(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=g??void 0,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Io;return this.send(e)}}throw new Is(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=>Ig.parse(m)):[Ig.parse(f)];for(let m of p)this.onmessage?.(m)}else throw await a.body?.cancel(),new Is(-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 Is(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 Es={name:"@intelliweave/embedded",version:"2.1.74",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-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};var er=new Ne("MCPKnowledgeClient"),AJ="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",i_=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(){er.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||AJ));let i=new Qy({name:Es.name,version:Es.version}),o=new n_(r,{requestInit:{headers:n}});return await i.connect(o),er.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=e,e.onerror=r=>{er.error(`MCP client error: ${r.message}`)},e.onclose=()=>{er.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(b0,r=>{r.params.level=="critical"?er.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?er.error(`[Server] ${r.params.data}`):r.params.level=="error"?er.error(`[Server] ${r.params.data}`):r.params.level=="warning"?er.warn(`[Server] ${r.params.data}`):r.params.level=="info"?er.info(`[Server] ${r.params.data}`):r.params.level=="debug"?er.debug(`[Server] ${r.params.data}`):er.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Sp,r=>{er.debug("Tool list changed",r),this.fetchTools()}),er.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let i=await this.client.listTools({cursor:r});r=i.nextCursor;for(let o of i.tools||[])e.push(o);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let o=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:s=>this.performToolCall(i.name,s),disabled:o})}er.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,er.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 er.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(),er.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 er.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 zJ=new Ne("Statistics"),Bf=[];async function Lr(t,e){let r={...e,event_id:sr(),event_date:new Date().toISOString(),sdk_version:Es.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Bf.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Bf.length===0))return;let n=Bf.slice();Bf.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){zJ.warn("Failed to submit analytics event:",i),Bf.push(...n);return}}var Ya=new Ne("KnowledgeBase"),sI=1,o_=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()=>CP(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.${sI++}`),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&&ht().knowledgeBaseSources&&(e=e.concat(ht().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Ya.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 l=>{try{let u=Date.now(),d=await l.query(e);return Ya.debug(`Source '${l.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Ya.warn(`Knowledge source '${l.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&ht().knowledgeBase&&(o=o.concat(ht().knowledgeBase)),o=o.filter(l=>l&&!l.disabled);for(let l=0;l<o.length;l++){let u=o[l];u.id=u.id||`temp.${l}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new Gd({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let c=s.search(e).map(l=>o.find(u=>u.id==l.id));for(let l of o)l.isContext&&(c.find(u=>u.id===l.id)||c.push(l));return this.lastResults=c,Lr(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Ya.debug("Found results:",c),c}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${sI++}`),Ya.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(c,l)=>{Ya.debug(`Calling remote knowledge base action: ${c.id}`);let u={type:"action",userID:this.ai.userID,actionID:c.id,parameters:l},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=c=>{for(let l of c){if(!l.id){Ya.warn("KB item skipped since it has no ID.",l);continue}let u=n.find(d=>d.id==l.id);if(u){u.name=l.name||u.name||"",u.content=l.content||u.content||"",u.disabled=l.disabled??u.disabled,u.isContext=l.isContext??u.isContext,u.parameters=l.parameters||u.parameters||[],u.tags=l.tags||u.tags,u.type=l.type||u.type;continue}n.push({...l,action:d=>s(l,d)})}};this.registerSource(r,async c=>{if(o&&i.includes(c))return n;let l={type:"search",userID:this.ai?.userID||"",query:c},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(c)||i.push(c),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.${sI++}`);let r=new i_(e);return this.registerSource(e.id,n=>r.search(n)),r}};var s_=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
113
|
+
`&&n++}}return[e,r]}var r_=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=MM({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 PJ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Is=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},n_=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=wM(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??PJ}async _authThenStart(){if(!this._authProvider)throw new Io("No auth provider");let e;try{e=await qf(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 Io;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=e_(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 Is(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,c=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new r_({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=Ig.parse(JSON.parse(p.data));Sa(h)&&(c=!0,o!==void 0&&(h.id=o)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(n||a)&&!c&&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)&&!c&&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 Io("No auth provider");if(await qf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Io("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:_p(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),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Is(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:p,scope:m}=nI(a);if(this._resourceMetadataUrl=p,this._scope=m,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Io;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:p,scope:m,error:h}=nI(a);if(h==="insufficient_scope"){let g=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===g)throw new Is(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=g??void 0,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Io;return this.send(e)}}throw new Is(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=>Ig.parse(m)):[Ig.parse(f)];for(let m of p)this.onmessage?.(m)}else throw await a.body?.cancel(),new Is(-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 Is(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 Es={name:"@intelliweave/embedded",version:"2.1.75",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-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};var er=new Ne("MCPKnowledgeClient"),AJ="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",i_=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(){er.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||AJ));let i=new Qy({name:Es.name,version:Es.version}),o=new n_(r,{requestInit:{headers:n}});return await i.connect(o),er.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=e,e.onerror=r=>{er.error(`MCP client error: ${r.message}`)},e.onclose=()=>{er.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(b0,r=>{r.params.level=="critical"?er.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?er.error(`[Server] ${r.params.data}`):r.params.level=="error"?er.error(`[Server] ${r.params.data}`):r.params.level=="warning"?er.warn(`[Server] ${r.params.data}`):r.params.level=="info"?er.info(`[Server] ${r.params.data}`):r.params.level=="debug"?er.debug(`[Server] ${r.params.data}`):er.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Sp,r=>{er.debug("Tool list changed",r),this.fetchTools()}),er.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let i=await this.client.listTools({cursor:r});r=i.nextCursor;for(let o of i.tools||[])e.push(o);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let o=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:s=>this.performToolCall(i.name,s),disabled:o})}er.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,er.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 er.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(),er.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 er.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 zJ=new Ne("Statistics"),Bf=[];async function Lr(t,e){let r={...e,event_id:sr(),event_date:new Date().toISOString(),sdk_version:Es.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Bf.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Bf.length===0))return;let n=Bf.slice();Bf.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){zJ.warn("Failed to submit analytics event:",i),Bf.push(...n);return}}var Ya=new Ne("KnowledgeBase"),sI=1,o_=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()=>CP(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.${sI++}`),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&&ht().knowledgeBaseSources&&(e=e.concat(ht().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Ya.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 l=>{try{let u=Date.now(),d=await l.query(e);return Ya.debug(`Source '${l.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Ya.warn(`Knowledge source '${l.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&ht().knowledgeBase&&(o=o.concat(ht().knowledgeBase)),o=o.filter(l=>l&&!l.disabled);for(let l=0;l<o.length;l++){let u=o[l];u.id=u.id||`temp.${l}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new Gd({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let c=s.search(e).map(l=>o.find(u=>u.id==l.id));for(let l of o)l.isContext&&(c.find(u=>u.id===l.id)||c.push(l));return this.lastResults=c,Lr(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Ya.debug("Found results:",c),c}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${sI++}`),Ya.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(c,l)=>{Ya.debug(`Calling remote knowledge base action: ${c.id}`);let u={type:"action",userID:this.ai.userID,actionID:c.id,parameters:l},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=c=>{for(let l of c){if(!l.id){Ya.warn("KB item skipped since it has no ID.",l);continue}let u=n.find(d=>d.id==l.id);if(u){u.name=l.name||u.name||"",u.content=l.content||u.content||"",u.disabled=l.disabled??u.disabled,u.isContext=l.isContext??u.isContext,u.parameters=l.parameters||u.parameters||[],u.tags=l.tags||u.tags,u.type=l.type||u.type;continue}n.push({...l,action:d=>s(l,d)})}};this.registerSource(r,async c=>{if(o&&i.includes(c))return n;let l={type:"search",userID:this.ai?.userID||"",query:c},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(c)||i.push(c),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.${sI++}`);let r=new i_(e);return this.registerSource(e.id,n=>r.search(n)),r}};var s_=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
|
|
|
@@ -129,7 +129,7 @@ ${e.extractions.map(i=>`- ${i.name} (${i.type}): ${i.description||"No descriptio
|
|
|
129
129
|
`,n=await this.instruct({...e,instruction:r});if(n=n.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),e.allowMultiple){let i=n.split(`
|
|
130
130
|
`).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of i)try{o.push(JSON.parse(s))}catch(a){console.error("Failed to parse line as JSON:",s,a.message)}return o}else return[JSON.parse(n.trim())]}async generateMarkdown(e){return this.instruct({...e,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(e){let r=this.ai.clone();return r.resetConversation(),r.getContextPrefix=async()=>e.instruction,e.callback&&r.addEventListener("output",n=>{e.callback(n.detail.message)}),e.allowKB||(r.knowledgeBase._sources=[]),await r.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(n=>n.text())}};var zu=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>e?.text||"")?.filter(e=>!!e)?.join(`
|
|
131
131
|
|
|
132
|
-
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,r)=>e+(r.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(r=>r.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(r=>r.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(r=>!!r)[0]||null}};var a_=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(r=>r.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,r=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(n,i)=>await this.runQuery(e,n.query)}])}remove(e){this.subagents=this.subagents.filter(r=>r.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,r){let n=e.apiKey||this.ai.apiKey,i=this.cachedSubagents[n];return i||(i=new Cu,await i.load(n,e.config),this.cachedSubagents[n]=i),i=i.clone(),i.knowledgeBase.allowGlobalConfigSources=!1,i.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&i.knowledgeBase.reset(),i.knowledgeBase.allowRagSearch=!e.disableRagSearch,e.knowledge&&i.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(i),(await i.sendMessage(r)).text()}};var Un=new Ne("Main"),jM=new Set,Qa=class Qa extends EventTarget{constructor(){super(...arguments);this.conversationID=sr();this.knowledgeBase=new o_(this);this.subAgents=new a_(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new s_(this);this.userID=P1();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:Qa.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(r,n){if(this.apiKey=r,!r)throw new Error("API key is required to load the AI.");n?.userID&&(this.userID=n.userID),n?.hubAPI&&(this.hubAPI=n.hubAPI);try{await Promise.all([(async()=>{Un.debug("Loading configuration...");let i=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r,userID:this.userID})});if(!i.ok)throw new Error(`Failed to load configuration: ${i.status} ${i.statusText}`);try{this.config=await i.json(),Un.debug("Config loaded successfully:",this.config),n&&(this.config={...this.config,...n}),this.config&&Un.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){Un.error("Failed to parse JSON response:",o);try{let s=await i.clone().text();Un.error("Raw response that failed parsing:",s)}catch{Un.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let i=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!i.ok)throw new Error(`Failed to load VAD model: ${i.status} ${i.statusText}`);this.vadModel=await i.blob()}catch(i){Un.warn(`Failed to load VAD model, some features will be unavailable. ${i.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let i of this.config.knowledge||[])i.url&&i.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:i.id,searchToolName:i.mcpSearchToolName,baseURL:i.url}):i.url&&this.knowledgeBase.registerSourceFromURL(i.url);for(let i of this.config.knowledge||[])i.entries?.length&&this.knowledgeBase.registerSource(i.id,()=>i.entries||[]);if(this.config.mcpServers)for(let i of this.config.mcpServers)this.knowledgeBase.registerMCPSource(i);for(let i of this.config.subagents||[])this.subAgents.register(i);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(i){throw Un.warn("Failed to load:",i),this.error=i,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:i}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:i}})),i}}setModel(r){let n=this.models.find(o=>o.id==r);if(!n)throw new Error(`Model with ID "${r}" not found.`);let i={...n.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(i):n.config.providerID==="anthropic"?this.currentModel=new Mh(i):this.currentModel=new sh(i),this.currentModel.id=n.id,this.currentModel.metadata=n}async getContextPrefix(){let r=ht().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof r=="function"&&(r=await r()),r}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let r=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let n=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:n}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:ih(`
|
|
132
|
+
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,r)=>e+(r.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(r=>r.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(r=>r.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(r=>!!r)[0]||null}};var a_=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(r=>r.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,r=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(n,i)=>await this.runQuery(e,n.query)}])}remove(e){this.subagents=this.subagents.filter(r=>r.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,r){let n=e.apiKey||this.ai.apiKey,i=this.cachedSubagents[n];return i||(i=new Cu,i.userID=this.ai.userID,await i.load(n,e.config),this.cachedSubagents[n]=i),i=i.clone(),i.knowledgeBase.allowGlobalConfigSources=!1,i.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&i.knowledgeBase.reset(),i.knowledgeBase.allowRagSearch=!e.disableRagSearch,e.knowledge&&i.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(i),(await i.sendMessage(r)).text()}};var Un=new Ne("Main"),jM=new Set,Qa=class Qa extends EventTarget{constructor(){super(...arguments);this.conversationID=sr();this.knowledgeBase=new o_(this);this.subAgents=new a_(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new s_(this);this.userID=P1();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:Qa.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(r,n){if(this.apiKey=r,!r)throw new Error("API key is required to load the AI.");n?.userID&&(this.userID=n.userID),n?.hubAPI&&(this.hubAPI=n.hubAPI);try{await Promise.all([(async()=>{Un.debug("Loading configuration...");let i=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r,userID:this.userID})});if(!i.ok)throw new Error(`Failed to load configuration: ${i.status} ${i.statusText}`);try{this.config=await i.json(),Un.debug("Config loaded successfully:",this.config),n&&(this.config={...this.config,...n}),this.config&&Un.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){Un.error("Failed to parse JSON response:",o);try{let s=await i.clone().text();Un.error("Raw response that failed parsing:",s)}catch{Un.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let i=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!i.ok)throw new Error(`Failed to load VAD model: ${i.status} ${i.statusText}`);this.vadModel=await i.blob()}catch(i){Un.warn(`Failed to load VAD model, some features will be unavailable. ${i.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let i of this.config.knowledge||[])i.url&&i.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:i.id,searchToolName:i.mcpSearchToolName,baseURL:i.url}):i.url&&this.knowledgeBase.registerSourceFromURL(i.url);for(let i of this.config.knowledge||[])i.entries?.length&&this.knowledgeBase.registerSource(i.id,()=>i.entries||[]);if(this.config.mcpServers)for(let i of this.config.mcpServers)this.knowledgeBase.registerMCPSource(i);for(let i of this.config.subagents||[])this.subAgents.register(i);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(i){throw Un.warn("Failed to load:",i),this.error=i,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:i}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:i}})),i}}setModel(r){let n=this.models.find(o=>o.id==r);if(!n)throw new Error(`Model with ID "${r}" not found.`);let i={...n.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(i):n.config.providerID==="anthropic"?this.currentModel=new Mh(i):this.currentModel=new sh(i),this.currentModel.id=n.id,this.currentModel.metadata=n}async getContextPrefix(){let r=ht().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof r=="function"&&(r=await r()),r}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let r=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let n=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:n}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:ih(`
|
|
133
133
|
# RAG search
|
|
134
134
|
Use the \`search\` tool proactively as much as possible to find missing information or tools.
|
|
135
135
|
Use the \`search\` tool when you are unsure about specific details or actions to take.
|
|
Binary file
|
package/dist/node/node.d.ts
CHANGED
|
@@ -1341,7 +1341,7 @@ interface SubAgentConfig {
|
|
|
1341
1341
|
/** Extra knowledge base sources for the sub-agent */
|
|
1342
1342
|
knowledge?: KnowledgeFetcher;
|
|
1343
1343
|
/** Optional extra configuration for the subagent instance */
|
|
1344
|
-
config?: Partial<
|
|
1344
|
+
config?: Partial<IntelliWeaveConfig>;
|
|
1345
1345
|
/** Called when the subagent is loaded */
|
|
1346
1346
|
onAgentLoaded?: (agent: IntelliWeave) => Promise<void> | void;
|
|
1347
1347
|
}
|
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"||!d?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!d?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let s=new URL(e.path,window.location.origin).pathname;return window.location.href=s,`Changed route to: ${s}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!d?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let s=encodeURIComponent(e.email_address),n=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),r=`mailto:${s}?subject=${n}&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 ce}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as de}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var v={name:"@intelliweave/embedded",version:"2.1.74",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-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 pe,ToolListChangedNotificationSchema as he}from"@modelcontextprotocol/sdk/types.js";var m=new g("MCPKnowledgeClient"),ge="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),s={};this.config.headers&&(s={...s,...this.config.headers}),this.config.proxy?.enabled&&(s["Mcp-Target-Url"]=t.toString(),s["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",t=new URL(this.config.proxy.url||ge));let n=new ce({name:v.name,version:v.version}),o=new de(t,{requestInit:{headers:s}});return await n.connect(o),m.debug("Connected with HTTP streaming mode"),n});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(pe,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(he,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 n=await this.client.listTools({cursor:t});t=n.nextCursor;for(let o of n.tools||[])e.push(o);if(!n?.tools?.length||!t)break}let s=[];for(let n of e){let o=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:r=>this.performToolCall(n.name,r),disabled:o})}m.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=s}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),s=await this.performSearchCall(e);return t=t.concat(s),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 s=this.tools.find(o=>o.name==this.config.searchToolName);if(!s)return m.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let n;if(s.inputSchema.required?.length==1){let o=s.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let o=Object.keys(s.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[o]:e})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let o=0;o<n.length;o++){let r=n[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 n=="string"?n:JSON.stringify(n)});return t}async performToolCall(e,t){await this.connect(),m.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let s=await this.client.callTool({name:e,arguments:t});if(s.isError){let n=s.content?.[0]?.text||"Unknown error";throw m.error(`Error calling tool ${e}: ${n}`),new Error(`Error calling tool ${e}: ${n}`)}if(Array.isArray(s.content)&&s.content.length==1&&s.content[0].type=="text")try{return JSON.parse(s.content[0].text)}catch{}return s.content||[]}};import{v4 as me}from"uuid";var fe=new g("Statistics"),_=[];async function I(d,e){let t={...e,event_id:me(),event_date:new Date().toISOString(),sdk_version:v.version,conversation_id:d?.conversationID||"",api_key:d?.apiKey||"",user_id:d?.userID||""};if(_.push(t),!d||(await new Promise(n=>setTimeout(n,5e3)),_.length===0))return;let s=_.slice();_.length=0;try{let n=await fetch(d.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){fe.warn("Failed to submit analytics event:",n),_.push(...s);return}}var k=new g("KnowledgeBase"),L=1,D=class d{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 s=e;return typeof e=="function"&&(t=e,s=`source.${L++}`),this._sources.push({id:s,query:t}),s}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(),s=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});s.query=e,s.entries=[],s.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(s),this._windowSources=s.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async u=>{try{let i=Date.now(),l=await u.query(e);return k.debug(`Source '${u.id}' took ${Date.now()-i}ms`),l||[]}catch(i){return k.warn(`Knowledge source '${u.id}' failed:`,i),[]}}))).flat();o=o.concat(s.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&y().knowledgeBase&&(o=o.concat(y().knowledgeBase)),o=o.filter(u=>u&&!u.disabled);for(let u=0;u<o.length;u++){let i=o[u];i.id=i.id||`temp.${u}`,i._functionID=i.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let r=new we({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});r.addAll(o);let a=r.search(e).map(u=>o.find(i=>i.id==u.id));for(let u of o)u.isContext&&(a.find(i=>i.id===u.id)||a.push(u));return this.lastResults=a,I(this.ai,{event_type:"kb_search",value:a.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),k.debug("Found results:",a),a}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 s=[],n=[],o=!0,r=async(a,u)=>{k.debug(`Calling remote knowledge base action: ${a.id}`);let i={type:"action",userID:this.ai.userID,actionID:a.id,parameters:u},l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let p=await l.json();return c(p.updateItems||[]),p.response},c=a=>{for(let u of a){if(!u.id){k.warn("KB item skipped since it has no ID.",u);continue}let i=s.find(l=>l.id==u.id);if(i){i.name=u.name||i.name||"",i.content=u.content||i.content||"",i.disabled=u.disabled??i.disabled,i.isContext=u.isContext??i.isContext,i.parameters=u.parameters||i.parameters||[],i.tags=u.tags||i.tags,i.type=u.type||i.type;continue}s.push({...u,action:l=>r(u,l)})}};this.registerSource(t,async a=>{if(o&&n.includes(a))return s;let u={type:"search",userID:this.ai?.userID||"",query:a},i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let l=await i.json();return o=!l.noCache,n.includes(a)||n.push(a),c(l.items),s})}clone(e){let t=new d(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,s=>t.search(s)),t}};var R=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>e?.text||"")?.filter(e=>!!e)?.join(`
|
|
21
|
+
${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"||!d?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!d?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let s=new URL(e.path,window.location.origin).pathname;return window.location.href=s,`Changed route to: ${s}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!d?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let s=encodeURIComponent(e.email_address),n=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),r=`mailto:${s}?subject=${n}&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 ce}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as de}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var v={name:"@intelliweave/embedded",version:"2.1.75",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-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 pe,ToolListChangedNotificationSchema as he}from"@modelcontextprotocol/sdk/types.js";var m=new g("MCPKnowledgeClient"),ge="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),s={};this.config.headers&&(s={...s,...this.config.headers}),this.config.proxy?.enabled&&(s["Mcp-Target-Url"]=t.toString(),s["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",t=new URL(this.config.proxy.url||ge));let n=new ce({name:v.name,version:v.version}),o=new de(t,{requestInit:{headers:s}});return await n.connect(o),m.debug("Connected with HTTP streaming mode"),n});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(pe,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(he,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 n=await this.client.listTools({cursor:t});t=n.nextCursor;for(let o of n.tools||[])e.push(o);if(!n?.tools?.length||!t)break}let s=[];for(let n of e){let o=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:r=>this.performToolCall(n.name,r),disabled:o})}m.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=s}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),s=await this.performSearchCall(e);return t=t.concat(s),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 s=this.tools.find(o=>o.name==this.config.searchToolName);if(!s)return m.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let n;if(s.inputSchema.required?.length==1){let o=s.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let o=Object.keys(s.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[o]:e})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let o=0;o<n.length;o++){let r=n[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 n=="string"?n:JSON.stringify(n)});return t}async performToolCall(e,t){await this.connect(),m.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let s=await this.client.callTool({name:e,arguments:t});if(s.isError){let n=s.content?.[0]?.text||"Unknown error";throw m.error(`Error calling tool ${e}: ${n}`),new Error(`Error calling tool ${e}: ${n}`)}if(Array.isArray(s.content)&&s.content.length==1&&s.content[0].type=="text")try{return JSON.parse(s.content[0].text)}catch{}return s.content||[]}};import{v4 as me}from"uuid";var fe=new g("Statistics"),_=[];async function I(d,e){let t={...e,event_id:me(),event_date:new Date().toISOString(),sdk_version:v.version,conversation_id:d?.conversationID||"",api_key:d?.apiKey||"",user_id:d?.userID||""};if(_.push(t),!d||(await new Promise(n=>setTimeout(n,5e3)),_.length===0))return;let s=_.slice();_.length=0;try{let n=await fetch(d.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){fe.warn("Failed to submit analytics event:",n),_.push(...s);return}}var k=new g("KnowledgeBase"),L=1,D=class d{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 s=e;return typeof e=="function"&&(t=e,s=`source.${L++}`),this._sources.push({id:s,query:t}),s}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(),s=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});s.query=e,s.entries=[],s.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(s),this._windowSources=s.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async u=>{try{let i=Date.now(),l=await u.query(e);return k.debug(`Source '${u.id}' took ${Date.now()-i}ms`),l||[]}catch(i){return k.warn(`Knowledge source '${u.id}' failed:`,i),[]}}))).flat();o=o.concat(s.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&y().knowledgeBase&&(o=o.concat(y().knowledgeBase)),o=o.filter(u=>u&&!u.disabled);for(let u=0;u<o.length;u++){let i=o[u];i.id=i.id||`temp.${u}`,i._functionID=i.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let r=new we({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});r.addAll(o);let a=r.search(e).map(u=>o.find(i=>i.id==u.id));for(let u of o)u.isContext&&(a.find(i=>i.id===u.id)||a.push(u));return this.lastResults=a,I(this.ai,{event_type:"kb_search",value:a.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),k.debug("Found results:",a),a}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 s=[],n=[],o=!0,r=async(a,u)=>{k.debug(`Calling remote knowledge base action: ${a.id}`);let i={type:"action",userID:this.ai.userID,actionID:a.id,parameters:u},l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let p=await l.json();return c(p.updateItems||[]),p.response},c=a=>{for(let u of a){if(!u.id){k.warn("KB item skipped since it has no ID.",u);continue}let i=s.find(l=>l.id==u.id);if(i){i.name=u.name||i.name||"",i.content=u.content||i.content||"",i.disabled=u.disabled??i.disabled,i.isContext=u.isContext??i.isContext,i.parameters=u.parameters||i.parameters||[],i.tags=u.tags||i.tags,i.type=u.type||i.type;continue}s.push({...u,action:l=>r(u,l)})}};this.registerSource(t,async a=>{if(o&&n.includes(a))return s;let u={type:"search",userID:this.ai?.userID||"",query:a},i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let l=await i.json();return o=!l.noCache,n.includes(a)||n.push(a),c(l.items),s})}clone(e){let t=new d(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,s=>t.search(s)),t}};var R=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>e?.text||"")?.filter(e=>!!e)?.join(`
|
|
22
22
|
|
|
23
23
|
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,t)=>e+(t.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(t=>t.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(t=>t.sections?.find(s=>s.type=="tool_result"&&s.toolCallInstanceID==e)).filter(t=>!!t)[0]||null}};import{v4 as Z}from"uuid";var K=class{constructor(e){this.ai=e}async boolean(e){let t=await this.instruct({...e,instruction:`${e.instruction}
|
|
24
24
|
|
|
@@ -37,7 +37,7 @@ Objects should have the following keys:
|
|
|
37
37
|
${e.extractions.map(n=>`- ${n.name} (${n.type}): ${n.description||"No description provided."}`).join(`
|
|
38
38
|
`)}
|
|
39
39
|
`,s=await this.instruct({...e,instruction:t});if(s=s.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),e.allowMultiple){let n=s.split(`
|
|
40
|
-
`).map(r=>r.trim()).filter(r=>!!r.trim()),o=[];for(let r of n)try{o.push(JSON.parse(r))}catch(c){console.error("Failed to parse line as JSON:",r,c.message)}return o}else return[JSON.parse(s.trim())]}async generateMarkdown(e){return this.instruct({...e,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(e){let t=this.ai.clone();return t.resetConversation(),t.getContextPrefix=async()=>e.instruction,e.callback&&t.addEventListener("output",s=>{e.callback(s.detail.message)}),e.allowKB||(t.knowledgeBase._sources=[]),await t.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(s=>s.text())}};var O=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(t=>t.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,t=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(s,n)=>await this.runQuery(e,s.query)}])}remove(e){this.subagents=this.subagents.filter(t=>t.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,t){let s=e.apiKey||this.ai.apiKey,n=this.cachedSubagents[s];return n||(n=new G,await n.load(s,e.config),this.cachedSubagents[s]=n),n=n.clone(),n.knowledgeBase.allowGlobalConfigSources=!1,n.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&n.knowledgeBase.reset(),n.knowledgeBase.allowRagSearch=!e.disableRagSearch,e.knowledge&&n.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(n),(await n.sendMessage(t)).text()}};var w=new g("Main"),ee=new Set,T=class T extends EventTarget{constructor(){super(...arguments);this.conversationID=Z();this.knowledgeBase=new D(this);this.subAgents=new O(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new K(this);this.userID=F();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:T.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(t,s){if(this.apiKey=t,!t)throw new Error("API key is required to load the AI.");s?.userID&&(this.userID=s.userID),s?.hubAPI&&(this.hubAPI=s.hubAPI);try{await Promise.all([(async()=>{w.debug("Loading configuration...");let n=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t,userID:this.userID})});if(!n.ok)throw new Error(`Failed to load configuration: ${n.status} ${n.statusText}`);try{this.config=await n.json(),w.debug("Config loaded successfully:",this.config),s&&(this.config={...this.config,...s}),this.config&&w.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){w.error("Failed to parse JSON response:",o);try{let r=await n.clone().text();w.error("Raw response that failed parsing:",r)}catch{w.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let n=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!n.ok)throw new Error(`Failed to load VAD model: ${n.status} ${n.statusText}`);this.vadModel=await n.blob()}catch(n){w.warn(`Failed to load VAD model, some features will be unavailable. ${n.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let n of this.config.knowledge||[])n.url&&n.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:n.id,searchToolName:n.mcpSearchToolName,baseURL:n.url}):n.url&&this.knowledgeBase.registerSourceFromURL(n.url);for(let n of this.config.knowledge||[])n.entries?.length&&this.knowledgeBase.registerSource(n.id,()=>n.entries||[]);if(this.config.mcpServers)for(let n of this.config.mcpServers)this.knowledgeBase.registerMCPSource(n);for(let n of this.config.subagents||[])this.subAgents.register(n);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(n){throw w.warn("Failed to load:",n),this.error=n,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:n}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:n}})),n}}setModel(t){let s=this.models.find(o=>o.id==t);if(!s)throw new Error(`Model with ID "${t}" not found.`);let n={...s.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,r)=>{let c=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(c?.id||o,r)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(n):s.config.providerID==="anthropic"?this.currentModel=new P(n):this.currentModel=new M(n),this.currentModel.id=s.id,this.currentModel.metadata=s}async getContextPrefix(){let t=y().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof t=="function"&&(t=await t()),t}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let t=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let s=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:s}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:A(`
|
|
40
|
+
`).map(r=>r.trim()).filter(r=>!!r.trim()),o=[];for(let r of n)try{o.push(JSON.parse(r))}catch(c){console.error("Failed to parse line as JSON:",r,c.message)}return o}else return[JSON.parse(s.trim())]}async generateMarkdown(e){return this.instruct({...e,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(e){let t=this.ai.clone();return t.resetConversation(),t.getContextPrefix=async()=>e.instruction,e.callback&&t.addEventListener("output",s=>{e.callback(s.detail.message)}),e.allowKB||(t.knowledgeBase._sources=[]),await t.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(s=>s.text())}};var O=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(t=>t.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,t=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(s,n)=>await this.runQuery(e,s.query)}])}remove(e){this.subagents=this.subagents.filter(t=>t.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,t){let s=e.apiKey||this.ai.apiKey,n=this.cachedSubagents[s];return n||(n=new G,n.userID=this.ai.userID,await n.load(s,e.config),this.cachedSubagents[s]=n),n=n.clone(),n.knowledgeBase.allowGlobalConfigSources=!1,n.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&n.knowledgeBase.reset(),n.knowledgeBase.allowRagSearch=!e.disableRagSearch,e.knowledge&&n.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(n),(await n.sendMessage(t)).text()}};var w=new g("Main"),ee=new Set,T=class T extends EventTarget{constructor(){super(...arguments);this.conversationID=Z();this.knowledgeBase=new D(this);this.subAgents=new O(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new K(this);this.userID=F();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:T.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(t,s){if(this.apiKey=t,!t)throw new Error("API key is required to load the AI.");s?.userID&&(this.userID=s.userID),s?.hubAPI&&(this.hubAPI=s.hubAPI);try{await Promise.all([(async()=>{w.debug("Loading configuration...");let n=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t,userID:this.userID})});if(!n.ok)throw new Error(`Failed to load configuration: ${n.status} ${n.statusText}`);try{this.config=await n.json(),w.debug("Config loaded successfully:",this.config),s&&(this.config={...this.config,...s}),this.config&&w.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){w.error("Failed to parse JSON response:",o);try{let r=await n.clone().text();w.error("Raw response that failed parsing:",r)}catch{w.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let n=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!n.ok)throw new Error(`Failed to load VAD model: ${n.status} ${n.statusText}`);this.vadModel=await n.blob()}catch(n){w.warn(`Failed to load VAD model, some features will be unavailable. ${n.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let n of this.config.knowledge||[])n.url&&n.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:n.id,searchToolName:n.mcpSearchToolName,baseURL:n.url}):n.url&&this.knowledgeBase.registerSourceFromURL(n.url);for(let n of this.config.knowledge||[])n.entries?.length&&this.knowledgeBase.registerSource(n.id,()=>n.entries||[]);if(this.config.mcpServers)for(let n of this.config.mcpServers)this.knowledgeBase.registerMCPSource(n);for(let n of this.config.subagents||[])this.subAgents.register(n);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(n){throw w.warn("Failed to load:",n),this.error=n,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:n}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:n}})),n}}setModel(t){let s=this.models.find(o=>o.id==t);if(!s)throw new Error(`Model with ID "${t}" not found.`);let n={...s.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,r)=>{let c=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(c?.id||o,r)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(n):s.config.providerID==="anthropic"?this.currentModel=new P(n):this.currentModel=new M(n),this.currentModel.id=s.id,this.currentModel.metadata=s}async getContextPrefix(){let t=y().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof t=="function"&&(t=await t()),t}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let t=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let s=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:s}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:A(`
|
|
41
41
|
# RAG search
|
|
42
42
|
Use the \`search\` tool proactively as much as possible to find missing information or tools.
|
|
43
43
|
Use the \`search\` tool when you are unsure about specific details or actions to take.
|
package/dist/react/react.d.ts
CHANGED
|
@@ -955,7 +955,7 @@ interface SubAgentConfig {
|
|
|
955
955
|
/** Extra knowledge base sources for the sub-agent */
|
|
956
956
|
knowledge?: KnowledgeFetcher;
|
|
957
957
|
/** Optional extra configuration for the subagent instance */
|
|
958
|
-
config?: Partial<
|
|
958
|
+
config?: Partial<IntelliWeaveConfig>;
|
|
959
959
|
/** Called when the subagent is loaded */
|
|
960
960
|
onAgentLoaded?: (agent: IntelliWeave) => Promise<void> | void;
|
|
961
961
|
}
|
package/dist/react/react.js
CHANGED
|
@@ -12,7 +12,7 @@ New information found:
|
|
|
12
12
|
${o}
|
|
13
13
|
|
|
14
14
|
New tools available:
|
|
15
|
-
${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),n=encodeURIComponent(i.subject),o=encodeURIComponent(i.body),s=`mailto:${t}?subject=${n}&body=${o}`;try{window.location.href=s}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as ft}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as yt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var E={name:"@intelliweave/embedded",version:"2.1.74",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-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 bt,ToolListChangedNotificationSchema as wt}from"@modelcontextprotocol/sdk/types.js";var y=new p("MCPKnowledgeClient"),vt="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",oe=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){y.debug("Connecting to MCP client");let i=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||vt));let n=new ft({name:E.name,version:E.version}),o=new yt(e,{requestInit:{headers:t}});return await n.connect(o),y.debug("Connected with HTTP streaming mode"),n});return await this.disconnect(),this.client=i,i.onerror=e=>{y.error(`MCP client error: ${e.message}`)},i.onclose=()=>{y.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(bt,e=>{e.params.level=="critical"?y.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?y.error(`[Server] ${e.params.data}`):e.params.level=="error"?y.error(`[Server] ${e.params.data}`):e.params.level=="warning"?y.warn(`[Server] ${e.params.data}`):e.params.level=="info"?y.info(`[Server] ${e.params.data}`):e.params.level=="debug"?y.debug(`[Server] ${e.params.data}`):y.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(wt,e=>{y.debug("Tool list changed",e),this.fetchTools()}),y.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let o of n.tools||[])i.push(o);if(!n?.tools?.length||!e)break}let t=[];for(let n of i){let o=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:s=>this.performToolCall(n.name,s),disabled:o})}y.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,y.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(o=>o.name==this.config.searchToolName);if(!t)return y.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(t.inputSchema.required?.length==1){let o=t.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let o=Object.keys(t.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let o=0;o<n.length;o++){let s=n[o];e.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 e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(i,e){await this.connect(),y.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let n=t.content?.[0]?.text||"Unknown error";throw y.error(`Error calling tool ${i}: ${n}`),new Error(`Error calling tool ${i}: ${n}`)}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 xt}from"uuid";var Mt=new p("Statistics"),K=[];async function w(r,i){let e={...i,event_id:xt(),event_date:new Date().toISOString(),sdk_version:E.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(K.push(e),!r||(await new Promise(n=>setTimeout(n,5e3)),K.length===0))return;let t=K.slice();K.length=0;try{let n=await fetch(r.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){Mt.warn("Failed to submit analytics event:",n),K.push(...t);return}}var Z=new p("KnowledgeBase"),Le=1,se=class r{constructor(i){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=i,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(i=>i.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>ze(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${Le++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return this.allowGlobalConfigSources&&h().knowledgeBaseSources&&(i=i.concat(h().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(i=i.concat(this._windowSources)),i=i.filter(e=>!e.disabled),i}async search(i){Z.debug(`Searching knowledge base for: ${i}`);let e=Date.now(),t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,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 u=>{try{let c=Date.now(),d=await u.query(i);return Z.debug(`Source '${u.id}' took ${Date.now()-c}ms`),d||[]}catch(c){return Z.warn(`Knowledge source '${u.id}' failed:`,c),[]}}))).flat();o=o.concat(t.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&h().knowledgeBase&&(o=o.concat(h().knowledgeBase)),o=o.filter(u=>u&&!u.disabled);for(let u=0;u<o.length;u++){let c=o[u];c.id=c.id||`temp.${u}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new It({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(i).map(u=>o.find(c=>c.id==u.id));for(let u of o)u.isContext&&(l.find(c=>c.id===u.id)||l.push(u));return this.lastResults=l,w(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),Z.debug("Found results:",l),l}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${Le++}`),Z.debug(`Registering remote knowledge base source: ${i}`);let t=[],n=[],o=!0,s=async(l,u)=>{Z.debug(`Calling remote knowledge base action: ${l.id}`);let c={type:"action",userID:this.ai.userID,actionID:l.id,parameters:u},d=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let g=await d.json();return a(g.updateItems||[]),g.response},a=l=>{for(let u of l){if(!u.id){Z.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=>s(u,d)})}};this.registerSource(e,async l=>{if(o&&n.includes(l))return t;let u={type:"search",userID:this.ai?.userID||"",query:l},c=await fetch(i,{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,n.includes(l)||n.push(l),a(d.items),t})}clone(i){let e=new r(i);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(i){i.id||(i.id=`external.${Le++}`);let e=new oe(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ae=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
15
|
+
${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!r?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),n=encodeURIComponent(i.subject),o=encodeURIComponent(i.body),s=`mailto:${t}?subject=${n}&body=${o}`;try{window.location.href=s}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as ft}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as yt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var E={name:"@intelliweave/embedded",version:"2.1.75",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-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 bt,ToolListChangedNotificationSchema as wt}from"@modelcontextprotocol/sdk/types.js";var y=new p("MCPKnowledgeClient"),vt="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",oe=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){y.debug("Connecting to MCP client");let i=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||vt));let n=new ft({name:E.name,version:E.version}),o=new yt(e,{requestInit:{headers:t}});return await n.connect(o),y.debug("Connected with HTTP streaming mode"),n});return await this.disconnect(),this.client=i,i.onerror=e=>{y.error(`MCP client error: ${e.message}`)},i.onclose=()=>{y.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(bt,e=>{e.params.level=="critical"?y.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?y.error(`[Server] ${e.params.data}`):e.params.level=="error"?y.error(`[Server] ${e.params.data}`):e.params.level=="warning"?y.warn(`[Server] ${e.params.data}`):e.params.level=="info"?y.info(`[Server] ${e.params.data}`):e.params.level=="debug"?y.debug(`[Server] ${e.params.data}`):y.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(wt,e=>{y.debug("Tool list changed",e),this.fetchTools()}),y.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let o of n.tools||[])i.push(o);if(!n?.tools?.length||!e)break}let t=[];for(let n of i){let o=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:s=>this.performToolCall(n.name,s),disabled:o})}y.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,y.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(o=>o.name==this.config.searchToolName);if(!t)return y.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(t.inputSchema.required?.length==1){let o=t.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let o=Object.keys(t.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let o=0;o<n.length;o++){let s=n[o];e.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 e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(i,e){await this.connect(),y.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let n=t.content?.[0]?.text||"Unknown error";throw y.error(`Error calling tool ${i}: ${n}`),new Error(`Error calling tool ${i}: ${n}`)}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 xt}from"uuid";var Mt=new p("Statistics"),K=[];async function w(r,i){let e={...i,event_id:xt(),event_date:new Date().toISOString(),sdk_version:E.version,conversation_id:r?.conversationID||"",api_key:r?.apiKey||"",user_id:r?.userID||""};if(K.push(e),!r||(await new Promise(n=>setTimeout(n,5e3)),K.length===0))return;let t=K.slice();K.length=0;try{let n=await fetch(r.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){Mt.warn("Failed to submit analytics event:",n),K.push(...t);return}}var Z=new p("KnowledgeBase"),Le=1,se=class r{constructor(i){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=i,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(i=>i.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>ze(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${Le++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return this.allowGlobalConfigSources&&h().knowledgeBaseSources&&(i=i.concat(h().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(i=i.concat(this._windowSources)),i=i.filter(e=>!e.disabled),i}async search(i){Z.debug(`Searching knowledge base for: ${i}`);let e=Date.now(),t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,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 u=>{try{let c=Date.now(),d=await u.query(i);return Z.debug(`Source '${u.id}' took ${Date.now()-c}ms`),d||[]}catch(c){return Z.warn(`Knowledge source '${u.id}' failed:`,c),[]}}))).flat();o=o.concat(t.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&h().knowledgeBase&&(o=o.concat(h().knowledgeBase)),o=o.filter(u=>u&&!u.disabled);for(let u=0;u<o.length;u++){let c=o[u];c.id=c.id||`temp.${u}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new It({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(i).map(u=>o.find(c=>c.id==u.id));for(let u of o)u.isContext&&(l.find(c=>c.id===u.id)||l.push(u));return this.lastResults=l,w(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),Z.debug("Found results:",l),l}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${Le++}`),Z.debug(`Registering remote knowledge base source: ${i}`);let t=[],n=[],o=!0,s=async(l,u)=>{Z.debug(`Calling remote knowledge base action: ${l.id}`);let c={type:"action",userID:this.ai.userID,actionID:l.id,parameters:u},d=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let g=await d.json();return a(g.updateItems||[]),g.response},a=l=>{for(let u of l){if(!u.id){Z.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=>s(u,d)})}};this.registerSource(e,async l=>{if(o&&n.includes(l))return t;let u={type:"search",userID:this.ai?.userID||"",query:l},c=await fetch(i,{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,n.includes(l)||n.push(l),a(d.items),t})}clone(i){let e=new r(i);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(i){i.id||(i.id=`external.${Le++}`);let e=new oe(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ae=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
16
16
|
|
|
17
17
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(e.toLowerCase().includes("true"))return!0;if(e.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+e)}async choose(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
18
18
|
|
|
@@ -31,7 +31,7 @@ ${i.extractions.map(n=>`- ${n.name} (${n.type}): ${n.description||"No descriptio
|
|
|
31
31
|
`,t=await this.instruct({...i,instruction:e});if(t=t.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),i.allowMultiple){let n=t.split(`
|
|
32
32
|
`).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of n)try{o.push(JSON.parse(s))}catch(a){console.error("Failed to parse line as JSON:",s,a.message)}return o}else return[JSON.parse(t.trim())]}async generateMarkdown(i){return this.instruct({...i,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(i){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>i.instruction,i.callback&&e.addEventListener("output",t=>{i.callback(t.detail.message)}),i.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof i.data=="string"?i.data:JSON.stringify(i.data)).then(t=>t.text())}};var P=class{constructor(i){this.messages=i}text(){return this.messages?.flatMap(i=>i.sections)?.filter(i=>i?.type=="text")?.map(i=>i?.text||"")?.filter(i=>!!i)?.join(`
|
|
33
33
|
|
|
34
|
-
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((i,e)=>i+(e.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(i=>i.sections||[])||[]}toolCalls(){return this.messages?.flatMap(i=>i.sections?.filter(e=>e.type=="tool_call")||[])||[]}toolResult(i){return this.messages?.map(e=>e.sections?.find(t=>t.type=="tool_result"&&t.toolCallInstanceID==i)).filter(e=>!!e)[0]||null}};var re=class{constructor(i){this.subagents=[];this.cachedSubagents={};this.ai=i}register(i){if(this.subagents.find(e=>e.id==i.id))throw new Error(`Sub-agent with ID ${i.id} already exists`);this.subagents.push(i),this.ai.knowledgeBase.registerSource("subagent:"+i.id,e=>[{type:"action",id:"ask:"+i.id,name:`Ask ${i.name||"subagent"}`,content:i.usageInstructions||`Use this tool to ask ${i.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(t,n)=>await this.runQuery(i,t.query)}])}remove(i){this.subagents=this.subagents.filter(e=>e.id!=i),this.ai.knowledgeBase.removeSource("subagent:"+i)}async runQuery(i,e){let t=i.apiKey||this.ai.apiKey,n=this.cachedSubagents[t];return n||(n=new N,await n.load(t,i.config),this.cachedSubagents[t]=n),n=n.clone(),n.knowledgeBase.allowGlobalConfigSources=!1,n.knowledgeBase.allowWindowSources=!1,i.clearExistingKnowledge&&n.knowledgeBase.reset(),n.knowledgeBase.allowRagSearch=!i.disableRagSearch,i.knowledge&&n.knowledgeBase.registerSource(i.knowledge),i.onAgentLoaded&&await i.onAgentLoaded(n),(await n.sendMessage(e)).text()}};var M=new p("Main"),je=new Set,D=class D extends EventTarget{constructor(){super(...arguments);this.conversationID=_e();this.knowledgeBase=new se(this);this.subAgents=new re(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new ae(this);this.userID=Re();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:D.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(e,t){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");t?.userID&&(this.userID=t.userID),t?.hubAPI&&(this.hubAPI=t.hubAPI);try{await Promise.all([(async()=>{M.debug("Loading configuration...");let n=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,userID:this.userID})});if(!n.ok)throw new Error(`Failed to load configuration: ${n.status} ${n.statusText}`);try{this.config=await n.json(),M.debug("Config loaded successfully:",this.config),t&&(this.config={...this.config,...t}),this.config&&M.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){M.error("Failed to parse JSON response:",o);try{let s=await n.clone().text();M.error("Raw response that failed parsing:",s)}catch{M.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let n=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!n.ok)throw new Error(`Failed to load VAD model: ${n.status} ${n.statusText}`);this.vadModel=await n.blob()}catch(n){M.warn(`Failed to load VAD model, some features will be unavailable. ${n.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let n of this.config.knowledge||[])n.url&&n.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:n.id,searchToolName:n.mcpSearchToolName,baseURL:n.url}):n.url&&this.knowledgeBase.registerSourceFromURL(n.url);for(let n of this.config.knowledge||[])n.entries?.length&&this.knowledgeBase.registerSource(n.id,()=>n.entries||[]);if(this.config.mcpServers)for(let n of this.config.mcpServers)this.knowledgeBase.registerMCPSource(n);for(let n of this.config.subagents||[])this.subAgents.register(n);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(n){throw M.warn("Failed to load:",n),this.error=n,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:n}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:n}})),n}}setModel(e){let t=this.models.find(o=>o.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let n={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(n):t.config.providerID==="anthropic"?this.currentModel=new ne(n):this.currentModel=new ie(n),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=h().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let t=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:t}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:ee(`
|
|
34
|
+
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((i,e)=>i+(e.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(i=>i.sections||[])||[]}toolCalls(){return this.messages?.flatMap(i=>i.sections?.filter(e=>e.type=="tool_call")||[])||[]}toolResult(i){return this.messages?.map(e=>e.sections?.find(t=>t.type=="tool_result"&&t.toolCallInstanceID==i)).filter(e=>!!e)[0]||null}};var re=class{constructor(i){this.subagents=[];this.cachedSubagents={};this.ai=i}register(i){if(this.subagents.find(e=>e.id==i.id))throw new Error(`Sub-agent with ID ${i.id} already exists`);this.subagents.push(i),this.ai.knowledgeBase.registerSource("subagent:"+i.id,e=>[{type:"action",id:"ask:"+i.id,name:`Ask ${i.name||"subagent"}`,content:i.usageInstructions||`Use this tool to ask ${i.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(t,n)=>await this.runQuery(i,t.query)}])}remove(i){this.subagents=this.subagents.filter(e=>e.id!=i),this.ai.knowledgeBase.removeSource("subagent:"+i)}async runQuery(i,e){let t=i.apiKey||this.ai.apiKey,n=this.cachedSubagents[t];return n||(n=new N,n.userID=this.ai.userID,await n.load(t,i.config),this.cachedSubagents[t]=n),n=n.clone(),n.knowledgeBase.allowGlobalConfigSources=!1,n.knowledgeBase.allowWindowSources=!1,i.clearExistingKnowledge&&n.knowledgeBase.reset(),n.knowledgeBase.allowRagSearch=!i.disableRagSearch,i.knowledge&&n.knowledgeBase.registerSource(i.knowledge),i.onAgentLoaded&&await i.onAgentLoaded(n),(await n.sendMessage(e)).text()}};var M=new p("Main"),je=new Set,D=class D extends EventTarget{constructor(){super(...arguments);this.conversationID=_e();this.knowledgeBase=new se(this);this.subAgents=new re(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new ae(this);this.userID=Re();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:D.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(e,t){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");t?.userID&&(this.userID=t.userID),t?.hubAPI&&(this.hubAPI=t.hubAPI);try{await Promise.all([(async()=>{M.debug("Loading configuration...");let n=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,userID:this.userID})});if(!n.ok)throw new Error(`Failed to load configuration: ${n.status} ${n.statusText}`);try{this.config=await n.json(),M.debug("Config loaded successfully:",this.config),t&&(this.config={...this.config,...t}),this.config&&M.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){M.error("Failed to parse JSON response:",o);try{let s=await n.clone().text();M.error("Raw response that failed parsing:",s)}catch{M.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let n=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!n.ok)throw new Error(`Failed to load VAD model: ${n.status} ${n.statusText}`);this.vadModel=await n.blob()}catch(n){M.warn(`Failed to load VAD model, some features will be unavailable. ${n.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let n of this.config.knowledge||[])n.url&&n.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:n.id,searchToolName:n.mcpSearchToolName,baseURL:n.url}):n.url&&this.knowledgeBase.registerSourceFromURL(n.url);for(let n of this.config.knowledge||[])n.entries?.length&&this.knowledgeBase.registerSource(n.id,()=>n.entries||[]);if(this.config.mcpServers)for(let n of this.config.mcpServers)this.knowledgeBase.registerMCPSource(n);for(let n of this.config.subagents||[])this.subAgents.register(n);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(n){throw M.warn("Failed to load:",n),this.error=n,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:n}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:n}})),n}}setModel(e){let t=this.models.find(o=>o.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let n={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(n):t.config.providerID==="anthropic"?this.currentModel=new ne(n):this.currentModel=new ie(n),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=h().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let t=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:t}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:ee(`
|
|
35
35
|
# RAG search
|
|
36
36
|
Use the \`search\` tool proactively as much as possible to find missing information or tools.
|
|
37
37
|
Use the \`search\` tool when you are unsure about specific details or actions to take.
|