@intelliweave/embedded 1.8.63 → 1.9.65-beta.0
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 +270 -286
- package/dist/component/component.js +21 -19
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.d.ts +728 -690
- package/dist/node/node.js +16 -14
- package/dist/react/react.d.ts +675 -693
- package/dist/react/react.js +21 -19
- package/dist/script-tag/script-tag.js +65 -42
- package/dist/webpack/index.d.ts +389 -351
- package/dist/webpack/index.js +23 -21
- package/package.json +4 -2
package/dist/node/node.js
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
import{v4 as
|
|
2
|
-
`);for(;t.length>0&&t[0].trim()=="";)t.shift();for(;t.length>0&&t[t.length-1].trim()=="";)t.pop();let e=1/0;for(let s of t){let
|
|
3
|
-
`)}var
|
|
1
|
+
import{v4 as L}from"uuid";function R(u){let t=(u||"").split(`
|
|
2
|
+
`);for(;t.length>0&&t[0].trim()=="";)t.shift();for(;t.length>0&&t[t.length-1].trim()=="";)t.pop();let e=1/0;for(let s of t){let n=s.match(/^\s*/)?.[0].length||0;e=Math.min(e,n)}return e>0&&e<1/0&&(t=t.map(s=>s.substring(e))),t.join(`
|
|
3
|
+
`)}var ne={};function C(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:ne}function p(){return C().intelliweave=C().intelliweave||C().webWeaver||{},C().intelliweave}async function*z(u){let t="",e=function*(){for(;;){let i=t.indexOf(`
|
|
4
4
|
|
|
5
|
-
`);if(
|
|
6
|
-
`);for(let
|
|
7
|
-
`+
|
|
5
|
+
`);if(i==-1)break;let r=t.slice(0,i);t=t.slice(i+2);let c={},o=r.split(`
|
|
6
|
+
`);for(let l of o){i=l.indexOf(": ");let a=l.slice(0,i),m=l.slice(i+2);i==-1&&(a=l,m=""),a&&(c[a]!==void 0?c[a]+=`
|
|
7
|
+
`+m:c[a]=m)}yield c}},s=new TextDecoder,n=u.getReader();for(;;){let{done:i,value:r}=await n.read();if(i)break;t+=s.decode(r,{stream:!0}),yield*e()}t+=s.decode()+`
|
|
8
8
|
|
|
9
|
-
`,yield*e()}function
|
|
10
|
-
`;this.itemPadding=0;this.sortFunction=(t,e)=>t.sortOrder!==e.sortOrder?t.sortOrder-e.sortOrder:t.dateAdded!==e.dateAdded?t.dateAdded-e.dateAdded:t.content.localeCompare(e.content)}setItemPadding(t){return this.itemPadding=t,this.recalculateTokens(),this}sortBy(t){return this.sortFunction=t,this.items.sort(this.sortFunction),this}setSeparator(t){return this.separator==t?this:(this.separator=t,this.recalculateTokens(),this)}setWeight(t){return this.weight=t,this}recalculateTokens(){this.tokenCount=this.items.reduce((t,e)=>(e.tokenCount=
|
|
9
|
+
`,yield*e()}function q(){if(p().userID)return p().userID||"";if(typeof localStorage<"u"){let u=localStorage.getItem("intelliweave.uid")||"";return u||(u=L(),localStorage.setItem("intelliweave.uid",u),u)}else return L()}function H(u){let t=u;if(t?.type=="object"&&t.properties)return u;let e={type:"object",properties:{},required:[]};if(u&&Array.isArray(u)){let s=u;for(let n of s)e.properties[n.name]={type:n.type||"string",description:n.description||""}}return e}var E=class E{constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return E.debug?!0:typeof window<"u"&&p().debug}log(...t){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...t)}debug(...t){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...t)}info(...t){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...t)}warn(...t){console.warn(`[IntelliWeave > ${this.module}]`,...t)}error(...t){console.error(`[IntelliWeave > ${this.module}]`,...t)}timer(t,...e){let s=Date.now();return this.debug(`[${t} 0ms] Started`,...e),(...n)=>this.debug(`[${t} ${Math.floor(Date.now()-s)}ms]`,...n)}};E.debug=!1;var g=E;var S=new g("ONNXModel"),V=class u{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,S.debug(`Model input parameters: ${t.inputNames.join(", ")}`),S.debug(`Model output parameters: ${t.outputNames.join(", ")}`)}static isSupported(){return!!u.lib}static async load(t){if(!u.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(S.debug("Loading ONNX runtime"),this.onnx=await u.lib()),S.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new u(e)}makeTensor(t,e,s=0){let n=1;for(let r of e)n*=r;let i;if(t=="float32")i=new u.onnx.Tensor(new Float32Array(n),e);else if(t=="int8")i=new u.onnx.Tensor(new Int8Array(n),e);else if(t=="int16")i=new u.onnx.Tensor(new Int16Array(n),e);else if(t=="int32")i=new u.onnx.Tensor(new Int32Array(n),e);else if(t=="int64")i=new u.onnx.Tensor(new BigInt64Array(n),e);else if(t=="uint8")i=new u.onnx.Tensor(new Uint8Array(n),e);else if(t=="uint16")i=new u.onnx.Tensor(new Uint16Array(n),e);else if(t=="uint32")i=new u.onnx.Tensor(new Uint32Array(n),e);else if(t=="uint64")i=new u.onnx.Tensor(new BigUint64Array(n),e);else throw new Error(`Invalid type: ${t}`);return s!==0&&(t=="int64"||t=="uint64")?i.data.fill(BigInt(s)):s!==0&&i.data.fill(s),i}registerConstant(t,e){if(!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);return this.constantTensors[t]=e,e}makeConstant(t,e,s,n=0){return this.registerConstant(t,this.makeTensor(e,s,n))}registerState(t,e,s){if(e||(e=t),!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[t]={outputName:e,tensor:s},s}makeState(t,e,s,n,i=0){return this.registerState(t,e,this.makeTensor(s,n,i))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return S.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)t[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)t[e]=this.constantTensors[e];try{let e=await this.session.run(t);for(let s in this.stateTensors){let n=e[this.stateTensors[s].outputName];this.stateTensors[s].tensor=n}return e}finally{this._runActive=!1}}resetState(){S.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};function xe(u,t){let e=t.reduce((o,l)=>o+l.byteLength,0),s=new DataView(new ArrayBuffer(44));s.setUint8(0,82),s.setUint8(1,73),s.setUint8(2,70),s.setUint8(3,70),s.setUint32(4,44+e,!0),s.setUint8(8,87),s.setUint8(9,65),s.setUint8(10,86),s.setUint8(11,69);let n=1,i=32,r=n*i/8,c=u*r;return s.setUint8(12,102),s.setUint8(13,109),s.setUint8(14,116),s.setUint8(15,32),s.setUint32(16,16,!0),s.setUint16(20,3,!0),s.setUint16(22,n,!0),s.setUint32(24,u,!0),s.setUint32(28,c,!0),s.setUint16(32,r,!0),s.setUint16(34,i,!0),s.setUint8(36,100),s.setUint8(37,97),s.setUint8(38,116),s.setUint8(39,97),s.setUint32(40,e,!0),new File([s,...t],"audio.wav",{type:"audio/wav"})}var X=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var Y=class{constructor(t,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!t)throw new Error(`Invalid array class: ${t}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=t,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((t,e)=>t+e.length,0)}feed(t){this.partialBuffers.push(t)}get canDrain(){return this.partialBuffers.reduce((e,s)=>e+s.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let t=this.ArrayClass,e=new t(this.outputBufferSize),s=0;for(;s!=e.length;){if(s>e.length)throw new Error(`Buffer overflow: ${s} > ${e.length}`);let n=e.length-s,i=this.partialBuffers[0],r=i.length-this.partialBufferOffset;r<n?(e.set(i.subarray(this.partialBufferOffset),s),s+=r,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(i.subarray(this.partialBufferOffset,this.partialBufferOffset+n),s),s+=n,this.partialBufferOffset+=n)}return e}pad(){let t=this.queuedSize%this.outputBufferSize;if(t==0)return;let e=this.ArrayClass,s=new e(t);this.feed(s)}};var Z=class{constructor(t,e,s,n){if(!t||!e||!s)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=t,this.toSampleRate=e,this.channels=s||0,this.inputBufferSize=n,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=t=>t,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(t){try{return this.outputBuffer.subarray(0,t)}catch{try{return this.outputBuffer.length=t,this.outputBuffer}catch{return this.outputBuffer.slice(0,t)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=t=>{let e=t.length,s=this.channels,n,i,r,c,o,l,a,m,d;if(e%s!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(n=this.outputBufferSize,i=this.ratioWeight,r=this.lastWeight,c=0,o=0,l=0,a=0,m=this.outputBuffer;r<1;r+=i)for(o=r%1,c=1-o,this.lastWeight=r%1,d=0;d<this.channels;++d)m[a++]=this.lastOutput[d]*c+t[d]*o;for(r-=1,e-=s,l=Math.floor(r)*s;a<n&&l<e;){for(o=r%1,c=1-o,d=0;d<this.channels;++d)m[a++]=t[l+(d>0?d:0)]*c+t[l+(s+d)]*o;r+=i,l=Math.floor(r)*s}for(d=0;d<s;++d)this.lastOutput[d]=t[l++];return this.bufferSlice(a)}}multiTap(){this.resampler=t=>{let e=t.length,s,n,i=this.channels,r,c,o,l,a,m,d,v,_;if(e%i!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,n=[],r=this.ratioWeight,c=0,l=0,a=0,m=!this.tailExists,this.tailExists=!1,d=this.outputBuffer,v=0,_=0,o=0;o<i;++o)n[o]=0;do{if(m)for(c=r,o=0;o<i;++o)n[o]=0;else{for(c=this.lastWeight,o=0;o<i;++o)n[o]=this.lastOutput[o];m=!0}for(;c>0&&l<e;)if(a=1+l-_,c>=a){for(o=0;o<i;++o)n[o]+=t[l++]*a;_=l,c-=a}else{for(o=0;o<i;++o)n[o]+=t[l+(o>0?o:0)]*c;_+=c,c=0;break}if(c===0)for(o=0;o<i;++o)d[v++]=n[o]/r;else{for(this.lastWeight=c,o=0;o<i;++o)this.lastOutput[o]=n[o];this.tailExists=!0;break}}while(l<e&&v<s);return this.bufferSlice(v)}}resample(t){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(t)}};function Te(u){let t=u.length,e=new Int16Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,u[t]));e[t]=s<0?s*32768:s*32767}return e}function _e(u){let t=u.length,e=new BigInt64Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,u[t]));e[t]=BigInt(Math.floor(s<0?s*32768:s*32767))*0x100000000000n}return e}function Ce(u){let t=u.length,e=new Float32Array(t);for(;t--;){let s=u[t];e[t]=s>=32768?-(65536-s)/32768:s/32767}return e}import{countTokens as re}from"gpt-tokenizer";import{countTokens as B}from"gpt-tokenizer";import{v4 as ie}from"uuid";var M=class{constructor(){this.size=4096;this.groups=[]}createGroup(t){let e=new U;return e.id=t,this.groups.push(e),e}group(t){return this.groups.find(e=>e.id===t)}countTokens(){return this.groups.reduce((t,e)=>t+e.tokenCount,0)}removeOverflow(){let t=this.countTokens(),e=this.groups.reduce((s,n)=>s+n.weight,0);for(;t>this.size;){let s=this.groups.slice().sort((i,r)=>{let c=Math.floor(i.weight/e*this.size),o=Math.floor(r.weight/e*this.size),l=i.tokenCount-c;return r.tokenCount-o-l}),n=this.removeOneItem(s);if(!n)throw new Error("Too many items in the token window that cannot be removed.");t-=n.tokenCount}}removeOneItem(t){for(let e of t){let s=e.items.findIndex(i=>!i.cannotRemove);if(s===-1)continue;let n=e.items[s];return e.items.splice(s,1),e.tokenCount-=n.tokenCount,n}return null}},U=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
10
|
+
`;this.itemPadding=0;this.sortFunction=(t,e)=>t.sortOrder!==e.sortOrder?t.sortOrder-e.sortOrder:t.dateAdded!==e.dateAdded?t.dateAdded-e.dateAdded:t.content.localeCompare(e.content)}setItemPadding(t){return this.itemPadding=t,this.recalculateTokens(),this}sortBy(t){return this.sortFunction=t,this.items.sort(this.sortFunction),this}setSeparator(t){return this.separator==t?this:(this.separator=t,this.recalculateTokens(),this)}setWeight(t){return this.weight=t,this}recalculateTokens(){this.tokenCount=this.items.reduce((t,e)=>(e.tokenCount=B(e.content)+B(this.separator)+this.itemPadding,t+e.tokenCount),0)}add(t){typeof t=="string"&&(t={content:t});let e=t;e.id===void 0&&(e.id=ie());let s=this.items.find(n=>n.id===e.id);return s?(this.tokenCount-=s.tokenCount,Object.assign(s,e),e=s):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.tokenCount=e.disabled?0:B(t.content)+B(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}getAllAsString(){return this.getAll().map(t=>t.content).join(this.separator)}getAll(){return this.items.filter(t=>!t.disabled)}empty(){this.items=[],this.tokenCount=0}};var k=class{constructor(t){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let t=new M;return t.createGroup("context").setSeparator(`
|
|
11
11
|
|
|
12
|
-
`),t.createGroup("actions").setItemPadding(25),t.createGroup("messages").setItemPadding(10),t})();this.config={...this.config,...t},this.tokenWindow.size=this.config.maxTokens||4096}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+x++,content:JSON.stringify(e),customData:e}),await this.processMessages();let i=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return i?.role=="assistant"&&i.content||""}addAssistantMessage(t){let e={role:"assistant",content:t};this.messageGroup.add({id:"msg-"+x++,content:JSON.stringify(e),customData:e})}addUserMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+x++,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(this.tokenWindow.removeOverflow();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}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 r=this.messageGroup.items.length-1;r>=0;r--){let o=this.messageGroup.items[r].customData;if(o.role=="assistant"&&o.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(o.role=="user")break}w.debugEnabled&&w.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(r=>r.customData),messages:this.messageGroup.items.map(r=>r.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(r=>r.customData)]};for(let r of this.toolGroup.getAll()){let o=r.customData;o.description&&o.description.length>1024&&w.warn(`Tool description for "${o.name}" is too long, it will be truncated.`);let a={type:"function",function:{name:o.name,description:(o.description||"").substring(0,1024),parameters:o.params}};s.tools.push(a)}s.user||delete s.user,s.tools.length||delete s.tools;let i={};if(i["Content-Type"]="application/json",this.config.apiKey&&(i.Authorization=`Bearer ${this.config.apiKey}`),t)return s;let n=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(s)});if(!n.ok){let r=`${n.status} ${n.statusText}`;try{let a=await n.json();r=a.errorText||a.error?.message||a.error||r}catch{}let o=new Error(r);throw o.code=n.status,o}let l=null,u=null;if(this.config.stream){for await(let o of j(n.body)){if(o.data=="[DONE]")break;if(!o.data)continue;let a=JSON.parse(o.data);if(u){for(let d in a.choices[0].delta)if(typeof a.choices[0].delta[d]=="string"){if(d=="role"&&u[d]==a.choices[0].delta[d])continue;u[d]=(u[d]||"")+a.choices[0].delta[d]}for(let d of a.choices[0].delta.tool_calls||[]){if(u.tool_calls||(u.tool_calls=[]),!u.tool_calls[d.index]){u.tool_calls[d.index]=d;continue}let h=u.tool_calls[d.index];h.function=h.function||{},h.function.name=(h.function.name||"")+(d.function?.name||""),h.function.arguments=(h.function.arguments||"")+(d.function?.arguments||"")}}else u={chunkID:a.id,...a.choices[0].delta};u?.content&&!u.content.startsWith("{")&&this.config.onAIMessage?.(u.content,!0)}let r=te(JSON.stringify(s)+JSON.stringify(u)||"");this.stats.tokensUsed+=r,w.debug(`Estimated ${r} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else l=await n.json(),this.stats.tokensUsed+=l.usage?.total_tokens||0,w.debug(`Used ${l.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),u=l.choices?.[0]?.message;if(u||(w.warn("No response block in API response."),u={role:"assistant",content:""}),u.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(u),this.messageGroup.add({id:"msg-"+x++,content:JSON.stringify(u),customData:u}),u.content&&this.config.onAIMessage?.(u.content,!1)}processIncomingMessage(t){}registerTool(t){this.toolGroup.add({id:t.name,cannotRemove:!t.canRemove,content:JSON.stringify(t),customData:t})}async processToolCall(t){try{let s=this.toolGroup.items.find(u=>u.id==t.function.name)?.customData;if(!s)throw new Error(`Tool "${t.function.name}" not found.`);let i=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,i);let n=await s.callback(i);typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success");let l={role:"tool",content:n,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+x++,content:JSON.stringify(l),customData:l})}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-"+x++,content:JSON.stringify(s),customData:s})}}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}};import ce from"minisearch";var H=[{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(c,t)=>{let e=await t.knowledgeBase.search(c.query),s=t;s._lastKBsearch=c.query,s._nextRequestUseKBitems=e,t.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let i=e.filter(l=>l.type!="action").map(l=>"id="+l.id).join(", ")||"(none)",n=e.filter(l=>l.type=="action").map(l=>"name="+l._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${n}.`}}];import{Client as Y}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as ne}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as ie}from"@modelcontextprotocol/sdk/client/sse.js";var y={name:"@intelliweave/embedded",version:"1.8.63",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 && IW_TESTER_API_KEY=97150cfc-5b97-413e-8da3-e86d01f70057 tsx --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:{"@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 re,ToolListChangedNotificationSchema as oe}from"@modelcontextprotocol/sdk/types.js";var m=new g("MCPKnowledgeClient"),P=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(){m.debug("Connecting to MCP client");let t=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Y({name:y.name,version:y.version}),s=new ne(new URL(this.config.baseURL));return await e.connect(s),m.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let s=new Y({name:y.name,version:y.version}),i=new ie(new URL(this.config.baseURL));return await s.connect(i),m.debug("Connected with SSE mode"),s});return await this.disconnect(),this.client=t,t.onerror=e=>{m.error(`MCP client error: ${e.message}`)},t.onclose=()=>{m.debug("MCP client connection closed"),this.client=void 0},t.setNotificationHandler(re,e=>{e.params.level=="critical"?m.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?m.error(`[Server] ${e.params.data}`):e.params.level=="error"?m.error(`[Server] ${e.params.data}`):e.params.level=="warning"?m.warn(`[Server] ${e.params.data}`):e.params.level=="info"?m.info(`[Server] ${e.params.data}`):e.params.level=="debug"?m.debug(`[Server] ${e.params.data}`):m.log(`[Server] ${e.params.data}`)}),t.setNotificationHandler(oe,e=>{m.debug("Tool list changed",e),this.fetchTools()}),m.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 i=await this.client.listTools({cursor:e});e=i.nextCursor;for(let n of i.tools||[])t.push(n);if(!i?.tools?.length||!e)break}let s=[];for(let i of t){let n=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:l=>this.performToolCall(i.name,l),disabled:n})}m.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,m.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(t){let e=[];if(!this.config.searchToolName)return e;let s=this.tools.find(n=>n.name==this.config.searchToolName);if(!s)return m.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let i;if(s.inputSchema.required?.length==1){let n=s.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[n]:t})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let n=Object.keys(s.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[n]:t})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let n=0;n<i.length;n++){let l=i[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof l=="string"?l:JSON.stringify(l)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return e}async performToolCall(t,e){await this.connect(),m.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 i=s.content?.[0]?.text||"Unknown error";throw m.error(`Error calling tool ${t}: ${i}`),new Error(`Error calling tool ${t}: ${i}`)}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 ae}from"uuid";var le=new g("Statistics"),T=[];async function v(c,t){let e={...t,event_id:ae(),event_date:new Date().toISOString(),sdk_version:y.version,conversation_id:c?.conversationID||"",api_key:c?.apiKey||"",user_id:c?.userID||""};if(T.push(e),!c||(await new Promise(i=>setTimeout(i,5e3)),T.length===0))return;let s=T.slice();T.length=0;try{let i=await fetch(c.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){le.warn("Failed to submit analytics event:",i),T.push(...s);return}}var b=new g("KnowledgeBase"),$=1,A=class c{constructor(t){this._sources=[{id:"core.internal",query:async()=>H}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${$++}`),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();b.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 n=(await Promise.all(this.sources.map(async o=>{try{let a=Date.now(),d=await o.query(t);return b.debug(`Source '${o.id}' took ${Date.now()-a}ms`),d||[]}catch(a){return b.warn(`Knowledge source '${o.id}' failed:`,a),[]}}))).flat();n=n.concat(s.entries),n=n.concat(this.manualEntries),p().knowledgeBase&&(n=n.concat(p().knowledgeBase)),n=n.filter(o=>o&&!o.disabled);for(let o=0;o<n.length;o++){let a=n[o];a.id=a.id||`temp.${o}`,a._functionID=a.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!a.action&&a.type=="tour"&&(a.action=d=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!a.action&&a.type=="info"&&(a.action=d=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let l=new ce({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});l.addAll(n);let r=l.search(t).map(o=>n.find(a=>a.id==o.id));for(let o of n)o.isContext&&(r.find(a=>a.id===o.id)||r.push(o));return this.lastResults=r,v(this.ai,{event_type:"kb_search",value:r.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),b.debug("Found results:",r),r}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${$++}`),b.debug(`Registering remote knowledge base source: ${t}`);let s=[],i=[],n=!0,l=async(r,o)=>{b.debug(`Calling remote knowledge base action: ${r.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:r.id,parameters:o},d=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let h=await d.json();return u(h.updateItems||[]),h.response},u=r=>{for(let o of r){if(!o.id){b.warn("KB item skipped since it has no ID.",o);continue}let a=s.find(d=>d.id==o.id);if(a){a.name=o.name||a.name||"",a.content=o.content||a.content||"",a.disabled=o.disabled??a.disabled,a.isContext=o.isContext??a.isContext,a.parameters=o.parameters||a.parameters||[],a.tags=o.tags||a.tags,a.type=o.type||a.type;continue}s.push({...o,action:d=>l(o,d)})}};this.registerSource(e,async r=>{if(n&&i.includes(r))return s;let o={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:r},a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let d=await a.json();return n=!d.noCache,i.includes(r)||i.push(r),u(d.items),s})}clone(){let t=new c(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}registerMCPSource(t){t.id||(t.id=`external.${$++}`);let e=new P(t);return this.registerSource(t.id,s=>e.search(s)),e}};import{v4 as O}from"uuid";var D=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
12
|
+
`),t.createGroup("actions").setItemPadding(25),t.createGroup("messages").setItemPadding(10),t})();this.config=t,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(t){throw new Error("Not implemented")}addUserMessage(t){throw new Error("Not implemented")}addAssistantMessage(t){throw new Error("Not implemented")}onBeforeIncomingMessage(t){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(t){return this.toolGroup.add({id:t.name,customData:t,cannotRemove:t.isContext,sortOrder:101,disabled:t.disabled,content:JSON.stringify(t)})}};var I=1,w=new g("ChatGPT"),A=class extends k{async sendMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+I++,content:JSON.stringify(e),customData:e}),await this.processMessages();let n=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return n?.role=="assistant"&&n.content||""}addAssistantMessage(t){let e={role:"assistant",content:t};this.messageGroup.add({id:"msg-"+I++,content:JSON.stringify(e),customData:e})}addUserMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+I++,content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(t=>t.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),w.debugEnabled&&w.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(s=>s.customData),messages:this.messageGroup.items.map(s=>s.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let s of e.tool_calls)await this.processToolCall(s);await this.processMessages()}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendRequest(t){let e={};return e["Content-Type"]="application/json",this.config.apiKey&&(e.Authorization=`Bearer ${this.config.apiKey}`),await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:e,body:JSON.stringify(t)})}async sendToAPI(t){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let c=this.messageGroup.items.length-1;c>=0;c--){let o=this.messageGroup.items[c].customData;if(o.role=="assistant"&&o.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(o.role=="user")break}w.debugEnabled&&w.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(c=>c.customData),messages:this.messageGroup.items.map(c=>c.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let s={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(c=>c.customData)]};for(let c of this.toolGroup.getAll()){let o=c.customData;o.description&&o.description.length>1024&&w.warn(`Tool description for "${o.name}" is too long, it will be truncated.`);let l={type:"function",function:{name:o.name,description:(o.description||"").substring(0,1024),parameters:o.params}};s.tools.push(l)}if(s.user||delete s.user,s.tools.length||delete s.tools,t)return s;let n=await this.sendRequest(s);if(!n.ok){let c=`${n.status} ${n.statusText}`;try{let l=await n.json();c=l.errorText||l.error?.message||l.error||c}catch{}let o=new Error(c);throw o.code=n.status,o}let i=null,r=null;if(this.config.stream){for await(let o of z(n.body)){if(o.data=="[DONE]")break;if(!o.data)continue;let l=JSON.parse(o.data);if(r){for(let a in l.choices[0].delta)if(typeof l.choices[0].delta[a]=="string"){if(a=="role"&&r[a]==l.choices[0].delta[a])continue;r[a]=(r[a]||"")+l.choices[0].delta[a]}for(let a of l.choices[0].delta.tool_calls||[]){if(r.tool_calls||(r.tool_calls=[]),!r.tool_calls[a.index]){r.tool_calls[a.index]=a;continue}let m=r.tool_calls[a.index];m.function=m.function||{},m.function.name=(m.function.name||"")+(a.function?.name||""),m.function.arguments=(m.function.arguments||"")+(a.function?.arguments||"")}}else r={chunkID:l.id,...l.choices[0].delta};r?.content&&!r.content.startsWith("{")&&this.config.onAIMessage?.(r.content,!0)}let c=re(JSON.stringify(s)+JSON.stringify(r)||"");this.stats.tokensUsed+=c,w.debug(`Estimated ${c} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else i=await n.json(),this.stats.tokensUsed+=i?.usage?.total_tokens||0,w.debug(`Used ${i?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),r=i?.choices?.[0]?.message;if(r||(w.warn("No response block in API response."),r={role:"assistant",content:""}),r.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(r),this.messageGroup.add({id:"msg-"+I++,content:JSON.stringify(r),customData:r}),r.content&&this.config.onAIMessage?.(r.content,!1)}async processToolCall(t){try{let s=this.toolGroup.items.find(c=>c.id==t.function.name)?.customData;if(!s)throw new Error(`Tool "${t.function.name}" not found.`);let n=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,n);let i=await s.callback(n);typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success");let r={role:"tool",content:i,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+I++,content:JSON.stringify(r),customData:r})}catch(e){w.warn(`Unable to process tool call for "${t?.function?.name}"`,e);let s={role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+I++,content:JSON.stringify(s),customData:s})}}};import oe from"@anthropic-ai/sdk";var D=1,P=new g("AnthropicChat"),O=class extends k{addUserMessage(t){let e={role:"user",content:t||""};this.messageGroup.add({id:"msg-"+D++,content:JSON.stringify(e),customData:e})}addAssistantMessage(t){let e={role:"assistant",content:t||""};this.messageGroup.add({id:"msg-"+D++,content:JSON.stringify(e),customData:e})}async sendMessage(t){this.addUserMessage(t);let e=new oe({apiKey:this.config.apiKey,baseURL:this.config.endpoint,dangerouslyAllowBrowser:!0}),s=!0,n="",i="";for(;s;){s=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),P.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.customData),tools:this.toolGroup.getAll().map(d=>d.customData),context:this.contextGroup.getAll().map(d=>d.content)});let r=this.toolGroup.getAll().map(d=>({name:d.customData?.name||"",description:d.customData?.description||"",input_schema:{type:"object",required:d.customData?.params.required||[],properties:d.customData?.params.properties||{}}})),c;if(this.config.stream){let d=e.messages.stream({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(v=>v.customData),tools:r,stream:!0});d.on("text",v=>{i+=v,this.config.onAIMessage?.(i,!0)}),c=await d.finalMessage()}else c=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(d=>d.customData),tools:r});P.debug("Message received",c);let o=!0;Array.isArray(c.content)&&c.content.length==0&&(o=!1);let l={role:c.role,content:c.content};o&&this.messageGroup.add({id:"msg-"+D++,content:JSON.stringify(l),customData:l});let a=[];for(let d of c.content)d.type=="thinking"?P.debug(`AI is thinking: ${d.thinking}`):d.type=="text"?n+=d.text||`
|
|
13
|
+
|
|
14
|
+
`:d.type=="tool_use"&&a.push(this.performToolCall(d));let m=await Promise.all(a);if(m.length>0){let d={role:"user",content:m};this.messageGroup.add({id:"msg-"+D++,content:JSON.stringify(d),customData:d}),s=!0}this.config.onAIMessage?.(n,!0),this.stats.tokensUsed+=c.usage.input_tokens+c.usage.output_tokens}return n=n.trim(),this.config.onAIMessage?.(n,!1),n}async performToolCall(t){try{let e=this.toolGroup.getAll().find(n=>n.customData?.name==t.name);if(!e)throw new Error(`Tool ${t.name} not found`);this.config.onAIToolStart?.(t.name,t.input);let s=await e.customData.callback(t.input);return typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),{type:"tool_result",tool_use_id:t.id,content:String(s||"")}}catch(e){return P.error(`Error performing tool call ${t.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:t.id,content:`Error performing tool call ${t.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0].customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import ge from"minisearch";var Q=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(u,t)=>{let e=await t.knowledgeBase.search(u.query),s=t;s._lastKBsearch=u.query,s._nextRequestUseKBitems=e,t.submitAnalyticsEvent({type:"kb-search",query:u.query,results:e});let n=e.filter(r=>r.type!="action").map(r=>"id="+r.id).join(", ")||"(none)",i=e.filter(r=>r.type=="action").map(r=>"name="+r._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${i}.`}}];import{Client as ee}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as le}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as ce}from"@modelcontextprotocol/sdk/client/sse.js";var y={name:"@intelliweave/embedded",version:"1.9.65-beta.0",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.12.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as ue,ToolListChangedNotificationSchema as de}from"@modelcontextprotocol/sdk/types.js";var h=new g("MCPKnowledgeClient"),N=class{constructor(t){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=t}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){h.debug("Connecting to MCP client");let t=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new ee({name:y.name,version:y.version}),s=new le(new URL(this.config.baseURL));return await e.connect(s),h.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let s=new ee({name:y.name,version:y.version}),n=new ce(new URL(this.config.baseURL));return await s.connect(n),h.debug("Connected with SSE mode"),s});return await this.disconnect(),this.client=t,t.onerror=e=>{h.error(`MCP client error: ${e.message}`)},t.onclose=()=>{h.debug("MCP client connection closed"),this.client=void 0},t.setNotificationHandler(ue,e=>{e.params.level=="critical"?h.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?h.error(`[Server] ${e.params.data}`):e.params.level=="error"?h.error(`[Server] ${e.params.data}`):e.params.level=="warning"?h.warn(`[Server] ${e.params.data}`):e.params.level=="info"?h.info(`[Server] ${e.params.data}`):e.params.level=="debug"?h.debug(`[Server] ${e.params.data}`):h.log(`[Server] ${e.params.data}`)}),t.setNotificationHandler(de,e=>{h.debug("Tool list changed",e),this.fetchTools()}),h.debug("Fetching tools from MCP server..."),await this.fetchTools(),t}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let t=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let i of n.tools||[])t.push(i);if(!n?.tools?.length||!e)break}let s=[];for(let n of t){let i=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:r=>this.performToolCall(n.name,r),disabled:i})}h.debug(`Fetched ${t.length} tools from MCP server.`),this.tools=t,this.iwActions=s}async search(t){if(t==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),s=await this.performSearchCall(t);return e=e.concat(s),this.lastSearchQuery=t,this.lastSearchResults=e,h.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(t){let e=[];if(!this.config.searchToolName)return e;let s=this.tools.find(i=>i.name==this.config.searchToolName);if(!s)return h.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(s.inputSchema.required?.length==1){let i=s.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let i=Object.keys(s.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let i=0;i<n.length;i++){let r=n[i];e.push({id:this.config.id+":"+this.config.searchToolName+":"+i,name:`Search result ${i+1} in ${this.config.searchToolName}`,type:"info",content:typeof r=="string"?r:JSON.stringify(r)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(t,e){await this.connect(),h.debug(`Performing tool call for ${t} with params:`,e),this.stats.toolsCalled+=1;let s=await this.client.callTool({name:t,arguments:e});if(s.isError){let n=s.content?.[0]?.text||"Unknown error";throw h.error(`Error calling tool ${t}: ${n}`),new Error(`Error calling tool ${t}: ${n}`)}if(Array.isArray(s.content)&&s.content.length==1&&s.content[0].type=="text")try{return JSON.parse(s.content[0].text)}catch{}return s.content||[]}};import{v4 as me}from"uuid";var he=new g("Statistics"),T=[];async function b(u,t){let e={...t,event_id:me(),event_date:new Date().toISOString(),sdk_version:y.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(T.push(e),!u||(await new Promise(n=>setTimeout(n,5e3)),T.length===0))return;let s=T.slice();T.length=0;try{let n=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){he.warn("Failed to submit analytics event:",n),T.push(...s);return}}var x=new g("KnowledgeBase"),F=1,W=class u{constructor(t){this._sources=[{id:"core.internal",query:async()=>Q}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${F++}`),this._sources.push({id:s,query:e}),s}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return p().knowledgeBaseSources&&(t=t.concat(p().knowledgeBaseSources)),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){let e=Date.now();x.debug(`Searching knowledge base for: ${t}`);let s=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});s.query=t,s.entries=[],s.sources=[],typeof document<"u"&&document.dispatchEvent(s),this._windowSources=s.sources;let i=(await Promise.all(this.sources.map(async l=>{try{let a=Date.now(),m=await l.query(t);return x.debug(`Source '${l.id}' took ${Date.now()-a}ms`),m||[]}catch(a){return x.warn(`Knowledge source '${l.id}' failed:`,a),[]}}))).flat();i=i.concat(s.entries),i=i.concat(this.manualEntries),p().knowledgeBase&&(i=i.concat(p().knowledgeBase)),i=i.filter(l=>l&&!l.disabled);for(let l=0;l<i.length;l++){let a=i[l];a.id=a.id||`temp.${l}`,a._functionID=a.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!a.action&&a.type=="tour"&&(a.action=m=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!a.action&&a.type=="info"&&(a.action=m=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let r=new ge({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});r.addAll(i);let o=r.search(t).map(l=>i.find(a=>a.id==l.id));for(let l of i)l.isContext&&(o.find(a=>a.id===l.id)||o.push(l));return this.lastResults=o,b(this.ai,{event_type:"kb_search",value:o.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),x.debug("Found results:",o),o}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${F++}`),x.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],i=!0,r=async(o,l)=>{x.debug(`Calling remote knowledge base action: ${o.id}`);let a={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:o.id,parameters:l},m=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!m.ok)throw new Error(`HTTP Error ${m.status} ${m.statusText}`);let d=await m.json();return c(d.updateItems||[]),d.response},c=o=>{for(let l of o){if(!l.id){x.warn("KB item skipped since it has no ID.",l);continue}let a=s.find(m=>m.id==l.id);if(a){a.name=l.name||a.name||"",a.content=l.content||a.content||"",a.disabled=l.disabled??a.disabled,a.isContext=l.isContext??a.isContext,a.parameters=l.parameters||a.parameters||[],a.tags=l.tags||a.tags,a.type=l.type||a.type;continue}s.push({...l,action:m=>r(l,m)})}};this.registerSource(e,async o=>{if(i&&n.includes(o))return s;let l={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:o},a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let m=await a.json();return i=!m.noCache,n.includes(o)||n.push(o),c(m.items),s})}clone(){let t=new u(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}registerMCPSource(t){t.id||(t.id=`external.${F++}`);let e=new N(t);return this.registerSource(t.id,s=>e.search(s)),e}};import{v4 as J}from"uuid";var K=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
13
15
|
|
|
14
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}
|
|
15
17
|
|
|
@@ -23,10 +25,10 @@ You will receive some data. Extraction instructions: ${t.instruction}
|
|
|
23
25
|
${t.allowMultiple?"Return a JSONL string only, one JSON object on each line.":"Return a valid JSON object only."}
|
|
24
26
|
|
|
25
27
|
Objects should have the following keys:
|
|
26
|
-
${t.extractions.map(
|
|
28
|
+
${t.extractions.map(n=>`- ${n.name} (${n.type}): ${n.description||"No description provided."}`).join(`
|
|
27
29
|
`)}
|
|
28
|
-
`,s=await this.instruct({...t,instruction:e});if(s=s.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),t.allowMultiple){let
|
|
29
|
-
`).map(
|
|
30
|
-
`});else if(
|
|
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(r=>r.trim()).filter(r=>!!r.trim()),i=[];for(let r of n)try{i.push(JSON.parse(r))}catch(c){console.error("Failed to parse line as JSON:",r,c.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,$=class $ extends EventTarget{constructor(){super(...arguments);this.conversationID=J();this.knowledgeBase=new W(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new K(this);this.userID=q();this.extra=p().extra||{};this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this._lastTrackedTokens=0}get loaded(){return!!(this.config&&this.currentModel)}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,r)=>{let c=this.knowledgeBase.getCachedEntry(i);this.onAIToolStart?.(c?.id||i,r)}};s.config.providerID==="anthropic"?this.currentModel=new O(n):this.currentModel=new A(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:e}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,content:'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). Current info and tour items:'});let s=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;for(let i of s)if(i.type=="info"||i.type=="tour"||i.type=="input-event")this.currentModel.contextGroup.add({id:i.id,customData:i,cannotRemove:i.isContext,sortOrder:101,disabled:i.disabled,content:JSON.stringify({id:i.id,type:i.type,name:i.name,content:R(typeof i.content=="function"?i.content():i.content)})+`
|
|
32
|
+
`});else if(i.type=="action"){let r={name:i._functionID,description:R(typeof i.content=="function"?i.content():i.content),params:H(i.parameters||[{name:"value",type:"string",description:"Input"}]),removeFromMessageHistory:!!i.removeFromMessageHistory,callback:c=>this.toolRunKBAction(i,c),kb:i};this.currentModel.registerTool(r)}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),r=Date.now()-n;return b(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:s,execution_time_ms:r,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:s,ai:this,result:i}})),i}catch(i){let r=Date.now()-n;throw b(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:s,execution_time_ms:r,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=J(),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:J(),content:JSON.stringify(s),customData:s})}clone(){let e=new $;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.extra=this.extra,e.knowledgeBase=this.knowledgeBase.clone(),e}};$.version=y.version;var G=$;var j=new g("Stream"),se=class extends G{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.
|
|
31
33
|
|
|
32
|
-
`;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(),
|
|
34
|
+
`;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(),j.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){j.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){j.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{O as AnthropicChat,X as BufferedWebSocket,k as ChatBase,A as ChatGPT,Y as FixedBufferStream,G as IntelliWeave,se as IntelliWeaveStream,W as KnowledgeBase,g as Logging,N as MCPKnowledgeClient,V as ONNXModel,Z as Resampler,M as TokenWindow,U as TokenWindowGroup,xe as audioToWav,H as convertParamsToJSONSchema,Te as floatTo16BitPCM,_e as floatTo64BitPCM,q as getDefaultUserID,Ce as int16ToFloat32BitPCM,p as intelliweaveConfig,C as intelliweaveGlobalThis,z as sseEvents,R as trimWhitespaceInText};
|