@intelliweave/embedded 1.6.45

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.
@@ -0,0 +1,26 @@
1
+ import{v4 as C}from"uuid";function A(c){let t=(c||"").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 i=s.match(/^\s*/)?.[0].length||0;e=Math.min(e,i)}return e>0&&e<1/0&&(t=t.map(s=>s.substring(e))),t.join(`
3
+ `)}var j={};function b(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:j}function f(){return b().intelliweave=b().intelliweave||b().webWeaver||{},b().intelliweave}async function*P(c){let t="",e=function*(){for(;;){let o=t.indexOf(`
4
+
5
+ `);if(o==-1)break;let l=t.slice(0,o);t=t.slice(o+2);let a={},n=l.split(`
6
+ `);for(let r of n){o=r.indexOf(": ");let u=r.slice(0,o),d=r.slice(o+2);o==-1&&(u=r,d=""),u&&(a[u]!==void 0?a[u]+=`
7
+ `+d:a[u]=d)}yield a}},s=new TextDecoder,i=c.getReader();for(;;){let{done:o,value:l}=await i.read();if(o)break;t+=s.decode(l,{stream:!0}),yield*e()}t+=s.decode()+`
8
+
9
+ `,yield*e()}function O(){if(f().userID)return f().userID;if(typeof localStorage<"u"){let c=localStorage.getItem("intelliweave.uid")||"";return c||(c=C(),localStorage.setItem("intelliweave.uid",c),c)}else return C()}var I=class I{constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return I.debug?!0:typeof window<"u"&&f().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),(...i)=>this.debug(`[${t} ${Math.floor(Date.now()-s)}ms]`,...i)}};I.debug=!1;var g=I;var w=new g("ONNXModel"),D=class c{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,w.debug(`Model input parameters: ${t.inputNames.join(", ")}`),w.debug(`Model output parameters: ${t.outputNames.join(", ")}`)}static isSupported(){return!!c.lib}static async load(t){if(!c.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(w.debug("Loading ONNX runtime"),this.onnx=await c.lib()),w.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new c(e)}makeTensor(t,e,s=0){let i=1;for(let l of e)i*=l;let o;if(t=="float32")o=new c.onnx.Tensor(new Float32Array(i),e);else if(t=="int8")o=new c.onnx.Tensor(new Int8Array(i),e);else if(t=="int16")o=new c.onnx.Tensor(new Int16Array(i),e);else if(t=="int32")o=new c.onnx.Tensor(new Int32Array(i),e);else if(t=="int64")o=new c.onnx.Tensor(new BigInt64Array(i),e);else if(t=="uint8")o=new c.onnx.Tensor(new Uint8Array(i),e);else if(t=="uint16")o=new c.onnx.Tensor(new Uint16Array(i),e);else if(t=="uint32")o=new c.onnx.Tensor(new Uint32Array(i),e);else if(t=="uint64")o=new c.onnx.Tensor(new BigUint64Array(i),e);else throw new Error(`Invalid type: ${t}`);return s!==0&&(t=="int64"||t=="uint64")?o.data.fill(BigInt(s)):s!==0&&o.data.fill(s),o}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,i=0){return this.registerConstant(t,this.makeTensor(e,s,i))}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,i,o=0){return this.registerState(t,e,this.makeTensor(s,i,o))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return w.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 i=e[this.stateTensors[s].outputName];this.stateTensors[s].tensor=i}return e}finally{this._runActive=!1}}resetState(){w.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};function V(c,t){let e=t.reduce((n,r)=>n+r.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 i=1,o=32,l=i*o/8,a=c*l;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,i,!0),s.setUint32(24,c,!0),s.setUint32(28,a,!0),s.setUint16(32,l,!0),s.setUint16(34,o,!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 W=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 _=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 i=e.length-s,o=this.partialBuffers[0],l=o.length-this.partialBufferOffset;l<i?(e.set(o.subarray(this.partialBufferOffset),s),s+=l,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+i),s),s+=i,this.partialBufferOffset+=i)}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 K=class{constructor(t,e,s,i){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=i,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,i,o,l,a,n,r,u,d,h;if(e%s!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(i=this.outputBufferSize,o=this.ratioWeight,l=this.lastWeight,a=0,n=0,r=0,u=0,d=this.outputBuffer;l<1;l+=o)for(n=l%1,a=1-n,this.lastWeight=l%1,h=0;h<this.channels;++h)d[u++]=this.lastOutput[h]*a+t[h]*n;for(l-=1,e-=s,r=Math.floor(l)*s;u<i&&r<e;){for(n=l%1,a=1-n,h=0;h<this.channels;++h)d[u++]=t[r+(h>0?h:0)]*a+t[r+(s+h)]*n;l+=o,r=Math.floor(l)*s}for(h=0;h<s;++h)this.lastOutput[h]=t[r++];return this.bufferSlice(u)}}multiTap(){this.resampler=t=>{let e=t.length,s,i,o=this.channels,l,a,n,r,u,d,h,v,x;if(e%o!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,i=[],l=this.ratioWeight,a=0,r=0,u=0,d=!this.tailExists,this.tailExists=!1,h=this.outputBuffer,v=0,x=0,n=0;n<o;++n)i[n]=0;do{if(d)for(a=l,n=0;n<o;++n)i[n]=0;else{for(a=this.lastWeight,n=0;n<o;++n)i[n]=this.lastOutput[n];d=!0}for(;a>0&&r<e;)if(u=1+r-x,a>=u){for(n=0;n<o;++n)i[n]+=t[r++]*u;x=r,a-=u}else{for(n=0;n<o;++n)i[n]+=t[r+(n>0?n:0)]*a;x+=a,a=0;break}if(a===0)for(n=0;n<o;++n)h[v++]=i[n]/l;else{for(this.lastWeight=a,n=0;n<o;++n)this.lastOutput[n]=i[n];this.tailExists=!0;break}}while(r<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(c){let t=c.length,e=new Int16Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,c[t]));e[t]=s<0?s*32768:s*32767}return e}function se(c){let t=c.length,e=new BigInt64Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,c[t]));e[t]=BigInt(Math.floor(s<0?s*32768:s*32767))*0x100000000000n}return e}function ne(c){let t=c.length,e=new Float32Array(t);for(;t--;){let s=c[t];e[t]=s>=32768?-(65536-s)/32768:s/32767}return e}var p=new g("ChatGPT"),S=class{constructor(t){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...t}}async sendMessage(t){this.messages.push({role:"user",content:t}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let e=this.messages[this.messages.length-1];return e?.role=="assistant"&&e.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),p.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let t=this.messages[this.messages.length-1];if(t?.role=="user"||t?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(t?.role=="assistant"&&t?.tool_calls?.length){for(let e of t.tool_calls)await this.processToolCall(e);await this.processMessages()}}async trimMessages(){for(;;){let t=await this.sendToAPI(!0);if(JSON.stringify(t).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){p.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(t){let e=0;for(let n=this.messages.length-1;n>=0;n--)if(this.messages[n].role=="assistant"&&this.messages[n].tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[n].role=="user")break;p.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let s={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let n of this.tools){n.description&&n.description.length>1024&&p.warn(`Tool description for "${n.name}" is too long, it will be truncated.`);let r={type:"function",function:{name:n.name,description:(n.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(n.params))for(let u of n.params)r.function.parameters.properties[u.name]={type:u.type,description:u.description};else if(n.params){let u=n.params;for(let d in u)r.function.parameters.properties[d]={type:"string",description:u[d]}}s.tools.push(r)}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 o=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(s)});if(!o.ok){let n=`${o.status} ${o.statusText}`;try{let u=await o.json();n=u.errorText||u.error?.message||u.error||n}catch{}let r=new Error(n);throw r.code=o.status,r}let l=null,a=null;if(this.config.stream)for await(let n of P(o.body)){if(n.data=="[DONE]")break;if(!n.data)continue;let r=JSON.parse(n.data);if(a){for(let u in r.choices[0].delta)if(typeof r.choices[0].delta[u]=="string"){if(u=="role"&&a[u]==r.choices[0].delta[u])continue;a[u]=(a[u]||"")+r.choices[0].delta[u]}for(let u of r.choices[0].delta.tool_calls||[]){if(a.tool_calls||(a.tool_calls=[]),!a.tool_calls[u.index]){a.tool_calls[u.index]=u;continue}let d=a.tool_calls[u.index];d.function=d.function||{},d.function.name=(d.function.name||"")+(u.function?.name||""),d.function.arguments=(d.function.arguments||"")+(u.function?.arguments||"")}}else a={chunkID:r.id,...r.choices[0].delta};a?.content&&!a.content.startsWith("{")&&this.config.onAIMessage?.(a.content,!0)}else l=await o.json(),this.stats.tokensUsed+=l.usage?.total_tokens||0,p.debug(`Used ${l.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),a=l.choices?.[0]?.message;if(a||(p.warn("No response block in API response."),a={role:"assistant",content:""}),a.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(a),this.messages.push(a),a.content&&this.config.onAIMessage?.(a.content,!1)}processIncomingMessage(t){}registerTool(t){this.tools.push(t)}async processToolCall(t){try{let e=this.tools.find(o=>o.name==t.function.name);if(!e)throw new Error(`Tool "${t.function.name}" not found.`);let s=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,s);let i=await e.callback(s);if(typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&e.removeFromMessageHistory){p.debug(`Removing tool call history for "${e.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(o=>o.role!="assistant"||!o.tool_calls?.find(l=>l.id==t.id));return}else e.removeFromMessageHistory&&p.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${e.name}"`);this.messages.push({role:"tool",content:i,tool_call_id:t.id})}catch(e){p.warn(`Unable to process tool call for "${t?.function?.name}"`,e),this.messages.push({role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id})}}resetConversation(){this.messages=[]}};import F from"minisearch";var N=[{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);t.updateKnowledgeBase(e),t.submitAnalyticsEvent({type:"kb-search",query:c.query,results:e});let s=e.filter(o=>o.type!="action").map(o=>"id="+o.id).join(", ")||"(none)",i=e.filter(o=>o.type=="action").map(o=>"name="+o.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${s}. New tools available: ${i}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",isContext:!0,get disabled(){return typeof window>"u"},content:"Opens the specified URL in a new tab.",parameters:[{name:"url",type:"string",description:"The URL to open"}],action:(c,t)=>{if(!window.open(c.url,"_blank"))throw new Error("Window blocked by popup blocker.");return t.submitAnalyticsEvent({type:"open-url",url:c.url}),"URL opened"}}];var y=new g("KnowledgeBase"),$=1,E=class c{constructor(t){this._sources=[{id:"core.internal",query:async()=>N}];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 typeof window<"u"&&f().knowledgeBaseSources&&(t=t.concat(f().knowledgeBaseSources.map(e=>({id:e.name,query:e})))),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){y.debug(`Searching knowledge base for: ${t}`);let e=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});e.query=t,e.entries=[],e.sources=[],typeof document<"u"&&document.dispatchEvent(e),this._windowSources=e.sources;let i=(await Promise.all(this.sources.map(async n=>{try{return await n.query(t)}catch(r){return y.warn(`Knowledge source '${n.id}' failed:`,r),[]}}))).flat();i=i.concat(e.entries),i=i.concat(this.manualEntries),f().knowledgeBase&&(i=i.concat(f().knowledgeBase)),i=i.filter(n=>n&&!n.disabled);for(let n=0;n<i.length;n++){let r=i[n];if(r.id=r.id||`temp.${n}`,!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.")}),r.parameters&&!Array.isArray(r.parameters)){let u=r.parameters,d=[];for(let h in u)d.push({name:h,type:"string",description:r.parameters[h]});r.parameters=d}r.content=A(typeof r.content=="function"?r.content():r.content)}let o=new F({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let a=o.search(t).map(n=>i.find(r=>r.id==n.id));for(let n of i)n.isContext&&(a.find(r=>r.id===n.id)||a.push(n));return this.lastResults=a,y.debug("Found results:",a),a}getCachedEntry(t){return this.lastResults.find(e=>e.id==t)}registerSourceFromURL(t,e){e||(e=`external.${$++}`),y.debug(`Registering remote knowledge base source: ${t}`);let s=[],i=async(l,a)=>{y.debug(`Calling remote knowledge base action: ${l.id}`);let n={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:a},r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let u=await r.json();return o(u.updateItems||[]),u.response},o=l=>{for(let a of l){if(!a.id){y.warn("KB item skipped since it has no ID.",a);continue}let n=s.find(r=>r.id==a.id);if(n){n.name=a.name||n.name||"",n.content=a.content||n.content||"",n.disabled=a.disabled??n.disabled,n.isContext=a.isContext??n.isContext,n.parameters=a.parameters||n.parameters||[],n.tags=a.tags||n.tags,n.type=a.type||n.type;continue}s.push({...a,action:r=>i(a,r)})}};this.registerSource(e,async l=>{let a={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:l},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!n.ok)throw new Error(`HTTP Error ${n.status} ${n.statusText}`);let r=await n.json();return o(r.items),s})}clone(){let t=new c(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}};import{v4 as R}from"uuid";var U={name:"@intelliweave/embedded",version:"1.6.45",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"},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:{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",uuid:"^10.0.0"}};var T=class{constructor(t){this.ai=t}async boolean(t,e){let s=this.ai.clone();s.resetConversation(),s.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let i=await s.sendMessage(t+`
10
+
11
+ `+JSON.stringify(e))||"";if(i.toLowerCase().includes("true"))return!0;if(i.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+i)}async choose(t,e,s){s=s.map(l=>l.trim());let i=this.ai.clone();i.resetConversation(),i.getContextPrefix=async()=>"You will receive a question and some data and options. Answer the question by replying with the option you want to choose. Only say the option you want, no additional text.";let o=await i.sendMessage("question:"+t+`
12
+
13
+ data:`+JSON.stringify(e)+`
14
+
15
+ options:`+s.join(`
16
+ `))||"";return s.find(l=>o.toLowerCase().includes(l.toLowerCase()))}async extract(t,e,s,i){let o=this.ai.clone();o.resetConversation(),o.getContextPrefix=async()=>"You will receive a question and some data. Answer the question by replying with the extracted data as valid json. If there are multiple extractions, separate them with commas.";let l=await o.sendMessage("question:"+t+`
17
+
18
+ data:`+JSON.stringify(e)+`
19
+
20
+ extractions:`+JSON.stringify(i))||"";l=l.replace(/```json/g,"").replace(/```/g,"").replace(/\n/g,"");let a=l.split(",").map(n=>n.trim()).join(",");return JSON.parse(a)}async generateMarkdown(t,e){return this.instruct("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.",t,e)}async instruct(t,e,s){let i=this.ai.clone();return i.resetConversation(),i.getContextPrefix=async()=>t,s&&i.addEventListener("output",l=>{s(l.detail.message)}),await i.sendMessage(e)}};var m=new g("Main"),M=class M extends EventTarget{constructor(){super(...arguments);this.conversationID=R();this.knowledgeBase=new E(this);this._lastKBentries=[];this.models=[];this.audio=null;this.apiKey="";this.logic=new T(this);this.userID=O();this.extra=f().extra||{};this._lastSystemMsg="";this.isProcessing=!1}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()=>{m.debug("Loading configuration...");let s=await fetch("https://intelliweave.ai/api/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}`);this.config=await s.json(),m.debug("Configuration loaded")})(),(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){m.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&&this.knowledgeBase.registerSourceFromURL(s.url);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 m.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.`);this.currentModel=new S({...s.config,onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(i,o)=>{let l=this._lastKBentries.find(a=>a.id?.replaceAll(/[^a-zA-Z0-9_]/g,"_")==i);this.onAIToolStart?.(l?.id||i,o)}}),this.currentModel.id=s.id,this.currentModel.metadata=s}async getContextPrefix(){let e=f().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._lastKBentries.length==0&&this.updateKnowledgeBase(await this.knowledgeBase.search("__intelliweaveblanksearchforcontextitems__"));let e=await this.getContextPrefix(),s=(this.currentModel.config.maxTokens||4e3)*.5*4,i=0;for(;;){let o=this._lastKBentries.slice(),l=0;for(;l<i;){let r=o.findLastIndex(u=>!u.isContext);if(!r){m.warn("Too much context, and no more items to remove from the KB. Check the size and number of knowledge base entries, or use an LLM with a larger context window.",o);break}o.splice(r,1)}let a=`${e}
21
+
22
+ You have access to a database of knowledge base items. These include "info" type items which provide information, "tour" type items which contain instructions you should follow (only do the first one from the list!), and "action" type items which become available as tool calls. Current info and tour items:
23
+ `;a+=o.filter(r=>r.type=="info"||r.type=="tour"||r.type=="input-event").map(r=>JSON.stringify({id:r.id,type:r.type,name:r.name,content:typeof r.content=="function"?r.content():r.content})).join(`
24
+ `),this.currentModel.config.systemMessage=a,this.currentModel.tools=o.filter(r=>r.type=="action"||r.type=="output-event").map(r=>({name:r.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),description:typeof r.content=="function"?r.content():r.content,params:r.parameters||[{name:"value",type:"string",description:"Input"}],removeFromMessageHistory:!!r.removeFromMessageHistory,callback:u=>this.toolRunKBAction(r,u),kb:r}));let n=this.currentModel.config.systemMessage;if(n+=JSON.stringify(this.currentModel.tools.map(r=>({name:r.name,description:r.description,params:r.params}))),n.length<=s)break;i+=1}this._lastSystemMsg!=this.currentModel.config.systemMessage&&(this._lastSystemMsg=this.currentModel.config.systemMessage,this.submitAnalyticsEvent({type:"system-msg",txt:this.currentModel.config.systemMessage}))}updateKnowledgeBase(e){this._lastKBentries=e}processIncomingMessage(e,s){s||this.submitAnalyticsEvent({type:"message",role:"assistant",message:e});let i="";this._lastOutput===void 0?(i=e,this._lastOutput=e):e.startsWith(this._lastOutput)?(i=e.substring(this._lastOutput.length),this._lastOutput=e):(m.warn("Message was changed during chunking. This should not happen.",e,this._lastOutput),i=e,this._lastOutput=e),s||(this._lastOutput=void 0),this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:s,message:e,messageChunk:i}})),this.onAIMessage?.(e,!!s)}async sendMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)return m.warn("Cannot send message while another message is being processed."),null;this.isProcessing=!0;try{return this.submitAnalyticsEvent({type:"message",role:"user",message:e}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),await this.currentModel.sendMessage(e)}finally{this.isProcessing=!1}}async toolRunKBAction(e,s){try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:s,ai:this}}));let i=await e.action(s,this);return this.submitAnalyticsEvent({type:"action",action:e.id,value:s,result:i}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:s,ai:this,result:i}})),i}catch(i){throw this.submitAnalyticsEvent({type:"action",action:e.id,value:s,error:i.message}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:s,ai:this,error:i}})),i}}submitAnalyticsEvent(e){f().analytics===!1||this.config?.analytics===!1||fetch("https://intelliweave.ai/api/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID})}).catch(s=>{m.debug("Failed to submit analytics event:",s)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this.conversationID=R(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.messages.push({role:"assistant",content:e})}exportState(){return{type:"intelliweave/state/v1",conversationID:this.conversationID,messages:this.currentModel?.messages}}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,this.currentModel.messages=e.messages}clone(){let e=new M;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}};M.version=U.version;var B=M;var k=new g("Stream"),L=class extends B{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.
25
+
26
+ `;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(),k.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){k.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 i=JSON.stringify(e),o=await this.sendMessage(i)||"";if(!o.trim())return;this.emitEvent({eventName:"text",text:o,timestamp:Date.now(),timestampDate:new Date().toString(),direction:"output"})}catch(e){k.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{W as BufferedWebSocket,S as ChatGPT,_ as FixedBufferStream,B as IntelliWeave,L as IntelliWeaveStream,E as KnowledgeBase,g as Logging,D as ONNXModel,K as Resampler,V as audioToWav,te as floatTo16BitPCM,se as floatTo64BitPCM,O as getDefaultUserID,ne as int16ToFloat32BitPCM,f as intelliweaveConfig,b as intelliweaveGlobalThis,P as sseEvents,A as trimWhitespaceInText};