@intelliweave/embedded 1.9.69-beta.4 → 2.0.70
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 +34 -0
- package/dist/component/component.js +22 -14
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.d.ts +34 -0
- package/dist/node/node.js +4 -4
- package/dist/react/react.d.ts +42 -0
- package/dist/react/react.js +33 -25
- package/dist/script-tag/script-tag.js +120 -79
- package/dist/webpack/index.d.ts +42 -0
- package/dist/webpack/index.js +23 -15
- package/examples/react-test/index.html +14 -0
- package/examples/react-test/package-lock.json +1844 -0
- package/examples/react-test/package.json +25 -0
- package/examples/react-test/src/App.tsx +69 -0
- package/examples/react-test/src/main.tsx +10 -0
- package/examples/react-test/vite.config.ts +8 -0
- package/package.json +2 -2
|
@@ -40,9 +40,18 @@ declare class MCPKnowledgeClient {
|
|
|
40
40
|
method: string;
|
|
41
41
|
params?: {
|
|
42
42
|
[x: string]: unknown;
|
|
43
|
+
task?: {
|
|
44
|
+
[x: string]: unknown;
|
|
45
|
+
ttl?: number | null | undefined;
|
|
46
|
+
pollInterval?: number | undefined;
|
|
47
|
+
} | undefined;
|
|
43
48
|
_meta?: {
|
|
44
49
|
[x: string]: unknown;
|
|
45
50
|
progressToken?: string | number | undefined;
|
|
51
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
52
|
+
[x: string]: unknown;
|
|
53
|
+
taskId: string;
|
|
54
|
+
} | undefined;
|
|
46
55
|
} | undefined;
|
|
47
56
|
} | undefined;
|
|
48
57
|
}, {
|
|
@@ -51,21 +60,38 @@ declare class MCPKnowledgeClient {
|
|
|
51
60
|
[x: string]: unknown;
|
|
52
61
|
_meta?: {
|
|
53
62
|
[x: string]: unknown;
|
|
63
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
64
|
+
[x: string]: unknown;
|
|
65
|
+
taskId: string;
|
|
66
|
+
} | undefined;
|
|
54
67
|
} | undefined;
|
|
55
68
|
} | undefined;
|
|
56
69
|
}, {
|
|
57
70
|
[x: string]: unknown;
|
|
58
71
|
_meta?: {
|
|
59
72
|
[x: string]: unknown;
|
|
73
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
74
|
+
[x: string]: unknown;
|
|
75
|
+
taskId: string;
|
|
76
|
+
} | undefined;
|
|
60
77
|
} | undefined;
|
|
61
78
|
}>>;
|
|
62
79
|
connectInternal(): Promise<Client<{
|
|
63
80
|
method: string;
|
|
64
81
|
params?: {
|
|
65
82
|
[x: string]: unknown;
|
|
83
|
+
task?: {
|
|
84
|
+
[x: string]: unknown;
|
|
85
|
+
ttl?: number | null | undefined;
|
|
86
|
+
pollInterval?: number | undefined;
|
|
87
|
+
} | undefined;
|
|
66
88
|
_meta?: {
|
|
67
89
|
[x: string]: unknown;
|
|
68
90
|
progressToken?: string | number | undefined;
|
|
91
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
92
|
+
[x: string]: unknown;
|
|
93
|
+
taskId: string;
|
|
94
|
+
} | undefined;
|
|
69
95
|
} | undefined;
|
|
70
96
|
} | undefined;
|
|
71
97
|
}, {
|
|
@@ -74,12 +100,20 @@ declare class MCPKnowledgeClient {
|
|
|
74
100
|
[x: string]: unknown;
|
|
75
101
|
_meta?: {
|
|
76
102
|
[x: string]: unknown;
|
|
103
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
104
|
+
[x: string]: unknown;
|
|
105
|
+
taskId: string;
|
|
106
|
+
} | undefined;
|
|
77
107
|
} | undefined;
|
|
78
108
|
} | undefined;
|
|
79
109
|
}, {
|
|
80
110
|
[x: string]: unknown;
|
|
81
111
|
_meta?: {
|
|
82
112
|
[x: string]: unknown;
|
|
113
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
114
|
+
[x: string]: unknown;
|
|
115
|
+
taskId: string;
|
|
116
|
+
} | undefined;
|
|
83
117
|
} | undefined;
|
|
84
118
|
}>>;
|
|
85
119
|
/** Disconnect from server */
|
|
@@ -11,7 +11,7 @@ import{v4 as Me}from"uuid";function ye(l){let i=(l||"").split(`
|
|
|
11
11
|
|
|
12
12
|
`),i.createGroup("actions").setItemPadding(25),i.createGroup("messages").setItemPadding(10),i})();this.config=i,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(i){throw new Error("Not implemented")}addUserMessage(i){throw new Error("Not implemented")}addAssistantMessage(i){throw new Error("Not implemented")}onBeforeIncomingMessage(i){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(i){return this.toolGroup.add({id:i.name,customData:i,cannotRemove:i.isContext,sortOrder:101,disabled:i.disabled,content:JSON.stringify(i)})}};import{v4 as X}from"uuid";var S=new h("ChatGPT"),H=class extends W{async sendMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(e),customData:e}),await this.processMessages();let s=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return s?.role=="assistant"&&s.content||""}addAssistantMessage(i){let e={role:"assistant",content:i};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(e),customData:e})}addUserMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(i=>i.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),S.debugEnabled&&S.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(t=>t.customData),messages:this.messageGroup.items.map(t=>t.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let t of e.tool_calls)await this.processToolCall(t);await this.processMessages()}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendRequest(i){let e={};return e["Content-Type"]="application/json",this.config.apiKey&&(e.Authorization=`Bearer ${this.config.apiKey}`),await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:e,body:JSON.stringify(i)})}async sendToAPI(i){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let a=this.messageGroup.items.length-1;a>=0;a--){let d=this.messageGroup.items[a].customData;if(d.role=="assistant"&&d.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(d.role=="user")break}S.debugEnabled&&S.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(a=>a.customData),messages:this.messageGroup.items.map(a=>a.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(a=>a.customData)]};for(let a of this.toolGroup.getAll()){let d=a.customData;d.description&&d.description.length>1024&&S.warn(`Tool description for "${d.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:d.name,description:(d.description||"").substring(0,1024),parameters:d.params}};t.tools.push(c)}if(t.user||delete t.user,t.tools.length||delete t.tools,i)return t;let s=await this.sendRequest(t);if(!s.ok){let a=`${s.status} ${s.statusText}`;try{let c=await s.json();a=c.errorText||c.error?.message||c.error||a}catch{}let d=new Error(a);throw d.code=s.status,d}let n=null,o=null;if(this.config.stream){for await(let d of ke(s.body)){if(d.data=="[DONE]")break;if(!d.data)continue;let c=JSON.parse(d.data);if(o){for(let r in c.choices[0].delta)if(typeof c.choices[0].delta[r]=="string"){if(r=="role"&&o[r]==c.choices[0].delta[r])continue;o[r]=(o[r]||"")+c.choices[0].delta[r]}for(let r of c.choices[0].delta.tool_calls||[]){if(o.tool_calls||(o.tool_calls=[]),!o.tool_calls[r.index]){o.tool_calls[r.index]=r;continue}let u=o.tool_calls[r.index];u.function=u.function||{},u.function.name=(u.function.name||"")+(r.function?.name||""),u.function.arguments=(u.function.arguments||"")+(r.function?.arguments||"")}}else o={chunkID:c.id,...c.choices[0].delta};o?.content&&!o.content.startsWith("{")&&this.config.onAIMessage?.(o.content,!0)}let a=Fe(JSON.stringify(t)+JSON.stringify(o)||"");this.stats.tokensUsed+=a,S.debug(`Estimated ${a} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else n=await s.json(),this.stats.tokensUsed+=n?.usage?.total_tokens||0,S.debug(`Used ${n?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),o=n?.choices?.[0]?.message;if(o||(S.warn("No response block in API response."),o={role:"assistant",content:""}),o.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(o),this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(o),customData:o}),o.content&&this.config.onAIMessage?.(o.content,!1)}async processToolCall(i){try{let t=this.toolGroup.items.find(a=>a.id==i.function.name)?.customData;if(!t)throw new Error(`Tool "${i.function.name}" not found.`);let s=JSON.parse(i.function.arguments);this.config.onAIToolStart?.(i.function.name,s);let n=await t.callback(s);typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success");let o={role:"tool",content:n,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(o),customData:o})}catch(e){S.warn(`Unable to process tool call for "${i?.function?.name}"`,e);let t={role:"tool",content:`Error: ${e.message}`,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(t),customData:t})}}};import Ye from"@anthropic-ai/sdk";import{v4 as U}from"uuid";var j=new h("AnthropicChat"),$=class extends W{addUserMessage(i){let e={role:"user",content:i||""};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(e),customData:e})}addAssistantMessage(i){let e={role:"assistant",content:i||""};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(e),customData:e})}async sendMessage(i){this.addUserMessage(i);let e=new Ye({apiKey:this.config.apiKey,baseURL:this.config.endpoint,dangerouslyAllowBrowser:!0}),t=!0,s="",n="";for(;t;){t=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),j.debug("Before processing state",{messages:this.messageGroup.getAll().map(p=>p.customData),tools:this.toolGroup.getAll().map(p=>p.customData),context:this.contextGroup.getAll().map(p=>p.content)});let o=this.toolGroup.getAll().map(p=>({name:p.customData?.name||"",description:p.customData?.description||"",input_schema:{type:"object",required:p.customData?.params.required||[],properties:p.customData?.params.properties||{}}})),a;if(this.config.stream){let p=e.messages.stream({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(Z=>Z.customData),tools:o,stream:!0});p.on("text",Z=>{n+=Z,this.config.onAIMessage?.(n,!0)}),a=await p.finalMessage()}else a=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(p=>p.customData),tools:o});j.debug("Message received",a);let d=!0;Array.isArray(a.content)&&a.content.length==0&&(d=!1);let c={role:a.role,content:a.content};d&&this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(c),customData:c});let r=[];for(let p of a.content)p.type=="thinking"?j.debug(`AI is thinking: ${p.thinking}`):p.type=="text"?s+=p.text||`
|
|
13
13
|
|
|
14
|
-
`:p.type=="tool_use"&&r.push(this.performToolCall(p));let u=await Promise.all(r);if(u.length>0){let p={role:"user",content:u};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(p),customData:p}),t=!0}this.config.onAIMessage?.(s,!0),this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return s=s.trim(),this.config.onAIMessage?.(s,!1),s}async performToolCall(i){try{let e=this.toolGroup.getAll().find(s=>s.customData?.name==i.name);if(!e)throw new Error(`Tool ${i.name} not found`);this.config.onAIToolStart?.(i.name,i.input);let t=await e.customData.callback(i.input);return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),{type:"tool_result",tool_use_id:i.id,content:String(t||"")}}catch(e){return j.error(`Error performing tool call ${i.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:i.id,content:`Error performing tool call ${i.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import{v4 as we}from"uuid";import Qe from"minisearch";var Xe=l=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(i,e)=>{let t=await e.knowledgeBase.search(i.query),s=e;s._lastKBsearch=i.query,s._nextRequestUseKBitems=t,e.submitAnalyticsEvent({type:"kb-search",query:i.query,results:t});let n=t.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=t.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:i.url}),`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,e.submitAnalyticsEvent({type:"change-route",path:t}),`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),s=encodeURIComponent(i.subject),n=encodeURIComponent(i.body),o=`mailto:${t}?subject=${s}&body=${n}`;try{window.location.href=o}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:i.email_address,subject:i.subject,body_length:i.body.length}),`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as Te}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Oe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Je}from"@modelcontextprotocol/sdk/client/sse.js";var G={name:"@intelliweave/embedded",version:"1.9.69-beta.4",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.12.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as He,ToolListChangedNotificationSchema as Ue}from"@modelcontextprotocol/sdk/types.js";var g=new h("MCPKnowledgeClient"),Q=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){g.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Te({name:G.name,version:G.version}),t=new Oe(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Te({name:G.name,version:G.version}),s=new Je(new URL(this.config.baseURL));return await t.connect(s),g.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{g.error(`MCP client error: ${e.message}`)},i.onclose=()=>{g.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(He,e=>{e.params.level=="critical"?g.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?g.error(`[Server] ${e.params.data}`):e.params.level=="error"?g.error(`[Server] ${e.params.data}`):e.params.level=="warning"?g.warn(`[Server] ${e.params.data}`):e.params.level=="info"?g.info(`[Server] ${e.params.data}`):e.params.level=="debug"?g.debug(`[Server] ${e.params.data}`):g.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(Ue,e=>{g.debug("Tool list changed",e),this.fetchTools()}),g.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let s=await this.client.listTools({cursor:e});e=s.nextCursor;for(let n of s.tools||[])i.push(n);if(!s?.tools?.length||!e)break}let t=[];for(let s of i){let n=!!(this.config.searchToolName&&s.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:s.name,name:s.name,content:s.description||"",type:"action",isContext:!0,parameters:s.inputSchema,action:o=>this.performToolCall(s.name,o),disabled:n})}g.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,g.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return g.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let s;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let n=0;n<s.length;n++){let o=s[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return e}async performToolCall(i,e){await this.connect(),g.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let s=t.content?.[0]?.text||"Unknown error";throw g.error(`Error calling tool ${i}: ${s}`),new Error(`Error calling tool ${i}: ${s}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};import{v4 as je}from"uuid";var $e=new h("Statistics"),N=[];async function f(l,i){let e={...i,event_id:je(),event_date:new Date().toISOString(),sdk_version:G.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(N.push(e),!l||(await new Promise(s=>setTimeout(s,5e3)),N.length===0))return;let t=N.slice();N.length=0;try{let s=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){$e.warn("Failed to submit analytics event:",s),N.push(...t);return}}var k=new h("KnowledgeBase"),ve=1,q=class l{constructor(i){this._sources=[{id:"core.internal",query:async()=>Xe(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${ve++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return m().knowledgeBaseSources&&(i=i.concat(m().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();k.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async c=>{try{let r=Date.now(),u=await c.query(i);return k.debug(`Source '${c.id}' took ${Date.now()-r}ms`),u||[]}catch(r){return k.warn(`Knowledge source '${c.id}' failed:`,r),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),m().knowledgeBase&&(n=n.concat(m().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let r=n[c];r.id=r.id||`temp.${c}`,r._functionID=r.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!r.action&&r.type=="tour"&&(r.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!r.action&&r.type=="info"&&(r.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new Qe({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(n);let d=o.search(i).map(c=>n.find(r=>r.id==c.id));for(let c of n)c.isContext&&(d.find(r=>r.id===c.id)||d.push(c));return this.lastResults=d,f(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),k.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${ve++}`),k.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{k.debug(`Calling remote knowledge base action: ${d.id}`);let r={type:"action",userID:this.ai.userID,actionID:d.id,parameters:c},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return a(p.updateItems||[]),p.response},a=d=>{for(let c of d){if(!c.id){k.warn("KB item skipped since it has no ID.",c);continue}let r=t.find(u=>u.id==c.id);if(r){r.name=c.name||r.name||"",r.content=c.content||r.content||"",r.disabled=c.disabled??r.disabled,r.isContext=c.isContext??r.isContext,r.parameters=c.parameters||r.parameters||[],r.tags=c.tags||r.tags,r.type=c.type||r.type;continue}t.push({...c,action:u=>o(c,u)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",query:d},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let u=await r.json();return n=!u.noCache,s.includes(d)||s.push(d),a(u.items),t})}clone(){let i=new l(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${ve++}`);let e=new Q(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ee=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
14
|
+
`:p.type=="tool_use"&&r.push(this.performToolCall(p));let u=await Promise.all(r);if(u.length>0){let p={role:"user",content:u};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(p),customData:p}),t=!0}this.config.onAIMessage?.(s,!0),this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return s=s.trim(),this.config.onAIMessage?.(s,!1),s}async performToolCall(i){try{let e=this.toolGroup.getAll().find(s=>s.customData?.name==i.name);if(!e)throw new Error(`Tool ${i.name} not found`);this.config.onAIToolStart?.(i.name,i.input);let t=await e.customData.callback(i.input);return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),{type:"tool_result",tool_use_id:i.id,content:String(t||"")}}catch(e){return j.error(`Error performing tool call ${i.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:i.id,content:`Error performing tool call ${i.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import{v4 as we}from"uuid";import Qe from"minisearch";var Xe=l=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(i,e)=>{let t=await e.knowledgeBase.search(i.query),s=e;s._lastKBsearch=i.query,s._nextRequestUseKBitems=t,e.submitAnalyticsEvent({type:"kb-search",query:i.query,results:t});let n=t.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=t.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:i.url}),`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,e.submitAnalyticsEvent({type:"change-route",path:t}),`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),s=encodeURIComponent(i.subject),n=encodeURIComponent(i.body),o=`mailto:${t}?subject=${s}&body=${n}`;try{window.location.href=o}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:i.email_address,subject:i.subject,body_length:i.body.length}),`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as Te}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Oe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Je}from"@modelcontextprotocol/sdk/client/sse.js";var G={name:"@intelliweave/embedded",version:"2.0.70",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as He,ToolListChangedNotificationSchema as Ue}from"@modelcontextprotocol/sdk/types.js";var g=new h("MCPKnowledgeClient"),Q=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){g.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Te({name:G.name,version:G.version}),t=new Oe(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Te({name:G.name,version:G.version}),s=new Je(new URL(this.config.baseURL));return await t.connect(s),g.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{g.error(`MCP client error: ${e.message}`)},i.onclose=()=>{g.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(He,e=>{e.params.level=="critical"?g.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?g.error(`[Server] ${e.params.data}`):e.params.level=="error"?g.error(`[Server] ${e.params.data}`):e.params.level=="warning"?g.warn(`[Server] ${e.params.data}`):e.params.level=="info"?g.info(`[Server] ${e.params.data}`):e.params.level=="debug"?g.debug(`[Server] ${e.params.data}`):g.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(Ue,e=>{g.debug("Tool list changed",e),this.fetchTools()}),g.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let s=await this.client.listTools({cursor:e});e=s.nextCursor;for(let n of s.tools||[])i.push(n);if(!s?.tools?.length||!e)break}let t=[];for(let s of i){let n=!!(this.config.searchToolName&&s.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:s.name,name:s.name,content:s.description||"",type:"action",isContext:!0,parameters:s.inputSchema,action:o=>this.performToolCall(s.name,o),disabled:n})}g.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,g.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return g.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let s;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let n=0;n<s.length;n++){let o=s[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return e}async performToolCall(i,e){await this.connect(),g.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let s=t.content?.[0]?.text||"Unknown error";throw g.error(`Error calling tool ${i}: ${s}`),new Error(`Error calling tool ${i}: ${s}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};import{v4 as je}from"uuid";var $e=new h("Statistics"),N=[];async function f(l,i){let e={...i,event_id:je(),event_date:new Date().toISOString(),sdk_version:G.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(N.push(e),!l||(await new Promise(s=>setTimeout(s,5e3)),N.length===0))return;let t=N.slice();N.length=0;try{let s=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){$e.warn("Failed to submit analytics event:",s),N.push(...t);return}}var k=new h("KnowledgeBase"),ve=1,q=class l{constructor(i){this._sources=[{id:"core.internal",query:async()=>Xe(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${ve++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return m().knowledgeBaseSources&&(i=i.concat(m().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();k.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async c=>{try{let r=Date.now(),u=await c.query(i);return k.debug(`Source '${c.id}' took ${Date.now()-r}ms`),u||[]}catch(r){return k.warn(`Knowledge source '${c.id}' failed:`,r),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),m().knowledgeBase&&(n=n.concat(m().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let r=n[c];r.id=r.id||`temp.${c}`,r._functionID=r.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!r.action&&r.type=="tour"&&(r.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!r.action&&r.type=="info"&&(r.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new Qe({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(n);let d=o.search(i).map(c=>n.find(r=>r.id==c.id));for(let c of n)c.isContext&&(d.find(r=>r.id===c.id)||d.push(c));return this.lastResults=d,f(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),k.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${ve++}`),k.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{k.debug(`Calling remote knowledge base action: ${d.id}`);let r={type:"action",userID:this.ai.userID,actionID:d.id,parameters:c},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return a(p.updateItems||[]),p.response},a=d=>{for(let c of d){if(!c.id){k.warn("KB item skipped since it has no ID.",c);continue}let r=t.find(u=>u.id==c.id);if(r){r.name=c.name||r.name||"",r.content=c.content||r.content||"",r.disabled=c.disabled??r.disabled,r.isContext=c.isContext??r.isContext,r.parameters=c.parameters||r.parameters||[],r.tags=c.tags||r.tags,r.type=c.type||r.type;continue}t.push({...c,action:u=>o(c,u)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",query:d},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let u=await r.json();return n=!u.noCache,s.includes(d)||s.push(d),a(u.items),t})}clone(){let i=new l(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${ve++}`);let e=new Q(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ee=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
15
15
|
|
|
16
16
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(e.toLowerCase().includes("true"))return!0;if(e.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+e)}async choose(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
17
17
|
|
|
@@ -28,10 +28,10 @@ Objects should have the following keys:
|
|
|
28
28
|
${i.extractions.map(s=>`- ${s.name} (${s.type}): ${s.description||"No description provided."}`).join(`
|
|
29
29
|
`)}
|
|
30
30
|
`,t=await this.instruct({...i,instruction:e});if(t=t.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),i.allowMultiple){let s=t.split(`
|
|
31
|
-
`).map(o=>o.trim()).filter(o=>!!o.trim()),n=[];for(let o of s)try{n.push(JSON.parse(o))}catch(a){console.error("Failed to parse line as JSON:",o,a.message)}return n}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))||""}};var v=new h("Main"),Ee=new Set,I=class I extends EventTarget{constructor(){super(...arguments);this.conversationID=we();this.knowledgeBase=new q(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new ee(this);this.userID=Ie();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this._lastTrackedTokens=0}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:I.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){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{v.debug("Loading configuration...");let t=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!t.ok)throw new Error(`Failed to load configuration: ${t.status} ${t.statusText}`);try{this.config=await t.json(),v.debug("Config loaded successfully:",this.config),this.config&&v.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(s){v.error("Failed to parse JSON response:",s);try{let n=await t.clone().text();v.error("Raw response that failed parsing:",n)}catch{v.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${s}`)}})(),(async()=>{try{let t=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!t.ok)throw new Error(`Failed to load VAD model: ${t.status} ${t.statusText}`);this.vadModel=await t.blob()}catch(t){v.warn(`Failed to load VAD model, some features will be unavailable. ${t.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let t of this.config.knowledge||[])t.url&&t.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:t.id,searchToolName:t.mcpSearchToolName,baseURL:t.url}):t.url&&this.knowledgeBase.registerSourceFromURL(t.url);for(let t of this.config.knowledge||[])t.entries?.length&&this.knowledgeBase.registerSource(t.id,()=>t.entries||[]);if(this.config.mcpServers)for(let t of this.config.mcpServers)this.knowledgeBase.registerMCPSource(t);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this.config}catch(t){throw v.warn("Failed to load:",t),this.error=t,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:t}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:t}})),t}}setModel(e){let t=this.models.find(n=>n.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let s={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(n,o)=>{let a=this.knowledgeBase.getCachedEntry(n);this.onAIToolStart?.(a?.id||n,o)}};t.config.providerID==="anthropic"?this.currentModel=new $(s):this.currentModel=new H(s),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=m().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=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,content:
|
|
32
|
-
You have access to a database of knowledge base items. These include "info" type items which provide information and "tour" type items which contain instructions you should follow (only do one item at a time).${
|
|
31
|
+
`).map(o=>o.trim()).filter(o=>!!o.trim()),n=[];for(let o of s)try{n.push(JSON.parse(o))}catch(a){console.error("Failed to parse line as JSON:",o,a.message)}return n}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))||""}};var v=new h("Main"),Ee=new Set,I=class I extends EventTarget{constructor(){super(...arguments);this.conversationID=we();this.knowledgeBase=new q(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new ee(this);this.userID=Ie();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this._lastTrackedTokens=0}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:I.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){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{v.debug("Loading configuration...");let t=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!t.ok)throw new Error(`Failed to load configuration: ${t.status} ${t.statusText}`);try{this.config=await t.json(),v.debug("Config loaded successfully:",this.config),this.config&&v.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(s){v.error("Failed to parse JSON response:",s);try{let n=await t.clone().text();v.error("Raw response that failed parsing:",n)}catch{v.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${s}`)}})(),(async()=>{try{let t=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!t.ok)throw new Error(`Failed to load VAD model: ${t.status} ${t.statusText}`);this.vadModel=await t.blob()}catch(t){v.warn(`Failed to load VAD model, some features will be unavailable. ${t.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let t of this.config.knowledge||[])t.url&&t.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:t.id,searchToolName:t.mcpSearchToolName,baseURL:t.url}):t.url&&this.knowledgeBase.registerSourceFromURL(t.url);for(let t of this.config.knowledge||[])t.entries?.length&&this.knowledgeBase.registerSource(t.id,()=>t.entries||[]);if(this.config.mcpServers)for(let t of this.config.mcpServers)this.knowledgeBase.registerMCPSource(t);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this.config}catch(t){throw v.warn("Failed to load:",t),this.error=t,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:t}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:t}})),t}}setModel(e){let t=this.models.find(n=>n.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let s={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(n,o)=>{let a=this.knowledgeBase.getCachedEntry(n);this.onAIToolStart?.(a?.id||n,o)}};t.config.providerID==="anthropic"?this.currentModel=new $(s):this.currentModel=new H(s),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=m().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,content:t}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,content:"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_description",sortOrder:100,cannotRemove:!0,content:`# Knowledge Database
|
|
32
|
+
You have access to a database of knowledge base items. These include "info" type items which provide information and "tour" type items which contain instructions you should follow (only do one item at a time).${e.length==0?`
|
|
33
33
|
|
|
34
|
-
(no items found)`:""}`});for(let n of
|
|
34
|
+
(no items found)`:""}`});for(let n of e)if(n.type=="info"||n.type=="tour"||n.type=="input-event"){let o=ye(typeof n.content=="function"?n.content():n.content);this.currentModel.contextGroup.add({id:n.id,customData:n,cannotRemove:n.isContext,sortOrder:101,disabled:n.disabled,content:`## ${n.type}: ${n.name}
|
|
35
35
|
${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeof n.content=="function"?n.content():n.content),params:We(n.parameters||[{name:"value",type:"string",description:"Input"}]),removeFromMessageHistory:!!n.removeFromMessageHistory,callback:a=>this.toolRunKBAction(n,a),kb:n};this.currentModel.registerTool(o)}else continue;let s=this.currentModel.contextGroup.getAllAsString();this._lastSystemMsg!=s&&(this._lastSystemMsg=s,this.submitAnalyticsEvent({type:"system-msg",txt:s}))}processIncomingMessage(e,t){if(!t){let s=this.currentModel?.stats?.tokensUsed||0,n=s-(this._lastTrackedTokens||0);this._lastTrackedTokens=s,f(this,{event_type:"message_receive",value:n,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:s}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:t,message:e}})),this.onAIMessage?.(e,!!t)}async sendMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)return v.warn("Cannot send message while another message is being processed."),null;this.isProcessing=!0;try{this._messageStartTime=Date.now(),Ee.has(this.conversationID)||(Ee.add(this.conversationID),f(this,{event_type:"session_start"})),this._lastTrackedTokens=this.currentModel?.stats?.tokensUsed||0,f(this,{event_type:"message_send",value_str:"",event_properties:{message_length:e.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),this.submitAnalyticsEvent({type:"message",role:"user",message:e,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()});let t=await this.currentModel.sendMessage(e);return t&&typeof t=="string"&&t.trim().length>0&&this.submitAnalyticsEvent({type:"message",role:"assistant",message:t,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()}),t}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let s=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:t,ai:this}}));let n=await e.action(t,this),o=Date.now()-s;return f(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:o,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,result:n}})),n}catch(n){let o=Date.now()-s;throw f(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:o,success:!1,error_message:n.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,error:n}})),n}}submitAnalyticsEvent(e){m().analytics===!1||this.config?.analytics===!1||fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(t=>{v.debug("Failed to submit analytics event:",t)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=we(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(e)}exportState(){return{type:"intelliweave/state/v1",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll().map(e=>e.customData)}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v1")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let t of e.messages)this.currentModel.messageGroup.add({id:we(),content:JSON.stringify(t),customData:t})}clone(){let e=new I;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.knowledgeBase=this.knowledgeBase.clone(),e}};I.version=G.version,I.builtInActionsVersion="1.0.0",v.debug("\u{1F6A8}\u{1F6A8}\u{1F6A8} NEW SDK BUILD LOADED - Built-in Actions Version:",I.builtInActionsVersion);var T=I;var y=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(e={},t=""){this.register();let s=document.createElement(this.tagName);for(let n in e)s.setAttribute(n,e[n]);return s.onBeforeCreate(),s.innerHTML=t,s}static add(e={},t=""){this.register();let s=n=>n.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">");return`<${this.tagName} ${Object.keys(e).map(n=>`${n}="${s(e[n]+"")}"`).join(" ")}>${t}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(e,t,s){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(e,t)=>this.getAttribute(t.toString())||"",set:(e,t,s)=>(this.getAttribute(t.toString())===s||(s?this.setAttribute(t.toString(),s):this.removeAttribute(t.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(e,t)=>this._state[t],set:(e,t,s)=>(this._state[t]=s,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(e){return!!this.root?.getElementById(e)}child(e){let t=this.root?.getElementById(e);if(!t)throw new Error(`Child with ID ${e} not found`);return t}};y.observedAttributes=[],y.tagName="",y._isRegistered=!1;var Re='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var Ve='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Le='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var _=class extends y{constructor(){super(...arguments);this.html=()=>`
|
|
36
36
|
|
|
37
37
|
<!-- Styling -->
|
|
@@ -153,23 +153,31 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
|
|
|
153
153
|
}
|
|
154
154
|
|
|
155
155
|
#root {
|
|
156
|
-
position:
|
|
156
|
+
position: absolute;
|
|
157
157
|
top: 0px;
|
|
158
|
-
|
|
159
|
-
width:
|
|
160
|
-
height:
|
|
158
|
+
left: 0px;
|
|
159
|
+
width: 100%;
|
|
160
|
+
height: 100%;
|
|
161
161
|
z-index: 200001;
|
|
162
|
-
transition:
|
|
163
|
-
animation: web-weaver-logo-hover 5s infinite ease-in-out;
|
|
162
|
+
transition: width 0.25s, height 0.25s;
|
|
164
163
|
cursor: pointer;
|
|
165
164
|
overflow: visible!important;
|
|
166
165
|
object-fit: contain;
|
|
167
166
|
}
|
|
168
167
|
|
|
168
|
+
#root.focused-mode {
|
|
169
|
+
position: fixed;
|
|
170
|
+
transition: top 0.15s ease-out, left 0.15s ease-out, width 0.25s, height 0.25s;
|
|
171
|
+
}
|
|
172
|
+
|
|
169
173
|
@keyframes web-weaver-logo-hover {
|
|
170
|
-
0% { transform: translate(0px, -
|
|
171
|
-
50% { transform: translate(0px,
|
|
172
|
-
100% { transform: translate(0px, -
|
|
174
|
+
0% { transform: translate(0px, -1px); }
|
|
175
|
+
50% { transform: translate(0px, 1px); }
|
|
176
|
+
100% { transform: translate(0px, -1px); }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
#root:not(.focused-mode) {
|
|
180
|
+
animation: web-weaver-logo-hover 5s infinite ease-in-out;
|
|
173
181
|
}
|
|
174
182
|
|
|
175
183
|
#root #web-weaver-logo {
|
|
@@ -188,7 +196,7 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
|
|
|
188
196
|
<!-- Logo -->
|
|
189
197
|
<img id='root' />
|
|
190
198
|
|
|
191
|
-
`;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),
|
|
199
|
+
`;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let t=this.attr.logo||Be;this._lastLogoSrc!=t&&(this._lastLogoSrc=t,e.src=t);let s=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(s){let n=window.visualViewport?.offsetTop||0,o=window.visualViewport?.offsetLeft||0,a=s.getBoundingClientRect();if(!a)return;e.classList.add("focused-mode"),e.style.width="128px",e.style.height="128px",e.style.left=Math.round(a.x+a.width/2-128/2+o)+"px",e.style.top=Math.round(a.y+a.height/2-128/2+n)+"px"}else e.classList.remove("focused-mode"),e.style.width="",e.style.height="",e.style.left="",e.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};D.observedAttributes=["logo","focusID"];import dt from"rehype-external-links";import ht from"rehype-format";import ut from"rehype-stringify";import pt from"remark-parse";import mt from"remark-rehype";import{unified as gt}from"unified";var K=class extends y{constructor(){super(...arguments);this.html=()=>`
|
|
192
200
|
|
|
193
201
|
<!-- Styling -->
|
|
194
202
|
<style>
|
|
Binary file
|
package/dist/node/node.d.ts
CHANGED
|
@@ -744,9 +744,18 @@ declare class MCPKnowledgeClient {
|
|
|
744
744
|
method: string;
|
|
745
745
|
params?: {
|
|
746
746
|
[x: string]: unknown;
|
|
747
|
+
task?: {
|
|
748
|
+
[x: string]: unknown;
|
|
749
|
+
ttl?: number | null | undefined;
|
|
750
|
+
pollInterval?: number | undefined;
|
|
751
|
+
} | undefined;
|
|
747
752
|
_meta?: {
|
|
748
753
|
[x: string]: unknown;
|
|
749
754
|
progressToken?: string | number | undefined;
|
|
755
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
756
|
+
[x: string]: unknown;
|
|
757
|
+
taskId: string;
|
|
758
|
+
} | undefined;
|
|
750
759
|
} | undefined;
|
|
751
760
|
} | undefined;
|
|
752
761
|
}, {
|
|
@@ -755,21 +764,38 @@ declare class MCPKnowledgeClient {
|
|
|
755
764
|
[x: string]: unknown;
|
|
756
765
|
_meta?: {
|
|
757
766
|
[x: string]: unknown;
|
|
767
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
768
|
+
[x: string]: unknown;
|
|
769
|
+
taskId: string;
|
|
770
|
+
} | undefined;
|
|
758
771
|
} | undefined;
|
|
759
772
|
} | undefined;
|
|
760
773
|
}, {
|
|
761
774
|
[x: string]: unknown;
|
|
762
775
|
_meta?: {
|
|
763
776
|
[x: string]: unknown;
|
|
777
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
778
|
+
[x: string]: unknown;
|
|
779
|
+
taskId: string;
|
|
780
|
+
} | undefined;
|
|
764
781
|
} | undefined;
|
|
765
782
|
}>>;
|
|
766
783
|
connectInternal(): Promise<Client<{
|
|
767
784
|
method: string;
|
|
768
785
|
params?: {
|
|
769
786
|
[x: string]: unknown;
|
|
787
|
+
task?: {
|
|
788
|
+
[x: string]: unknown;
|
|
789
|
+
ttl?: number | null | undefined;
|
|
790
|
+
pollInterval?: number | undefined;
|
|
791
|
+
} | undefined;
|
|
770
792
|
_meta?: {
|
|
771
793
|
[x: string]: unknown;
|
|
772
794
|
progressToken?: string | number | undefined;
|
|
795
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
796
|
+
[x: string]: unknown;
|
|
797
|
+
taskId: string;
|
|
798
|
+
} | undefined;
|
|
773
799
|
} | undefined;
|
|
774
800
|
} | undefined;
|
|
775
801
|
}, {
|
|
@@ -778,12 +804,20 @@ declare class MCPKnowledgeClient {
|
|
|
778
804
|
[x: string]: unknown;
|
|
779
805
|
_meta?: {
|
|
780
806
|
[x: string]: unknown;
|
|
807
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
808
|
+
[x: string]: unknown;
|
|
809
|
+
taskId: string;
|
|
810
|
+
} | undefined;
|
|
781
811
|
} | undefined;
|
|
782
812
|
} | undefined;
|
|
783
813
|
}, {
|
|
784
814
|
[x: string]: unknown;
|
|
785
815
|
_meta?: {
|
|
786
816
|
[x: string]: unknown;
|
|
817
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
818
|
+
[x: string]: unknown;
|
|
819
|
+
taskId: string;
|
|
820
|
+
} | undefined;
|
|
787
821
|
} | undefined;
|
|
788
822
|
}>>;
|
|
789
823
|
/** Disconnect from server */
|
package/dist/node/node.js
CHANGED
|
@@ -11,7 +11,7 @@ import{v4 as J}from"uuid";function G(u){let t=(u||"").split(`
|
|
|
11
11
|
|
|
12
12
|
`),t.createGroup("actions").setItemPadding(25),t.createGroup("messages").setItemPadding(10),t})();this.config=t,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(t){throw new Error("Not implemented")}addUserMessage(t){throw new Error("Not implemented")}addAssistantMessage(t){throw new Error("Not implemented")}onBeforeIncomingMessage(t){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(t){return this.toolGroup.add({id:t.name,customData:t,cannotRemove:t.isContext,sortOrder:101,disabled:t.disabled,content:JSON.stringify(t)})}};import{v4 as T}from"uuid";var w=new g("ChatGPT"),D=class extends I{async sendMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e}),await this.processMessages();let n=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return n?.role=="assistant"&&n.content||""}addAssistantMessage(t){let e={role:"assistant",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e})}addUserMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(t=>t.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),w.debugEnabled&&w.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(s=>s.customData),messages:this.messageGroup.items.map(s=>s.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let s of e.tool_calls)await this.processToolCall(s);await this.processMessages()}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendRequest(t){let e={};return e["Content-Type"]="application/json",this.config.apiKey&&(e.Authorization=`Bearer ${this.config.apiKey}`),await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:e,body:JSON.stringify(t)})}async sendToAPI(t){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let a=this.messageGroup.items.length-1;a>=0;a--){let r=this.messageGroup.items[a].customData;if(r.role=="assistant"&&r.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(r.role=="user")break}w.debugEnabled&&w.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(a=>a.customData),messages:this.messageGroup.items.map(a=>a.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let s={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(a=>a.customData)]};for(let a of this.toolGroup.getAll()){let r=a.customData;r.description&&r.description.length>1024&&w.warn(`Tool description for "${r.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:r.name,description:(r.description||"").substring(0,1024),parameters:r.params}};s.tools.push(c)}if(s.user||delete s.user,s.tools.length||delete s.tools,t)return s;let n=await this.sendRequest(s);if(!n.ok){let a=`${n.status} ${n.statusText}`;try{let c=await n.json();a=c.errorText||c.error?.message||c.error||a}catch{}let r=new Error(a);throw r.code=n.status,r}let i=null,o=null;if(this.config.stream){for await(let r of q(n.body)){if(r.data=="[DONE]")break;if(!r.data)continue;let c=JSON.parse(r.data);if(o){for(let l in c.choices[0].delta)if(typeof c.choices[0].delta[l]=="string"){if(l=="role"&&o[l]==c.choices[0].delta[l])continue;o[l]=(o[l]||"")+c.choices[0].delta[l]}for(let l of c.choices[0].delta.tool_calls||[]){if(o.tool_calls||(o.tool_calls=[]),!o.tool_calls[l.index]){o.tool_calls[l.index]=l;continue}let m=o.tool_calls[l.index];m.function=m.function||{},m.function.name=(m.function.name||"")+(l.function?.name||""),m.function.arguments=(m.function.arguments||"")+(l.function?.arguments||"")}}else o={chunkID:c.id,...c.choices[0].delta};o?.content&&!o.content.startsWith("{")&&this.config.onAIMessage?.(o.content,!0)}let a=oe(JSON.stringify(s)+JSON.stringify(o)||"");this.stats.tokensUsed+=a,w.debug(`Estimated ${a} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else i=await n.json(),this.stats.tokensUsed+=i?.usage?.total_tokens||0,w.debug(`Used ${i?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),o=i?.choices?.[0]?.message;if(o||(w.warn("No response block in API response."),o={role:"assistant",content:""}),o.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(o),this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(o),customData:o}),o.content&&this.config.onAIMessage?.(o.content,!1)}async processToolCall(t){try{let s=this.toolGroup.items.find(a=>a.id==t.function.name)?.customData;if(!s)throw new Error(`Tool "${t.function.name}" not found.`);let n=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,n);let i=await s.callback(n);typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success");let o={role:"tool",content:i,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(o),customData:o})}catch(e){w.warn(`Unable to process tool call for "${t?.function?.name}"`,e);let s={role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(s),customData:s})}}};import re from"@anthropic-ai/sdk";import{v4 as P}from"uuid";var O=new g("AnthropicChat"),N=class extends I{addUserMessage(t){let e={role:"user",content:t||""};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(e),customData:e})}addAssistantMessage(t){let e={role:"assistant",content:t||""};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(e),customData:e})}async sendMessage(t){this.addUserMessage(t);let e=new re({apiKey:this.config.apiKey,baseURL:this.config.endpoint,dangerouslyAllowBrowser:!0}),s=!0,n="",i="";for(;s;){s=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),O.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.customData),tools:this.toolGroup.getAll().map(d=>d.customData),context:this.contextGroup.getAll().map(d=>d.content)});let o=this.toolGroup.getAll().map(d=>({name:d.customData?.name||"",description:d.customData?.description||"",input_schema:{type:"object",required:d.customData?.params.required||[],properties:d.customData?.params.properties||{}}})),a;if(this.config.stream){let d=e.messages.stream({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(v=>v.customData),tools:o,stream:!0});d.on("text",v=>{i+=v,this.config.onAIMessage?.(i,!0)}),a=await d.finalMessage()}else a=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(d=>d.customData),tools:o});O.debug("Message received",a);let r=!0;Array.isArray(a.content)&&a.content.length==0&&(r=!1);let c={role:a.role,content:a.content};r&&this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(c),customData:c});let l=[];for(let d of a.content)d.type=="thinking"?O.debug(`AI is thinking: ${d.thinking}`):d.type=="text"?n+=d.text||`
|
|
13
13
|
|
|
14
|
-
`:d.type=="tool_use"&&l.push(this.performToolCall(d));let m=await Promise.all(l);if(m.length>0){let d={role:"user",content:m};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(d),customData:d}),s=!0}this.config.onAIMessage?.(n,!0),this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return n=n.trim(),this.config.onAIMessage?.(n,!1),n}async performToolCall(t){try{let e=this.toolGroup.getAll().find(n=>n.customData?.name==t.name);if(!e)throw new Error(`Tool ${t.name} not found`);this.config.onAIToolStart?.(t.name,t.input);let s=await e.customData.callback(t.input);return typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),{type:"tool_result",tool_use_id:t.id,content:String(s||"")}}catch(e){return O.error(`Error performing tool call ${t.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:t.id,content:`Error performing tool call ${t.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import ge from"minisearch";var Q=u=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(t,e)=>{let s=await e.knowledgeBase.search(t.query),n=e;n._lastKBsearch=t.query,n._nextRequestUseKBitems=s,e.submitAnalyticsEvent({type:"kb-search",query:t.query,results:s});let i=s.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=s.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!t.url||typeof t.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(t.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:t.url}),`Opened URL: ${t.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!t.path||typeof t.path!="string")throw new Error("Path parameter is required and must be a string.");let s=new URL(t.path,window.location.origin).pathname;return window.location.href=s,e.submitAnalyticsEvent({type:"change-route",path:s}),`Changed route to: ${s}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!t.email_address||typeof t.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!t.subject||typeof t.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!t.body||typeof t.body!="string")throw new Error("Body parameter is required and must be a string.");let s=encodeURIComponent(t.email_address),n=encodeURIComponent(t.subject),i=encodeURIComponent(t.body),o=`mailto:${s}?subject=${n}&body=${i}`;try{window.location.href=o}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:t.email_address,subject:t.subject,body_length:t.body.length}),`Email opened in default mail client. Recipient: ${t.email_address}, Subject: ${t.subject}`}}];import{Client as ee}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as le}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as ce}from"@modelcontextprotocol/sdk/client/sse.js";var y={name:"@intelliweave/embedded",version:"1.9.69-beta.4",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.12.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as ue,ToolListChangedNotificationSchema as de}from"@modelcontextprotocol/sdk/types.js";var h=new g("MCPKnowledgeClient"),W=class{constructor(t){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=t}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){h.debug("Connecting to MCP client");let t=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new ee({name:y.name,version:y.version}),s=new le(new URL(this.config.baseURL));return await e.connect(s),h.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let s=new ee({name:y.name,version:y.version}),n=new ce(new URL(this.config.baseURL));return await s.connect(n),h.debug("Connected with SSE mode"),s});return await this.disconnect(),this.client=t,t.onerror=e=>{h.error(`MCP client error: ${e.message}`)},t.onclose=()=>{h.debug("MCP client connection closed"),this.client=void 0},t.setNotificationHandler(ue,e=>{e.params.level=="critical"?h.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?h.error(`[Server] ${e.params.data}`):e.params.level=="error"?h.error(`[Server] ${e.params.data}`):e.params.level=="warning"?h.warn(`[Server] ${e.params.data}`):e.params.level=="info"?h.info(`[Server] ${e.params.data}`):e.params.level=="debug"?h.debug(`[Server] ${e.params.data}`):h.log(`[Server] ${e.params.data}`)}),t.setNotificationHandler(de,e=>{h.debug("Tool list changed",e),this.fetchTools()}),h.debug("Fetching tools from MCP server..."),await this.fetchTools(),t}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let t=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let i of n.tools||[])t.push(i);if(!n?.tools?.length||!e)break}let s=[];for(let n of t){let i=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:o=>this.performToolCall(n.name,o),disabled:i})}h.debug(`Fetched ${t.length} tools from MCP server.`),this.tools=t,this.iwActions=s}async search(t){if(t==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),s=await this.performSearchCall(t);return e=e.concat(s),this.lastSearchQuery=t,this.lastSearchResults=e,h.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(t){let e=[];if(!this.config.searchToolName)return e;let s=this.tools.find(i=>i.name==this.config.searchToolName);if(!s)return h.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(s.inputSchema.required?.length==1){let i=s.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let i=Object.keys(s.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let i=0;i<n.length;i++){let o=n[i];e.push({id:this.config.id+":"+this.config.searchToolName+":"+i,name:`Search result ${i+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(t,e){await this.connect(),h.debug(`Performing tool call for ${t} with params:`,e),this.stats.toolsCalled+=1;let s=await this.client.callTool({name:t,arguments:e});if(s.isError){let n=s.content?.[0]?.text||"Unknown error";throw h.error(`Error calling tool ${t}: ${n}`),new Error(`Error calling tool ${t}: ${n}`)}if(Array.isArray(s.content)&&s.content.length==1&&s.content[0].type=="text")try{return JSON.parse(s.content[0].text)}catch{}return s.content||[]}};import{v4 as me}from"uuid";var he=new g("Statistics"),_=[];async function b(u,t){let e={...t,event_id:me(),event_date:new Date().toISOString(),sdk_version:y.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(_.push(e),!u||(await new Promise(n=>setTimeout(n,5e3)),_.length===0))return;let s=_.slice();_.length=0;try{let n=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){he.warn("Failed to submit analytics event:",n),_.push(...s);return}}var S=new g("KnowledgeBase"),j=1,$=class u{constructor(t){this._sources=[{id:"core.internal",query:async()=>Q(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${j++}`),this._sources.push({id:s,query:e}),s}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return p().knowledgeBaseSources&&(t=t.concat(p().knowledgeBaseSources)),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){let e=Date.now();S.debug(`Searching knowledge base for: ${t}`);let s=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});s.query=t,s.entries=[],s.sources=[],typeof document<"u"&&document.dispatchEvent(s),this._windowSources=s.sources;let i=(await Promise.all(this.sources.map(async c=>{try{let l=Date.now(),m=await c.query(t);return S.debug(`Source '${c.id}' took ${Date.now()-l}ms`),m||[]}catch(l){return S.warn(`Knowledge source '${c.id}' failed:`,l),[]}}))).flat();i=i.concat(s.entries),i=i.concat(this.manualEntries),p().knowledgeBase&&(i=i.concat(p().knowledgeBase)),i=i.filter(c=>c&&!c.disabled);for(let c=0;c<i.length;c++){let l=i[c];l.id=l.id||`temp.${c}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!l.action&&l.type=="tour"&&(l.action=m=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=m=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new ge({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let r=o.search(t).map(c=>i.find(l=>l.id==c.id));for(let c of i)c.isContext&&(r.find(l=>l.id===c.id)||r.push(c));return this.lastResults=r,b(this.ai,{event_type:"kb_search",value:r.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),S.debug("Found results:",r),r}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${j++}`),S.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],i=!0,o=async(r,c)=>{S.debug(`Calling remote knowledge base action: ${r.id}`);let l={type:"action",userID:this.ai.userID,actionID:r.id,parameters:c},m=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!m.ok)throw new Error(`HTTP Error ${m.status} ${m.statusText}`);let d=await m.json();return a(d.updateItems||[]),d.response},a=r=>{for(let c of r){if(!c.id){S.warn("KB item skipped since it has no ID.",c);continue}let l=s.find(m=>m.id==c.id);if(l){l.name=c.name||l.name||"",l.content=c.content||l.content||"",l.disabled=c.disabled??l.disabled,l.isContext=c.isContext??l.isContext,l.parameters=c.parameters||l.parameters||[],l.tags=c.tags||l.tags,l.type=c.type||l.type;continue}s.push({...c,action:m=>o(c,m)})}};this.registerSource(e,async r=>{if(i&&n.includes(r))return s;let c={type:"search",userID:this.ai?.userID||"",query:r},l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let m=await l.json();return i=!m.noCache,n.includes(r)||n.push(r),a(m.items),s})}clone(){let t=new u(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}registerMCPSource(t){t.id||(t.id=`external.${j++}`);let e=new W(t);return this.registerSource(t.id,s=>e.search(s)),e}};import{v4 as F}from"uuid";var K=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
14
|
+
`:d.type=="tool_use"&&l.push(this.performToolCall(d));let m=await Promise.all(l);if(m.length>0){let d={role:"user",content:m};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(d),customData:d}),s=!0}this.config.onAIMessage?.(n,!0),this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return n=n.trim(),this.config.onAIMessage?.(n,!1),n}async performToolCall(t){try{let e=this.toolGroup.getAll().find(n=>n.customData?.name==t.name);if(!e)throw new Error(`Tool ${t.name} not found`);this.config.onAIToolStart?.(t.name,t.input);let s=await e.customData.callback(t.input);return typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),{type:"tool_result",tool_use_id:t.id,content:String(s||"")}}catch(e){return O.error(`Error performing tool call ${t.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:t.id,content:`Error performing tool call ${t.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import ge from"minisearch";var Q=u=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(t,e)=>{let s=await e.knowledgeBase.search(t.query),n=e;n._lastKBsearch=t.query,n._nextRequestUseKBitems=s,e.submitAnalyticsEvent({type:"kb-search",query:t.query,results:s});let i=s.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=s.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!t.url||typeof t.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(t.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:t.url}),`Opened URL: ${t.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!t.path||typeof t.path!="string")throw new Error("Path parameter is required and must be a string.");let s=new URL(t.path,window.location.origin).pathname;return window.location.href=s,e.submitAnalyticsEvent({type:"change-route",path:s}),`Changed route to: ${s}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!t.email_address||typeof t.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!t.subject||typeof t.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!t.body||typeof t.body!="string")throw new Error("Body parameter is required and must be a string.");let s=encodeURIComponent(t.email_address),n=encodeURIComponent(t.subject),i=encodeURIComponent(t.body),o=`mailto:${s}?subject=${n}&body=${i}`;try{window.location.href=o}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:t.email_address,subject:t.subject,body_length:t.body.length}),`Email opened in default mail client. Recipient: ${t.email_address}, Subject: ${t.subject}`}}];import{Client as ee}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as le}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as ce}from"@modelcontextprotocol/sdk/client/sse.js";var y={name:"@intelliweave/embedded",version:"2.0.70",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as ue,ToolListChangedNotificationSchema as de}from"@modelcontextprotocol/sdk/types.js";var h=new g("MCPKnowledgeClient"),W=class{constructor(t){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=t}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){h.debug("Connecting to MCP client");let t=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new ee({name:y.name,version:y.version}),s=new le(new URL(this.config.baseURL));return await e.connect(s),h.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let s=new ee({name:y.name,version:y.version}),n=new ce(new URL(this.config.baseURL));return await s.connect(n),h.debug("Connected with SSE mode"),s});return await this.disconnect(),this.client=t,t.onerror=e=>{h.error(`MCP client error: ${e.message}`)},t.onclose=()=>{h.debug("MCP client connection closed"),this.client=void 0},t.setNotificationHandler(ue,e=>{e.params.level=="critical"?h.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?h.error(`[Server] ${e.params.data}`):e.params.level=="error"?h.error(`[Server] ${e.params.data}`):e.params.level=="warning"?h.warn(`[Server] ${e.params.data}`):e.params.level=="info"?h.info(`[Server] ${e.params.data}`):e.params.level=="debug"?h.debug(`[Server] ${e.params.data}`):h.log(`[Server] ${e.params.data}`)}),t.setNotificationHandler(de,e=>{h.debug("Tool list changed",e),this.fetchTools()}),h.debug("Fetching tools from MCP server..."),await this.fetchTools(),t}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let t=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let i of n.tools||[])t.push(i);if(!n?.tools?.length||!e)break}let s=[];for(let n of t){let i=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:o=>this.performToolCall(n.name,o),disabled:i})}h.debug(`Fetched ${t.length} tools from MCP server.`),this.tools=t,this.iwActions=s}async search(t){if(t==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),s=await this.performSearchCall(t);return e=e.concat(s),this.lastSearchQuery=t,this.lastSearchResults=e,h.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(t){let e=[];if(!this.config.searchToolName)return e;let s=this.tools.find(i=>i.name==this.config.searchToolName);if(!s)return h.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(s.inputSchema.required?.length==1){let i=s.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let i=Object.keys(s.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let i=0;i<n.length;i++){let o=n[i];e.push({id:this.config.id+":"+this.config.searchToolName+":"+i,name:`Search result ${i+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(t,e){await this.connect(),h.debug(`Performing tool call for ${t} with params:`,e),this.stats.toolsCalled+=1;let s=await this.client.callTool({name:t,arguments:e});if(s.isError){let n=s.content?.[0]?.text||"Unknown error";throw h.error(`Error calling tool ${t}: ${n}`),new Error(`Error calling tool ${t}: ${n}`)}if(Array.isArray(s.content)&&s.content.length==1&&s.content[0].type=="text")try{return JSON.parse(s.content[0].text)}catch{}return s.content||[]}};import{v4 as me}from"uuid";var he=new g("Statistics"),_=[];async function b(u,t){let e={...t,event_id:me(),event_date:new Date().toISOString(),sdk_version:y.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(_.push(e),!u||(await new Promise(n=>setTimeout(n,5e3)),_.length===0))return;let s=_.slice();_.length=0;try{let n=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){he.warn("Failed to submit analytics event:",n),_.push(...s);return}}var S=new g("KnowledgeBase"),j=1,$=class u{constructor(t){this._sources=[{id:"core.internal",query:async()=>Q(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${j++}`),this._sources.push({id:s,query:e}),s}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return p().knowledgeBaseSources&&(t=t.concat(p().knowledgeBaseSources)),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){let e=Date.now();S.debug(`Searching knowledge base for: ${t}`);let s=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});s.query=t,s.entries=[],s.sources=[],typeof document<"u"&&document.dispatchEvent(s),this._windowSources=s.sources;let i=(await Promise.all(this.sources.map(async c=>{try{let l=Date.now(),m=await c.query(t);return S.debug(`Source '${c.id}' took ${Date.now()-l}ms`),m||[]}catch(l){return S.warn(`Knowledge source '${c.id}' failed:`,l),[]}}))).flat();i=i.concat(s.entries),i=i.concat(this.manualEntries),p().knowledgeBase&&(i=i.concat(p().knowledgeBase)),i=i.filter(c=>c&&!c.disabled);for(let c=0;c<i.length;c++){let l=i[c];l.id=l.id||`temp.${c}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!l.action&&l.type=="tour"&&(l.action=m=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=m=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new ge({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let r=o.search(t).map(c=>i.find(l=>l.id==c.id));for(let c of i)c.isContext&&(r.find(l=>l.id===c.id)||r.push(c));return this.lastResults=r,b(this.ai,{event_type:"kb_search",value:r.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),S.debug("Found results:",r),r}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${j++}`),S.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],i=!0,o=async(r,c)=>{S.debug(`Calling remote knowledge base action: ${r.id}`);let l={type:"action",userID:this.ai.userID,actionID:r.id,parameters:c},m=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!m.ok)throw new Error(`HTTP Error ${m.status} ${m.statusText}`);let d=await m.json();return a(d.updateItems||[]),d.response},a=r=>{for(let c of r){if(!c.id){S.warn("KB item skipped since it has no ID.",c);continue}let l=s.find(m=>m.id==c.id);if(l){l.name=c.name||l.name||"",l.content=c.content||l.content||"",l.disabled=c.disabled??l.disabled,l.isContext=c.isContext??l.isContext,l.parameters=c.parameters||l.parameters||[],l.tags=c.tags||l.tags,l.type=c.type||l.type;continue}s.push({...c,action:m=>o(c,m)})}};this.registerSource(e,async r=>{if(i&&n.includes(r))return s;let c={type:"search",userID:this.ai?.userID||"",query:r},l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let m=await l.json();return i=!m.noCache,n.includes(r)||n.push(r),a(m.items),s})}clone(){let t=new u(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}registerMCPSource(t){t.id||(t.id=`external.${j++}`);let e=new W(t);return this.registerSource(t.id,s=>e.search(s)),e}};import{v4 as F}from"uuid";var K=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
15
15
|
|
|
16
16
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(e.toLowerCase().includes("true"))return!0;if(e.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+e)}async choose(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
17
17
|
|
|
@@ -28,10 +28,10 @@ Objects should have the following keys:
|
|
|
28
28
|
${t.extractions.map(n=>`- ${n.name} (${n.type}): ${n.description||"No description provided."}`).join(`
|
|
29
29
|
`)}
|
|
30
30
|
`,s=await this.instruct({...t,instruction:e});if(s=s.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),t.allowMultiple){let n=s.split(`
|
|
31
|
-
`).map(o=>o.trim()).filter(o=>!!o.trim()),i=[];for(let o of n)try{i.push(JSON.parse(o))}catch(a){console.error("Failed to parse line as JSON:",o,a.message)}return i}else return[JSON.parse(s.trim())]}async generateMarkdown(t){return this.instruct({...t,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(t){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>t.instruction,t.callback&&e.addEventListener("output",s=>{t.callback(s.detail.message)}),t.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof t.data=="string"?t.data:JSON.stringify(t.data))||""}};var f=new g("Main"),te=new Set,x=class x extends EventTarget{constructor(){super(...arguments);this.conversationID=F();this.knowledgeBase=new $(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new K(this);this.userID=z();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this._lastTrackedTokens=0}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:x.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){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{f.debug("Loading configuration...");let s=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!s.ok)throw new Error(`Failed to load configuration: ${s.status} ${s.statusText}`);try{this.config=await s.json(),f.debug("Config loaded successfully:",this.config),this.config&&f.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(n){f.error("Failed to parse JSON response:",n);try{let i=await s.clone().text();f.error("Raw response that failed parsing:",i)}catch{f.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${n}`)}})(),(async()=>{try{let s=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!s.ok)throw new Error(`Failed to load VAD model: ${s.status} ${s.statusText}`);this.vadModel=await s.blob()}catch(s){f.warn(`Failed to load VAD model, some features will be unavailable. ${s.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let s of this.config.knowledge||[])s.url&&s.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:s.id,searchToolName:s.mcpSearchToolName,baseURL:s.url}):s.url&&this.knowledgeBase.registerSourceFromURL(s.url);for(let s of this.config.knowledge||[])s.entries?.length&&this.knowledgeBase.registerSource(s.id,()=>s.entries||[]);if(this.config.mcpServers)for(let s of this.config.mcpServers)this.knowledgeBase.registerMCPSource(s);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this.config}catch(s){throw f.warn("Failed to load:",s),this.error=s,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:s}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:s}})),s}}setModel(e){let s=this.models.find(i=>i.id==e);if(!s)throw new Error(`Model with ID "${e}" not found.`);let n={...s.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(i,o)=>{let a=this.knowledgeBase.getCachedEntry(i);this.onAIToolStart?.(a?.id||i,o)}};s.config.providerID==="anthropic"?this.currentModel=new N(n):this.currentModel=new D(n),this.currentModel.id=s.id,this.currentModel.metadata=s}async getContextPrefix(){let e=p().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=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,content:
|
|
32
|
-
You have access to a database of knowledge base items. These include "info" type items which provide information and "tour" type items which contain instructions you should follow (only do one item at a time).${
|
|
31
|
+
`).map(o=>o.trim()).filter(o=>!!o.trim()),i=[];for(let o of n)try{i.push(JSON.parse(o))}catch(a){console.error("Failed to parse line as JSON:",o,a.message)}return i}else return[JSON.parse(s.trim())]}async generateMarkdown(t){return this.instruct({...t,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(t){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>t.instruction,t.callback&&e.addEventListener("output",s=>{t.callback(s.detail.message)}),t.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof t.data=="string"?t.data:JSON.stringify(t.data))||""}};var f=new g("Main"),te=new Set,x=class x extends EventTarget{constructor(){super(...arguments);this.conversationID=F();this.knowledgeBase=new $(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new K(this);this.userID=z();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this._lastTrackedTokens=0}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:x.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){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{f.debug("Loading configuration...");let s=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!s.ok)throw new Error(`Failed to load configuration: ${s.status} ${s.statusText}`);try{this.config=await s.json(),f.debug("Config loaded successfully:",this.config),this.config&&f.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(n){f.error("Failed to parse JSON response:",n);try{let i=await s.clone().text();f.error("Raw response that failed parsing:",i)}catch{f.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${n}`)}})(),(async()=>{try{let s=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!s.ok)throw new Error(`Failed to load VAD model: ${s.status} ${s.statusText}`);this.vadModel=await s.blob()}catch(s){f.warn(`Failed to load VAD model, some features will be unavailable. ${s.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let s of this.config.knowledge||[])s.url&&s.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:s.id,searchToolName:s.mcpSearchToolName,baseURL:s.url}):s.url&&this.knowledgeBase.registerSourceFromURL(s.url);for(let s of this.config.knowledge||[])s.entries?.length&&this.knowledgeBase.registerSource(s.id,()=>s.entries||[]);if(this.config.mcpServers)for(let s of this.config.mcpServers)this.knowledgeBase.registerMCPSource(s);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this.config}catch(s){throw f.warn("Failed to load:",s),this.error=s,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:s}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:s}})),s}}setModel(e){let s=this.models.find(i=>i.id==e);if(!s)throw new Error(`Model with ID "${e}" not found.`);let n={...s.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(i,o)=>{let a=this.knowledgeBase.getCachedEntry(i);this.onAIToolStart?.(a?.id||i,o)}};s.config.providerID==="anthropic"?this.currentModel=new N(n):this.currentModel=new D(n),this.currentModel.id=s.id,this.currentModel.metadata=s}async getContextPrefix(){let e=p().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 s=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,content:s}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,content:"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_description",sortOrder:100,cannotRemove:!0,content:`# Knowledge Database
|
|
32
|
+
You have access to a database of knowledge base items. These include "info" type items which provide information and "tour" type items which contain instructions you should follow (only do one item at a time).${e.length==0?`
|
|
33
33
|
|
|
34
|
-
(no items found)`:""}`});for(let i of
|
|
34
|
+
(no items found)`:""}`});for(let i of e)if(i.type=="info"||i.type=="tour"||i.type=="input-event"){let o=G(typeof i.content=="function"?i.content():i.content);this.currentModel.contextGroup.add({id:i.id,customData:i,cannotRemove:i.isContext,sortOrder:101,disabled:i.disabled,content:`## ${i.type}: ${i.name}
|
|
35
35
|
${o}`})}else if(i.type=="action"){let o={name:i._functionID,description:G(typeof i.content=="function"?i.content():i.content),params:V(i.parameters||[{name:"value",type:"string",description:"Input"}]),removeFromMessageHistory:!!i.removeFromMessageHistory,callback:a=>this.toolRunKBAction(i,a),kb:i};this.currentModel.registerTool(o)}else continue;let n=this.currentModel.contextGroup.getAllAsString();this._lastSystemMsg!=n&&(this._lastSystemMsg=n,this.submitAnalyticsEvent({type:"system-msg",txt:n}))}processIncomingMessage(e,s){if(!s){let n=this.currentModel?.stats?.tokensUsed||0,i=n-(this._lastTrackedTokens||0);this._lastTrackedTokens=n,b(this,{event_type:"message_receive",value:i,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:n}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:s,message:e}})),this.onAIMessage?.(e,!!s)}async sendMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)return f.warn("Cannot send message while another message is being processed."),null;this.isProcessing=!0;try{this._messageStartTime=Date.now(),te.has(this.conversationID)||(te.add(this.conversationID),b(this,{event_type:"session_start"})),this._lastTrackedTokens=this.currentModel?.stats?.tokensUsed||0,b(this,{event_type:"message_send",value_str:"",event_properties:{message_length:e.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),this.submitAnalyticsEvent({type:"message",role:"user",message:e,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()});let s=await this.currentModel.sendMessage(e);return s&&typeof s=="string"&&s.trim().length>0&&this.submitAnalyticsEvent({type:"message",role:"assistant",message:s,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()}),s}finally{this.isProcessing=!1}}async toolRunKBAction(e,s){let n=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:s,ai:this}}));let i=await e.action(s,this),o=Date.now()-n;return b(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:s,execution_time_ms:o,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:s,ai:this,result:i}})),i}catch(i){let o=Date.now()-n;throw b(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:s,execution_time_ms:o,success:!1,error_message:i.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:s,ai:this,error:i}})),i}}submitAnalyticsEvent(e){p().analytics===!1||this.config?.analytics===!1||fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(s=>{process.env.NODE_ENV==="development"?f.warn(`Failed to submit analytics event to ${this.hubAPI+"/analytics/post"}:`,s):f.debug("Failed to submit analytics event:",s)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=F(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(e)}exportState(){return{type:"intelliweave/state/v1",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll().map(e=>e.customData)}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v1")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let s of e.messages)this.currentModel.messageGroup.add({id:F(),content:JSON.stringify(s),customData:s})}clone(){let e=new x;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.knowledgeBase=this.knowledgeBase.clone(),e}};x.version=y.version,x.builtInActionsVersion="1.0.0",f.debug("\u{1F6A8}\u{1F6A8}\u{1F6A8} NEW SDK BUILD LOADED - Built-in Actions Version:",x.builtInActionsVersion);var R=x;var L=new g("Stream"),se=class extends R{constructor(){super(...arguments);this.pendingEvents=[];this._isProcessingEvents=!1}async getContextPrefix(){let e=`You will receive an event stream, a list of JSON objects, one on each line. Respond with tool calls only and no text output.
|
|
36
36
|
|
|
37
37
|
`;return e+=await super.getContextPrefix(),e}postEvent(e){if(!e.eventName)throw new Error("Missing event name");if(e.direction||(e.direction="input"),e.direction!="input")throw new Error('Invalid event direction, must be "input".');e.timestamp||(e.timestamp=Date.now()),e.timestampDate=new Date(e.timestamp).toString(),L.log("Event in",JSON.stringify(e)),this.pendingEvents.push(e),this.processEvents()}async toolRunKBAction(e,s){if(e.type!="output-event")return await super.toolRunKBAction(e,s);this.emitEvent({...s,eventName:e.id,timestamp:Date.now(),timestampDate:new Date().toString(),direction:"output"})}emitEvent(e){L.log("Event out",JSON.stringify(e)),this.dispatchEvent(new CustomEvent("event",{detail:{ai:this,event:e}}))}async processEvents(){if(!this._isProcessingEvents){this._isProcessingEvents=!0;try{let e=this.pendingEvents.shift();if(!e)return;let s=this.knowledgeBase.getCachedEntry(e.eventName);s&&(e.assistantHint=typeof s.content=="function"?s.content():s.content);let n=JSON.stringify(e),i=await this.sendMessage(n)||"";if(!i.trim())return;this.emitEvent({eventName:"text",text:i,timestamp:Date.now(),timestampDate:new Date().toString(),direction:"output"})}catch(e){L.error("Error processing events:",e),this.emitEvent({eventName:"error",timestamp:Date.now(),timestampDate:new Date().toString(),errorMessage:e.message,direction:"output"})}finally{this._isProcessingEvents=!1,this.pendingEvents.length>0&&this.processEvents()}}}};export{N as AnthropicChat,X as BufferedWebSocket,I as ChatBase,D as ChatGPT,Y as FixedBufferStream,R as IntelliWeave,se as IntelliWeaveStream,$ as KnowledgeBase,g as Logging,W as MCPKnowledgeClient,H as ONNXModel,Z as Resampler,A as TokenWindow,U as TokenWindowGroup,Se as audioToWav,V as convertParamsToJSONSchema,Te as floatTo16BitPCM,_e as floatTo64BitPCM,z as getDefaultUserID,Ee as int16ToFloat32BitPCM,p as intelliweaveConfig,C as intelliweaveGlobalThis,q as sseEvents,G as trimWhitespaceInText};
|