@intelliweave/embedded 2.0.72-beta.4 → 2.0.72-beta.6
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 +52 -0
- package/dist/component/component.js +38 -38
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.d.ts +52 -0
- package/dist/node/node.js +22 -22
- package/dist/react/react.d.ts +52 -0
- package/dist/react/react.js +21 -21
- package/dist/script-tag/script-tag.js +61 -61
- package/dist/webpack/index.d.ts +53 -1
- package/dist/webpack/index.js +36 -36
- package/package.json +1 -1
- package/vitest.config.ts +1 -1
package/dist/webpack/index.js
CHANGED
|
@@ -1,43 +1,43 @@
|
|
|
1
|
-
import{v4 as Ge}from"uuid";function Q(l){let
|
|
2
|
-
`);for(;
|
|
3
|
-
`)}var
|
|
1
|
+
import{v4 as Ge}from"uuid";function Q(l){let t=(l||"").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 i of t){let o=i.match(/^\s*/)?.[0].length||0;e=Math.min(e,o)}return e>0&&e<1/0&&(t=t.map(i=>i.substring(e))),t.join(`
|
|
3
|
+
`)}var st={};function k(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:st}function h(){return k().intelliweave=k().intelliweave||k().webWeaver||{},k().intelliweave}async function*Vt(l){let t="",e=function*(){for(;;){let n=t.indexOf(`
|
|
4
4
|
|
|
5
|
-
`);if(n==-1)break;let s=
|
|
5
|
+
`);if(n==-1)break;let s=t.slice(0,n);t=t.slice(n+2);let a={},r=s.split(`
|
|
6
6
|
`);for(let d of r){n=d.indexOf(": ");let c=d.slice(0,n),u=d.slice(n+2);n==-1&&(c=d,u=""),c&&(a[c]!==void 0?a[c]+=`
|
|
7
|
-
`+u:a[c]=u)}yield a}},
|
|
7
|
+
`+u:a[c]=u)}yield a}},i=new TextDecoder,o=l.getReader();for(;;){let{done:n,value:s}=await o.read();if(n)break;t+=i.decode(s,{stream:!0}),yield*e()}t+=i.decode()+`
|
|
8
8
|
|
|
9
|
-
`,yield*e()}function Ae(){if(h().userID)return h().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let l=localStorage.getItem("intelliweave.uid")||"";return l||(l=Ge(),localStorage.setItem("intelliweave.uid",l),l)}else return Ge()}function Ee(l){let i=l;if(i?.type=="object"&&i.properties)return l;let e={type:"object",properties:{},required:[]};if(l&&Array.isArray(l)){let t=l;for(let o of t)e.properties[o.name]={type:o.type||"string",description:o.description||""}}return e}var $=class ${constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return $.debug?!0:typeof window<"u"&&h().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...o)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...o)}};$.debug=!1;var m=$;var Z=new m("ONNXModel"),S=class l{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,Z.debug(`Model input parameters: ${i.inputNames.join(", ")}`),Z.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!l.lib}static async load(i){if(!l.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(Z.debug("Loading ONNX runtime"),this.onnx=await l.lib()),Z.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new l(e)}makeTensor(i,e,t=0){let o=1;for(let s of e)o*=s;let n;if(i=="float32")n=new l.onnx.Tensor(new Float32Array(o),e);else if(i=="int8")n=new l.onnx.Tensor(new Int8Array(o),e);else if(i=="int16")n=new l.onnx.Tensor(new Int16Array(o),e);else if(i=="int32")n=new l.onnx.Tensor(new Int32Array(o),e);else if(i=="int64")n=new l.onnx.Tensor(new BigInt64Array(o),e);else if(i=="uint8")n=new l.onnx.Tensor(new Uint8Array(o),e);else if(i=="uint16")n=new l.onnx.Tensor(new Uint16Array(o),e);else if(i=="uint32")n=new l.onnx.Tensor(new Uint32Array(o),e);else if(i=="uint64")n=new l.onnx.Tensor(new BigUint64Array(o),e);else throw new Error(`Invalid type: ${i}`);return t!==0&&(i=="int64"||i=="uint64")?n.data.fill(BigInt(t)):t!==0&&n.data.fill(t),n}registerConstant(i,e){if(!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);return this.constantTensors[i]=e,e}makeConstant(i,e,t,o=0){return this.registerConstant(i,this.makeTensor(e,t,o))}registerState(i,e,t){if(e||(e=i),!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[i]={outputName:e,tensor:t},t}makeState(i,e,t,o,n=0){return this.registerState(i,e,this.makeTensor(t,o,n))}async run(i={}){if(this._runActive&&this.ignoreIfBusy)return Z.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)i[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)i[e]=this.constantTensors[e];try{let e=await this.session.run(i);for(let t in this.stateTensors){let o=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=o}return e}finally{this._runActive=!1}}resetState(){Z.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var Ze="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0a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g9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var at=new m("PCMPlayerNode"),W=class extends AudioWorkletNode{constructor(e,t,o){super(e,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!o||o!="int16"&&o!="float32")throw new Error(`Invalid format: ${o}`);this.sampleRate=t,this.format=o,this.port.onmessage=n=>this.onWorkletMessage(n),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:o})}static async registerModule(e){await e.audioWorklet.addModule(Ze)}feed(e){this.port.postMessage({action:"data",buffer:e.buffer},[e.buffer])}async play(e){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(t=>this._playPromiseResolve=t),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:e}}));try{let t=e.getReader();for(;!this.isCancelled;){let{done:o,value:n}=await t.read();if(o||!n)break;this.feed(n)}}catch(t){at.warn("Stream error:",t),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:e,error:t}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(e){e.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var q=new m("SpeechOutput"),We=.5,rt=.8,ee=class extends EventTarget{constructor(e){super();this.maxVolumeHeard=0;this.ai=e,this.ai.addEventListener("output",t=>this.onTextOutputFromAI(t)),this.ai.audio?.speechRecognition.addEventListener("speechstart",t=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(e){e.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(e.detail.message)}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let o of this.analyserBuffer)e+=o*o;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}async speak(e){if(!this.ai?.config?.voice?.providerID)return q.warn("No voice provider configured");let t=`speech-${lt++}`;await this.ai.audio.beginAccess(t);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(t)}}async _speakWithLock(e){let t=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:e}});if(this.dispatchEvent(t),e=t.detail.message,t.defaultPrevented||!e)return;this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=rt);let o=this.ai?._voiceTracker||q.timer(`${this.ai.config.voice.providerID} voice`);o(`Speak: ${e}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let n=new W(this.ai.audio.context,24e3,"int16");this.currentPlayer=n,n.connect(this.analyserNode),n.addEventListener("end",a=>{let r=a;o(`PCM stream ${r.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==n&&!r.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let s;if(this.ai.config.voice.providerID=="openai")s=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:e,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:e})});else{q.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(o(`Received response ${s.status} ${s.statusText}`),!s.ok){q.warn(`Failed to generate voice sample: ${s.status} ${s.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),o("Playing PCM stream"),await n.play(s.body),o("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let e=this.currentPlayerVolume,t=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=We);let o=400;e.gain.linearRampToValueAtTime(0,o/1e3),await new Promise(n=>setTimeout(n,o+250)),e.disconnect(),t?.stop(),t?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=We)}},lt=1;function te(l,i){let e=i.reduce((r,d)=>r+d.byteLength,0),t=new DataView(new ArrayBuffer(44));t.setUint8(0,82),t.setUint8(1,73),t.setUint8(2,70),t.setUint8(3,70),t.setUint32(4,44+e,!0),t.setUint8(8,87),t.setUint8(9,65),t.setUint8(10,86),t.setUint8(11,69);let o=1,n=32,s=o*n/8,a=l*s;return t.setUint8(12,102),t.setUint8(13,109),t.setUint8(14,116),t.setUint8(15,32),t.setUint32(16,16,!0),t.setUint16(20,3,!0),t.setUint16(22,o,!0),t.setUint32(24,l,!0),t.setUint32(28,a,!0),t.setUint16(32,s,!0),t.setUint16(34,n,!0),t.setUint8(36,100),t.setUint8(37,97),t.setUint8(38,116),t.setUint8(39,97),t.setUint32(40,e,!0),new File([t,...i],"audio.wav",{type:"audio/wav"})}var De="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoZSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGUpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoP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TWF0aC5taW4oaVthXS5sZW5ndGgsdFswXS5sZW5ndGgpO2ZvcihsZXQgcj0wO3I8cztyKyspaVthXVtyXS5zZXQodFswXVtyXSl9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var D=class extends AudioWorkletNode{constructor(e,t,o,n){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=o;let s=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!s.includes(o))throw new Error(`Invalid format ${o}, must be one of: ${s.join(", ")}`);if(!n||n<=0)throw new Error(`Invalid buffer size: ${n}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:o,bufferSize:n})}static async registerModule(e){await e.audioWorklet.addModule(De)}onWorkletMessage(e){if(e.data.action=="data"){let t=null;if(this.format=="int16"&&(t=new Int16Array(e.data.buffer)),this.format=="int64"&&(t=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(t=new Float32Array(e.data.buffer)),!t)throw new Error(`Invalid format: ${this.format}`);this.onData(t),this.dispatchEvent(new CustomEvent("data",{detail:{data:t}}))}}onData(e){}};var Me=16e3,ie=256,X=8,O=new m("VoiceDetectionNode"),Y=class Y extends D{constructor(e){super(e,Me,"float32",ie*X);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!Y.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return Me}get numberOfSamples(){return ie}get numberOfSampleChunks(){return X}get outputBufferSize(){return ie*X}get isModelLoaded(){return!!this.vad}async loadModel(){O.debug("Loading VAD model"),this.vad=await S.load(Y.vadModelURL),this.vad.ignoreIfBusy=!0,O.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],Me),this.vad.makeState("h","hn","float32",[2,X,64]),this.vad.makeState("c","cn","float32",[2,X,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new S.onnx.Tensor(e,[X,ie])});if(!t)return;this.currentProbability=0;for(let s=0;s<t.output.data.length;s++)t.output.data[s]>this.currentProbability&&(this.currentProbability=t.output.data[s]);let o=this.isVoiceActive?this.sentivityEnd:this.sensitivity,n=this.currentProbability>o;if(!n&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=n,n&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),O.debug("Started speaking")):n?this.lastVoiceActiveDate=Date.now():!n&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!n&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),O.debug("Stopped speaking after timeout")),!n){let s=Date.now();s>this.nextVadReset&&(this.nextVadReset=s+5e3,this.vad.resetState())}}catch(t){O.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};Y.vadModelURL="";var R=Y;var Xe=new m("VoiceChunkOutputNode"),V=class extends R{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((e,t)=>e+t.length,0)/8e3}async onData(e){if(await super.onData(e),this.isVoiceActive&&!this._voiceRecording){Xe.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let t of this.buffers)this.recordedBuffers.push(t),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:t,isFinal:!1}})),this.onVoiceChunk(t);this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!0}})),this.onVoiceChunk(e),this._voiceRecording=!1;let t=this.recordedBuffers.reduce((o,n)=>o+n.length,0);Xe.debug(`Voice complete, recorded ${(t/8e3).toFixed(2)} seconds of audio, ${t*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(e);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(e){}onVoiceEnd(e){}};var oe=new m("OpenAITranscriptionNode"),ne=class extends V{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=oe.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let o=te(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let n="";try{let s=new FormData;s.append("file",o),s.append("model","whisper-1"),s.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);t("Response received"),n=await a.text(),t("Content received: "+n),this.lastRequestAbortController=void 0}catch(s){oe.error(`Failed to transcribe speech: ${s.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return oe.debug("Transcription complete, but no text was found");oe.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var se=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 M=new m("IntelliWeaveTranscriptionNode"),dt="wss://speech.intelliweave.ai/api/v1/transcribe",re=class re extends V{constructor(e,t){super(e);this.apiAddress=dt;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(M.debug("Opening WebSocket connection"),this.ws=new se(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(e.buffer),this.ws.onopen=()=>{M.debug("WebSocket connection opened")},this.ws.addEventListener("message",o=>{let n=JSON.parse(o.data);if(n.error)return M.warn("Error: "+n.error);if(n.type!="transcription")return M.warn("Invalid response type",n);if(n.streaming&&!n.final)return M.debug("Partial transcription: "+n.partialText);if(this.isTranscribing=!1,!n.text.trim())return M.warn(`Empty transcription (${n.processingTime}ms)`);M.debug(`Transcription: ${n.text} (${n.processingTime}ms)`),this.onVoiceTranscription(n.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",o=>M.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{M.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),re.debugExportWav){let t=te(this.sampleRate,e),o=document.createElement("a");o.href=URL.createObjectURL(t),o.download="recording.wav",o.click()}}onVoiceTranscription(e){}onSocketClose(){M.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};re.debugExportWav=!1;var ae=re;var I={name:"@intelliweave/embedded",version:"2.0.72-beta.4",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.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",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.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{v4 as pt}from"uuid";var ht=new m("Statistics"),_=[];async function y(l,i){let e={...i,event_id:pt(),event_date:new Date().toISOString(),sdk_version:I.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(_.push(e),!l||(await new Promise(o=>setTimeout(o,5e3)),_.length===0))return;let t=_.slice();_.length=0;try{let o=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!o.ok)throw new Error(`Analytics submission failed: ${o.status} ${o.statusText}`)}catch(o){ht.warn("Failed to submit analytics event:",o),_.push(...t);return}}var Ie=new m("SpeechRecognition"),le=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e,this.ai.knowledgeBase.registerSource(()=>[{id:"system.microphone.enable",type:"action",name:"Enable or disable microphone",isContext:!0,content:`Starts or stops listening to input from the user through the microphone. ${this.isRunning?"Microphone access is currently enabled and you can hear the user.":"Microphone access is currently disabled."}.`,parameters:[{name:"enable",type:"boolean",description:"If true, enables the microphone. If false, disables it."}],action:async t=>{t.enable?await this.start():this.stop()}}])}get isSupported(){if(!S.lib||!this.ai?.vadModel||!k().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let e=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,e.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),R.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new ne(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new ae(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",t=>{this.ai._voiceTracker=Ie.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),y(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("speechend",t=>{this.ai._voiceTracker?.("Speech ended");let o=this.recordingStartTime?Date.now()-this.recordingStartTime:0;y(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:o}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),y(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:t.detail.confidence||void 0}}),this.onTranscription(t)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){Ie.error("Failed to start speech recognition:",e),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(e=>e.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let o of this.analyserBuffer)e+=o*o;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(e){let t=e.detail.text;Ie.debug("Heard:",t),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:t,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(e){throw this._skipEvents=!1,e}}}};var ce=new m("AudioSystem"),C=class l{constructor(i){this.locks=[];if(!i)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=i,this.ai.audio=this,this.speechRecognition=new le(this.ai),this.speechOutput=new ee(this.ai)}static get isSupported(){return!(!S.lib||!k().AudioWorkletNode)}static async registerModules(i){await Promise.all([W.registerModule(i),D.registerModule(i)])}async beginAccess(i){ce.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(ce.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await l.registerModules(this.context))}endAccess(i){ce.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(ce.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var Re=class{constructor(i,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!i)throw new Error(`Invalid array class: ${i}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=i,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((i,e)=>i+e.length,0)}feed(i){this.partialBuffers.push(i)}get canDrain(){return this.partialBuffers.reduce((e,t)=>e+t.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let i=this.ArrayClass,e=new i(this.outputBufferSize),t=0;for(;t!=e.length;){if(t>e.length)throw new Error(`Buffer overflow: ${t} > ${e.length}`);let o=e.length-t,n=this.partialBuffers[0],s=n.length-this.partialBufferOffset;s<o?(e.set(n.subarray(this.partialBufferOffset),t),t+=s,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(n.subarray(this.partialBufferOffset,this.partialBufferOffset+o),t),t+=o,this.partialBufferOffset+=o)}return e}pad(){let i=this.queuedSize%this.outputBufferSize;if(i==0)return;let e=this.ArrayClass,t=new e(i);this.feed(t)}};var Ve=class{constructor(i,e,t,o){if(!i||!e||!t)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=i,this.toSampleRate=e,this.channels=t||0,this.inputBufferSize=o,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=i=>i,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(i){try{return this.outputBuffer.subarray(0,i)}catch{try{return this.outputBuffer.length=i,this.outputBuffer}catch{return this.outputBuffer.slice(0,i)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=i=>{let e=i.length,t=this.channels,o,n,s,a,r,d,c,u,p;if(e%t!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(o=this.outputBufferSize,n=this.ratioWeight,s=this.lastWeight,a=0,r=0,d=0,c=0,u=this.outputBuffer;s<1;s+=n)for(r=s%1,a=1-r,this.lastWeight=s%1,p=0;p<this.channels;++p)u[c++]=this.lastOutput[p]*a+i[p]*r;for(s-=1,e-=t,d=Math.floor(s)*t;c<o&&d<e;){for(r=s%1,a=1-r,p=0;p<this.channels;++p)u[c++]=i[d+(p>0?p:0)]*a+i[d+(t+p)]*r;s+=n,d=Math.floor(s)*t}for(p=0;p<t;++p)this.lastOutput[p]=i[d++];return this.bufferSlice(c)}}multiTap(){this.resampler=i=>{let e=i.length,t,o,n=this.channels,s,a,r,d,c,u,p,g,b;if(e%n!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(t=this.outputBufferSize,o=[],s=this.ratioWeight,a=0,d=0,c=0,u=!this.tailExists,this.tailExists=!1,p=this.outputBuffer,g=0,b=0,r=0;r<n;++r)o[r]=0;do{if(u)for(a=s,r=0;r<n;++r)o[r]=0;else{for(a=this.lastWeight,r=0;r<n;++r)o[r]=this.lastOutput[r];u=!0}for(;a>0&&d<e;)if(c=1+d-b,a>=c){for(r=0;r<n;++r)o[r]+=i[d++]*c;b=d,a-=c}else{for(r=0;r<n;++r)o[r]+=i[d+(r>0?r:0)]*a;b+=a,a=0;break}if(a===0)for(r=0;r<n;++r)p[g++]=o[r]/s;else{for(this.lastWeight=a,r=0;r<n;++r)this.lastOutput[r]=o[r];this.tailExists=!0;break}}while(d<e&&g<t);return this.bufferSlice(g)}}resample(i){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(i)}};function zi(l){let i=l.length,e=new Int16Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,l[i]));e[i]=t<0?t*32768:t*32767}return e}function Bi(l){let i=l.length,e=new BigInt64Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,l[i]));e[i]=BigInt(Math.floor(t<0?t*32768:t*32767))*0x100000000000n}return e}function ji(l){let i=l.length,e=new Float32Array(i);for(;i--;){let t=l[i];e[i]=t>=32768?-(65536-t)/32768:t/32767}return e}import ft from"openai";import{v4 as mt}from"uuid";var N=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new Te;return e.id=i,this.groups.push(e),e}group(i){return this.groups.find(e=>e.id===i)}static countTokensInText(i){return i==null?i="":typeof i=="number"?i=i+"":typeof i!="string"&&(i=JSON.stringify(i)),Math.ceil(i.length/3)}countTokens(){return this.groups.reduce((i,e)=>i+e.tokenCount,0)}removeOverflow(){let i=this.countTokens(),e=this.groups.reduce((t,o)=>t+o.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((n,s)=>{let a=Math.floor(n.weight/e*this.size),r=Math.floor(s.weight/e*this.size),d=n.tokenCount-a;return s.tokenCount-r-d}),o=this.removeOneItem(t);if(!o)throw new Error("Too many items in the token window that cannot be removed.");i-=o.tokenCount}}removeOneItem(i){for(let e of i){let t=e.items.findIndex(n=>!n.cannotRemove);if(t===-1)continue;let o=e.items[t];return e.items.splice(t,1),e.tokenCount-=o.tokenCount,o}return null}},Te=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
10
|
-
`;this.itemPadding=0;this.sortFunction=(
|
|
9
|
+
`,yield*e()}function Ee(){if(h().userID)return h().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let l=localStorage.getItem("intelliweave.uid")||"";return l||(l=Ge(),localStorage.setItem("intelliweave.uid",l),l)}else return Ge()}function We(l){let t=l;if(t?.type=="object"&&t.properties)return l;let e={type:"object",properties:{},required:[]};if(l&&Array.isArray(l)){let i=l;for(let o of i)e.properties[o.name]={type:o.type||"string",description:o.description||""}}return e}var $=class ${constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return $.debug?!0:typeof window<"u"&&h().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 i=Date.now();return this.debug(`[${t} 0ms] Started`,...e),(...o)=>this.debug(`[${t} ${Math.floor(Date.now()-i)}ms]`,...o)}};$.debug=!1;var m=$;var Z=new m("ONNXModel"),S=class l{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,Z.debug(`Model input parameters: ${t.inputNames.join(", ")}`),Z.debug(`Model output parameters: ${t.outputNames.join(", ")}`)}static isSupported(){return!!l.lib}static async load(t){if(!l.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(Z.debug("Loading ONNX runtime"),this.onnx=await l.lib()),Z.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new l(e)}makeTensor(t,e,i=0){let o=1;for(let s of e)o*=s;let n;if(t=="float32")n=new l.onnx.Tensor(new Float32Array(o),e);else if(t=="int8")n=new l.onnx.Tensor(new Int8Array(o),e);else if(t=="int16")n=new l.onnx.Tensor(new Int16Array(o),e);else if(t=="int32")n=new l.onnx.Tensor(new Int32Array(o),e);else if(t=="int64")n=new l.onnx.Tensor(new BigInt64Array(o),e);else if(t=="uint8")n=new l.onnx.Tensor(new Uint8Array(o),e);else if(t=="uint16")n=new l.onnx.Tensor(new Uint16Array(o),e);else if(t=="uint32")n=new l.onnx.Tensor(new Uint32Array(o),e);else if(t=="uint64")n=new l.onnx.Tensor(new BigUint64Array(o),e);else throw new Error(`Invalid type: ${t}`);return i!==0&&(t=="int64"||t=="uint64")?n.data.fill(BigInt(i)):i!==0&&n.data.fill(i),n}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,i,o=0){return this.registerConstant(t,this.makeTensor(e,i,o))}registerState(t,e,i){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:i},i}makeState(t,e,i,o,n=0){return this.registerState(t,e,this.makeTensor(i,o,n))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return Z.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 i in this.stateTensors){let o=e[this.stateTensors[i].outputName];this.stateTensors[i].tensor=o}return e}finally{this._runActive=!1}}resetState(){Z.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};var Ze="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3IoO3IhPXQ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WYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var rt=new m("PCMPlayerNode"),D=class extends AudioWorkletNode{constructor(e,i,o){super(e,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!i||i<=0)throw new Error(`Invalid sample rate: ${i}`);if(!o||o!="int16"&&o!="float32")throw new Error(`Invalid format: ${o}`);this.sampleRate=i,this.format=o,this.port.onmessage=n=>this.onWorkletMessage(n),this.port.postMessage({action:"start",inputSampleRate:i,outputSampleRate:e.sampleRate,format:o})}static async registerModule(e){await e.audioWorklet.addModule(Ze)}feed(e){this.port.postMessage({action:"data",buffer:e.buffer},[e.buffer])}async play(e){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(i=>this._playPromiseResolve=i),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:e}}));try{let i=e.getReader();for(;!this.isCancelled;){let{done:o,value:n}=await i.read();if(o||!n)break;this.feed(n)}}catch(i){rt.warn("Stream error:",i),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:e,error:i}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(e){e.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var q=new m("SpeechOutput"),De=.5,lt=.8,ee=class extends EventTarget{constructor(e){super();this.maxVolumeHeard=0;this.ai=e,this.ai.addEventListener("output",i=>this.onTextOutputFromAI(i)),this.ai.audio?.speechRecognition.addEventListener("speechstart",i=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(e){e.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(e.detail.message)}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let o of this.analyserBuffer)e+=o*o;let i=Math.sqrt(e/this.analyserBuffer.length);return i>this.maxVolumeHeard&&(this.maxVolumeHeard=i),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,i/this.maxVolumeHeard))}async speak(e){if(!this.ai?.config?.voice?.providerID)return q.warn("No voice provider configured");let i=`speech-${ct++}`;await this.ai.audio.beginAccess(i);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(i)}}async _speakWithLock(e){let i=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:e}});if(this.dispatchEvent(i),e=i.detail.message,i.defaultPrevented||!e)return;this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=lt);let o=this.ai?._voiceTracker||q.timer(`${this.ai.config.voice.providerID} voice`);o(`Speak: ${e}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let n=new D(this.ai.audio.context,24e3,"int16");this.currentPlayer=n,n.connect(this.analyserNode),n.addEventListener("end",a=>{let r=a;o(`PCM stream ${r.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==n&&!r.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let s;if(this.ai.config.voice.providerID=="openai")s=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:e,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:e})});else{q.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(o(`Received response ${s.status} ${s.statusText}`),!s.ok){q.warn(`Failed to generate voice sample: ${s.status} ${s.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),o("Playing PCM stream"),await n.play(s.body),o("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let e=this.currentPlayerVolume,i=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=De);let o=400;e.gain.linearRampToValueAtTime(0,o/1e3),await new Promise(n=>setTimeout(n,o+250)),e.disconnect(),i?.stop(),i?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=De)}},ct=1;function te(l,t){let e=t.reduce((r,d)=>r+d.byteLength,0),i=new DataView(new ArrayBuffer(44));i.setUint8(0,82),i.setUint8(1,73),i.setUint8(2,70),i.setUint8(3,70),i.setUint32(4,44+e,!0),i.setUint8(8,87),i.setUint8(9,65),i.setUint8(10,86),i.setUint8(11,69);let o=1,n=32,s=o*n/8,a=l*s;return i.setUint8(12,102),i.setUint8(13,109),i.setUint8(14,116),i.setUint8(15,32),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,o,!0),i.setUint32(24,l,!0),i.setUint32(28,a,!0),i.setUint16(32,s,!0),i.setUint16(34,n,!0),i.setUint8(36,100),i.setUint8(37,97),i.setUint8(38,116),i.setUint8(39,97),i.setUint32(40,e,!0),new File([i,...t],"audio.wav",{type:"audio/wav"})}var Xe="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2x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JkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var X=class extends AudioWorkletNode{constructor(e,i,o,n){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=o;let s=["int16","int64","float32"];if(!i||i<=0)throw new Error(`Invalid sample rate: ${i}`);if(!s.includes(o))throw new Error(`Invalid format ${o}, must be one of: ${s.join(", ")}`);if(!n||n<=0)throw new Error(`Invalid buffer size: ${n}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:i,format:o,bufferSize:n})}static async registerModule(e){await e.audioWorklet.addModule(Xe)}onWorkletMessage(e){if(e.data.action=="data"){let i=null;if(this.format=="int16"&&(i=new Int16Array(e.data.buffer)),this.format=="int64"&&(i=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(i=new Float32Array(e.data.buffer)),!i)throw new Error(`Invalid format: ${this.format}`);this.onData(i),this.dispatchEvent(new CustomEvent("data",{detail:{data:i}}))}}onData(e){}};var Ie=16e3,ie=256,R=8,O=new m("VoiceDetectionNode"),_=class _ extends X{constructor(e){super(e,Ie,"float32",ie*R);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!_.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return Ie}get numberOfSamples(){return ie}get numberOfSampleChunks(){return R}get outputBufferSize(){return ie*R}get isModelLoaded(){return!!this.vad}async loadModel(){O.debug("Loading VAD model"),this.vad=await S.load(_.vadModelURL),this.vad.ignoreIfBusy=!0,O.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],Ie),this.vad.makeState("h","hn","float32",[2,R,64]),this.vad.makeState("c","cn","float32",[2,R,64])}async onData(e){if(this.vad)try{let i=await this.vad.run({input:new S.onnx.Tensor(e,[R,ie])});if(!i)return;this.currentProbability=0;for(let s=0;s<i.output.data.length;s++)i.output.data[s]>this.currentProbability&&(this.currentProbability=i.output.data[s]);let o=this.isVoiceActive?this.sentivityEnd:this.sensitivity,n=this.currentProbability>o;if(!n&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=n,n&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),O.debug("Started speaking")):n?this.lastVoiceActiveDate=Date.now():!n&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!n&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),O.debug("Stopped speaking after timeout")),!n){let s=Date.now();s>this.nextVadReset&&(this.nextVadReset=s+5e3,this.vad.resetState())}}catch(i){O.error("VAD failed:",i)}}onSpeechStart(){}onSpeechEnd(){}};_.vadModelURL="";var P=_;var Re=new m("VoiceChunkOutputNode"),V=class extends P{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((e,i)=>e+i.length,0)/8e3}async onData(e){if(await super.onData(e),this.isVoiceActive&&!this._voiceRecording){Re.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let i of this.buffers)this.recordedBuffers.push(i),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:i,isFinal:!1}})),this.onVoiceChunk(i);this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!0}})),this.onVoiceChunk(e),this._voiceRecording=!1;let i=this.recordedBuffers.reduce((o,n)=>o+n.length,0);Re.debug(`Voice complete, recorded ${(i/8e3).toFixed(2)} seconds of audio, ${i*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(e);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(e){}onVoiceEnd(e){}};var oe=new m("OpenAITranscriptionNode"),ne=class extends V{constructor(e,i){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=i}async onVoiceEnd(e){let i=oe.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let o=te(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let n="";try{let s=new FormData;s.append("file",o),s.append("model","whisper-1"),s.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);i("Response received"),n=await a.text(),i("Content received: "+n),this.lastRequestAbortController=void 0}catch(s){oe.error(`Failed to transcribe speech: ${s.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return oe.debug("Transcription complete, but no text was found");oe.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var se=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 M=new m("IntelliWeaveTranscriptionNode"),ut="wss://speech.intelliweave.ai/api/v1/transcribe",re=class re extends V{constructor(e,i){super(e);this.apiAddress=ut;this.apiKey="";this.isTranscribing=!1;this.apiKey=i}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(M.debug("Opening WebSocket connection"),this.ws=new se(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(e.buffer),this.ws.onopen=()=>{M.debug("WebSocket connection opened")},this.ws.addEventListener("message",o=>{let n=JSON.parse(o.data);if(n.error)return M.warn("Error: "+n.error);if(n.type!="transcription")return M.warn("Invalid response type",n);if(n.streaming&&!n.final)return M.debug("Partial transcription: "+n.partialText);if(this.isTranscribing=!1,!n.text.trim())return M.warn(`Empty transcription (${n.processingTime}ms)`);M.debug(`Transcription: ${n.text} (${n.processingTime}ms)`),this.onVoiceTranscription(n.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",o=>M.warn("WebSocket error")));let i=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{M.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},i)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),re.debugExportWav){let i=te(this.sampleRate,e),o=document.createElement("a");o.href=URL.createObjectURL(i),o.download="recording.wav",o.click()}}onVoiceTranscription(e){}onSocketClose(){M.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};re.debugExportWav=!1;var ae=re;var I={name:"@intelliweave/embedded",version:"2.0.72-beta.6",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.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",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.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{v4 as ht}from"uuid";var mt=new m("Statistics"),Y=[];async function b(l,t){let e={...t,event_id:ht(),event_date:new Date().toISOString(),sdk_version:I.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(Y.push(e),!l||(await new Promise(o=>setTimeout(o,5e3)),Y.length===0))return;let i=Y.slice();Y.length=0;try{let o=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:i})});if(!o.ok)throw new Error(`Analytics submission failed: ${o.status} ${o.statusText}`)}catch(o){mt.warn("Failed to submit analytics event:",o),Y.push(...i);return}}var Te=new m("SpeechRecognition"),le=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e}get isSupported(){if(!S.lib||!this.ai?.vadModel||!k().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let e=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,e.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),P.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new ne(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new ae(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",i=>{this.ai._voiceTracker=Te.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),b(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(i.type,{detail:i.detail}))}),this.voiceDetection.addEventListener("speechend",i=>{this.ai._voiceTracker?.("Speech ended");let o=this.recordingStartTime?Date.now()-this.recordingStartTime:0;b(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:o}}),this.dispatchEvent(new CustomEvent(i.type,{detail:i.detail}))}),this.voiceDetection.addEventListener("transcription",i=>{this.ai._voiceTracker?.(`Transcription: ${i.detail.text}`),b(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:i.detail.confidence||void 0}}),this.onTranscription(i)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){Te.error("Failed to start speech recognition:",e),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(e=>e.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let o of this.analyserBuffer)e+=o*o;let i=Math.sqrt(e/this.analyserBuffer.length);return i>this.maxVolumeHeard&&(this.maxVolumeHeard=i),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,i/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(e){let i=e.detail.text;Te.debug("Heard:",i),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:i,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(e){throw this._skipEvents=!1,e}}}};var ce=new m("AudioSystem"),C=class l{constructor(t){this.locks=[];if(!t)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=t,this.ai.audio=this,this.speechRecognition=new le(this.ai),this.speechOutput=new ee(this.ai)}static get isSupported(){return!(!S.lib||!k().AudioWorkletNode)}static async registerModules(t){await Promise.all([D.registerModule(t),X.registerModule(t)])}async beginAccess(t){ce.debug(`Began access for: ${t}`),this.locks.includes(t)||this.locks.push(t),!this.context&&(ce.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await l.registerModules(this.context))}endAccess(t){ce.debug(`Ended access for: ${t}`),this.locks=this.locks.filter(e=>e!=t),!this.locks.length&&(ce.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var Pe=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,i)=>e+i.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let t=this.ArrayClass,e=new t(this.outputBufferSize),i=0;for(;i!=e.length;){if(i>e.length)throw new Error(`Buffer overflow: ${i} > ${e.length}`);let o=e.length-i,n=this.partialBuffers[0],s=n.length-this.partialBufferOffset;s<o?(e.set(n.subarray(this.partialBufferOffset),i),i+=s,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(n.subarray(this.partialBufferOffset,this.partialBufferOffset+o),i),i+=o,this.partialBufferOffset+=o)}return e}pad(){let t=this.queuedSize%this.outputBufferSize;if(t==0)return;let e=this.ArrayClass,i=new e(t);this.feed(i)}};var Ve=class{constructor(t,e,i,o){if(!t||!e||!i)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=t,this.toSampleRate=e,this.channels=i||0,this.inputBufferSize=o,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,i=this.channels,o,n,s,a,r,d,c,u,p;if(e%i!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(o=this.outputBufferSize,n=this.ratioWeight,s=this.lastWeight,a=0,r=0,d=0,c=0,u=this.outputBuffer;s<1;s+=n)for(r=s%1,a=1-r,this.lastWeight=s%1,p=0;p<this.channels;++p)u[c++]=this.lastOutput[p]*a+t[p]*r;for(s-=1,e-=i,d=Math.floor(s)*i;c<o&&d<e;){for(r=s%1,a=1-r,p=0;p<this.channels;++p)u[c++]=t[d+(p>0?p:0)]*a+t[d+(i+p)]*r;s+=n,d=Math.floor(s)*i}for(p=0;p<i;++p)this.lastOutput[p]=t[d++];return this.bufferSlice(c)}}multiTap(){this.resampler=t=>{let e=t.length,i,o,n=this.channels,s,a,r,d,c,u,p,g,y;if(e%n!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(i=this.outputBufferSize,o=[],s=this.ratioWeight,a=0,d=0,c=0,u=!this.tailExists,this.tailExists=!1,p=this.outputBuffer,g=0,y=0,r=0;r<n;++r)o[r]=0;do{if(u)for(a=s,r=0;r<n;++r)o[r]=0;else{for(a=this.lastWeight,r=0;r<n;++r)o[r]=this.lastOutput[r];u=!0}for(;a>0&&d<e;)if(c=1+d-y,a>=c){for(r=0;r<n;++r)o[r]+=t[d++]*c;y=d,a-=c}else{for(r=0;r<n;++r)o[r]+=t[d+(r>0?r:0)]*a;y+=a,a=0;break}if(a===0)for(r=0;r<n;++r)p[g++]=o[r]/s;else{for(this.lastWeight=a,r=0;r<n;++r)this.lastOutput[r]=o[r];this.tailExists=!0;break}}while(d<e&&g<i);return this.bufferSlice(g)}}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 Bi(l){let t=l.length,e=new Int16Array(t);for(;t--;){let i=Math.max(-1,Math.min(1,l[t]));e[t]=i<0?i*32768:i*32767}return e}function ji(l){let t=l.length,e=new BigInt64Array(t);for(;t--;){let i=Math.max(-1,Math.min(1,l[t]));e[t]=BigInt(Math.floor(i<0?i*32768:i*32767))*0x100000000000n}return e}function Oi(l){let t=l.length,e=new Float32Array(t);for(;t--;){let i=l[t];e[t]=i>=32768?-(65536-i)/32768:i/32767}return e}import yt from"openai";import{v4 as gt}from"uuid";var N=class{constructor(){this.size=4096;this.groups=[]}createGroup(t){let e=new Se;return e.id=t,this.groups.push(e),e}group(t){return this.groups.find(e=>e.id===t)}static countTokensInText(t){return t==null?t="":typeof t=="number"?t=t+"":typeof t!="string"&&(t=JSON.stringify(t)),Math.ceil(t.length/3)}countTokens(){return this.groups.reduce((t,e)=>t+e.tokenCount,0)}removeOverflow(){let t=this.countTokens(),e=this.groups.reduce((i,o)=>i+o.weight,0);for(;t>this.size;){let i=this.groups.slice().sort((n,s)=>{let a=Math.floor(n.weight/e*this.size),r=Math.floor(s.weight/e*this.size),d=n.tokenCount-a;return s.tokenCount-r-d}),o=this.removeOneItem(i);if(!o)throw new Error("Too many items in the token window that cannot be removed.");t-=o.tokenCount}}removeOneItem(t){for(let e of t){let i=e.items.findIndex(n=>!n.cannotRemove);if(i===-1)continue;let o=e.items[i];return e.items.splice(i,1),e.tokenCount-=o.tokenCount,o}return null}},Se=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:0}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=N.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+N.countTokensInText(this.separator)+this.itemPadding,t+e.tokenCount),0)}add(t){typeof t=="string"&&(t={source:"user",data:t});let e=t;e.id===void 0&&(e.id=gt()),!e.sections?.length&&typeof e.data=="string"?e.text=e.data:e.text=e.sections?.map(o=>{if(o.type==="text")return o.text||"";if(o.type==="tool_call")return`[Tool Call: ${o.toolKbName||o.toolName}] `;if(o.type==="tool_result"&&o.toolErrorResponse)return`[Tool Error: ${o.toolErrorResponse}] `}).filter(o=>!!o).join(`
|
|
11
11
|
|
|
12
|
-
`)||"";let
|
|
12
|
+
`)||"";let i=this.items.find(o=>o.id===e.id);return i?(this.tokenCount-=i.tokenCount,Object.assign(i,e),e=i):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.source===void 0&&(e.source="user"),e.sections===void 0&&(e.sections=[]),e.tokenCount=e.disabled?0:N.countTokensInText(typeof t.data=="string"?t.data:JSON.stringify(t.data))+N.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}getAllAsString(){return this.getAll().map(t=>t.text).join(this.separator)}getAll(){return this.items.filter(t=>!t.disabled)}empty(){this.items=[],this.tokenCount=0}},L=(n=>(n.Text="text",n.ToolCall="tool_call",n.ToolResult="tool_result",n.Thinking="thinking",n.Other="other",n))(L||{});import{v4 as ft}from"uuid";var ze=new m("ChatBase"),z=class{constructor(t){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let t=new N;return t.createGroup("context").setSeparator(`
|
|
13
13
|
|
|
14
|
-
`),
|
|
15
|
-
`)||"- (none)",s=
|
|
14
|
+
`),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")}getBaseURL(){if(!this.config.endpoint)return;let t=this.config.endpoint;return t.endsWith("/chat/completions")&&(t=t.substring(0,t.length-17)),t}async sendMessage(t,e){throw new Error("Not implemented")}addUserMessage(t){throw new Error("Not implemented")}addAssistantMessage(t){throw new Error("Not implemented")}addTextMessage(t,e,i){this.messageGroup.add({id:"msg-"+ft(),source:e,data:i,sections:[{type:"text",text:t}]})}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,data:t,cannotRemove:!t.canRemove,sortOrder:101,disabled:!!t.kbItem?.disabled})}findToolBySafeName(t){return this.toolGroup.getAll().find(e=>e.id==t||e.data?.kbItem?.name==t)?.data}async executeTool(t,e){if(!t)throw new Error("Tool not found");ze.debug(`Executing tool '${t.name}'`,e,t),this.config.onAIToolStart?.(t.kbItem?.name||t.name,e);let i;try{i=await t.callback(e)}catch(o){throw ze.error(`Error executing tool '${t.name}'`,o),o}return typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),i}};import{v4 as bt}from"uuid";var ke=new m("ChatGPT"),de=class extends z{addUserMessage(t){this.addTextMessage(t,"user",{role:"user",content:t||""})}addAssistantMessage(t){this.addTextMessage(t,"assistant",{role:"assistant",content:t||""})}createOpenAIClient(){return new yt({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(t,e){this.addUserMessage(t);let i=this.createOpenAIClient(),o=!0,n=[];for(;o;){let s="msg-"+bt();o=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),ke.debug("Before processing state",{messages:this.messageGroup.getAll().map(u=>u.data),tools:this.toolGroup.getAll().map(u=>u.data),context:this.contextGroup.getAll().map(u=>u.text)});let a=this.toolGroup.getAll().filter(u=>!!u?.data).map(u=>({type:"function",function:{name:u.data.name,description:u.data.description||"",parameters:{type:"object",...u.data?.params}}})),r,d;if(this.config.stream){let u=i.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:a,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let p of u){let g=u.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!g)continue;let y=this.parseMessageBlock(s,g,void 0,!0);this.config.onAIMessage?.([...n,y],!0),e?.([...n,y])}r=await u.finalMessage(),d=await u.totalUsage()}else{let u=await i.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:a,parallel_tool_calls:!0});r=u.choices[0].message,d=u.usage}r.role=="assistant"&&!r.content&&!r.tool_calls?.length&&(r.content=""),ke.debug("Message received",r);let c=this.messageGroup.add(this.parseMessageBlock(s,r,d,!1));n.push(c),await Promise.all((r.tool_calls||[]).map(async u=>{if(u.type!="function")return;let p=this.findToolBySafeName(u.function.name);try{let g=null;try{g=u.function.arguments?JSON.parse(u.function.arguments):null}catch(W){throw new Error(`The AI provided invalid JSON arguments for tool call ${u.function.name}: ${W.message}`)}let y=await this.executeTool(p,g),x=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:u.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolSuccessResponse:y,toolCallInstanceID:u.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:u.id,content:y}});n.push(x)}catch(g){let y=g?.message||"An unknown error occurred",x=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:u.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolErrorResponse:y,toolCallInstanceID:u.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:u.id,content:`Error performing tool call ${u.function.name}: ${y}`}});n.push(x)}o=!0,this.config.onAIMessage?.(n,!0),e?.(n)})),this.stats.tokensUsed+=d?.total_tokens||0}return this.config.onAIMessage?.(n,!1),e?.(n),n}parseMessageBlock(t,e,i,o){let n=[];e.reasoning&&n.push({type:"thinking",text:e.reasoning});for(let s of e.tool_calls||[]){if(s.type!="function")continue;let a=this.findToolBySafeName(s.function.name),r=null;if(s.function.arguments)try{r=JSON.parse(s.function.arguments)}catch(d){o||ke.error(`Failed to parse tool parameters for tool call ${s.function.name}:`,d)}n.push({type:"tool_call",toolName:s.function.name,toolKbID:a?.kbItem?.id,toolKbName:a?.kbItem?.name,toolCallInstanceID:s.id,toolCallHiddenInUI:a?.kbItem?.hideActionInUI,toolParameters:r})}return typeof e.content=="string"&&n.push({type:"text",text:e.content||""}),{id:t,data:e,sections:n,source:"assistant",usage:{inputTokens:i?.prompt_tokens||0,outputTokens:i?.completion_tokens||0,cachedInputTokens:0,totalTokens:(i?.prompt_tokens||0)+(i?.completion_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].data?.role=="tool";)this.messageGroup.items.shift()}};import wt from"@anthropic-ai/sdk";import{v4 as vt}from"uuid";var Be=new m("AnthropicChat"),ue=class extends z{addUserMessage(t){this.addTextMessage(t,"user",{role:"user",content:t||""})}addAssistantMessage(t){this.addTextMessage(t,"assistant",{role:"assistant",content:t||""})}async sendMessage(t,e){this.addUserMessage(t);let i=new wt({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),o=!0,n=[];for(;o;){o=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),Be.debug("Before processing state",{messages:this.messageGroup.getAll().map(c=>c.data),tools:this.toolGroup.getAll().map(c=>c.data),context:this.contextGroup.getAll().map(c=>c.text)});let s=this.toolGroup.getAll().map(c=>({name:c.data?.name||"",description:c.data?.description||"",input_schema:{...c.data?.params,type:"object"}})),a;if(this.config.stream){let c=i.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(u=>u.data),tools:s,stream:!0});c.on("streamEvent",(u,p)=>{let g=this.parseMessageBlock(p);this.config.onAIMessage?.([...n,g],!0),e?.([...n,g])});try{a=await c.finalMessage()}catch(u){throw u?.error?.error?.message?u.error.error:u}}else try{a=await i.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(c=>c.data),tools:s})}catch(c){throw c?.error?.error?.message?c.error.error:c}if(Be.debug("Message received",a),a.content?.length){let c=this.messageGroup.add(this.parseMessageBlock(a));n.push(c)}let r=[],d=[];if(await Promise.all(a.content.map(async c=>{if(c.type!="tool_use")return;let u=this.findToolBySafeName(c.name);try{let p=await this.executeTool(u,c.input);d.push({type:"tool_result",tool_use_id:c.id,content:p}),r.push({type:"tool_result",toolKbID:u?.kbItem?.id,toolKbName:u?.kbItem?.name,toolName:c.name,toolSuccessResponse:p,toolCallInstanceID:c.id,toolCallHiddenInUI:u?.kbItem?.hideActionInUI})}catch(p){let g=p?.message||"An unknown error occurred";d.push({type:"tool_result",tool_use_id:c.id,content:`Error performing tool call ${c.name}: ${g}`}),r.push({type:"tool_result",toolKbID:u?.kbItem?.id,toolKbName:u?.kbItem?.name,toolName:c.name,toolErrorResponse:g,toolCallInstanceID:c.id,toolCallHiddenInUI:u?.kbItem?.hideActionInUI})}})),d.length>0){let c=this.messageGroup.add({id:"msg-"+vt(),sections:r,data:{role:"user",content:d}});n.push(c),o=!0,this.config.onAIMessage?.(n,!0),e?.(n)}this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return this.config.onAIMessage?.(n,!1),e?.(n),n}parseMessageBlock(t){let e=[];for(let i of t.content)if(i.type=="thinking")e.push({type:"thinking",text:i.thinking||""});else if(i.type=="text")e.push({type:"text",text:i.text||""});else if(i.type=="tool_use"){let o=this.findToolBySafeName(i.name);e.push({type:"tool_call",toolName:i.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:i.input,toolCallInstanceID:i.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:t.id,data:{role:t.role,content:t.content},sections:e,source:"assistant",usage:{inputTokens:t.usage?.input_tokens||0,outputTokens:t.usage?.output_tokens||0,cachedInputTokens:t.usage?.cache_read_input_tokens||0,totalTokens:(t.usage?.input_tokens||0)+(t.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import St from"minisearch";var je=l=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,hideActionInUI:"after-complete",parameters:[{name:"query",type:"string",description:"The search query"}],action:async(t,e)=>{let i=await e.knowledgeBase.search(t.query),o=e;o._lastKBsearch=t.query,o._nextRequestUseKBitems=i;let n=i.filter(a=>a.type!="action").map(a=>"- "+a.name).join(`
|
|
15
|
+
`)||"- (none)",s=i.filter(a=>a.type=="action").map(a=>"- "+a._functionID).join(`
|
|
16
16
|
`)||"- (none)";return`Search complete, context has been updated.
|
|
17
17
|
New information found:
|
|
18
18
|
${n}
|
|
19
19
|
|
|
20
20
|
New tools available:
|
|
21
|
-
${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),o=encodeURIComponent(i.subject),n=encodeURIComponent(i.body),s=`mailto:${t}?subject=${o}&body=${n}`;try{window.location.href=s}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as je}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as vt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as xt}from"@modelcontextprotocol/sdk/client/sse.js";import{LoggingMessageNotificationSchema as Mt,ToolListChangedNotificationSchema as It}from"@modelcontextprotocol/sdk/types.js";var f=new m("MCPKnowledgeClient"),pe=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){f.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new je({name:I.name,version:I.version}),t=new vt(new URL(this.config.baseURL));return await e.connect(t),f.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new je({name:I.name,version:I.version}),o=new xt(new URL(this.config.baseURL));return await t.connect(o),f.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{f.error(`MCP client error: ${e.message}`)},i.onclose=()=>{f.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(Mt,e=>{e.params.level=="critical"?f.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?f.error(`[Server] ${e.params.data}`):e.params.level=="error"?f.error(`[Server] ${e.params.data}`):e.params.level=="warning"?f.warn(`[Server] ${e.params.data}`):e.params.level=="info"?f.info(`[Server] ${e.params.data}`):e.params.level=="debug"?f.debug(`[Server] ${e.params.data}`):f.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(It,e=>{f.debug("Tool list changed",e),this.fetchTools()}),f.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let o=await this.client.listTools({cursor:e});e=o.nextCursor;for(let n of o.tools||[])i.push(n);if(!o?.tools?.length||!e)break}let t=[];for(let o of i){let n=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:o.name,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:s=>this.performToolCall(o.name,s),disabled:n})}f.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,f.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return f.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let o;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];o=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];o=await this.performToolCall(this.config.searchToolName,{[n]:i})}else o=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(o))for(let n=0;n<o.length;n++){let s=o[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)});return e}async performToolCall(i,e){await this.connect(),f.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let o=t.content?.[0]?.text||"Unknown error";throw f.error(`Error calling tool ${i}: ${o}`),new Error(`Error calling tool ${i}: ${o}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};var G=new m("KnowledgeBase"),ke=1,he=class l{constructor(i){this._sources=[{id:"core.internal",query:async()=>Be(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${ke++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return h().knowledgeBaseSources&&(i=i.concat(h().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();G.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async d=>{try{let c=Date.now(),u=await d.query(i);return G.debug(`Source '${d.id}' took ${Date.now()-c}ms`),u||[]}catch(c){return G.warn(`Knowledge source '${d.id}' failed:`,c),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),h().knowledgeBase&&(n=n.concat(h().knowledgeBase)),n=n.filter(d=>d&&!d.disabled);for(let d=0;d<n.length;d++){let c=n[d];c.id=c.id||`temp.${d}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new Tt({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(n);let r=s.search(i).map(d=>n.find(c=>c.id==d.id));for(let d of n)d.isContext&&(r.find(c=>c.id===d.id)||r.push(d));return this.lastResults=r,y(this.ai,{event_type:"kb_search",value:r.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),G.debug("Found results:",r),r}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${ke++}`),G.debug(`Registering remote knowledge base source: ${i}`);let t=[],o=[],n=!0,s=async(r,d)=>{G.debug(`Calling remote knowledge base action: ${r.id}`);let c={type:"action",userID:this.ai.userID,actionID:r.id,parameters:d},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return a(p.updateItems||[]),p.response},a=r=>{for(let d of r){if(!d.id){G.warn("KB item skipped since it has no ID.",d);continue}let c=t.find(u=>u.id==d.id);if(c){c.name=d.name||c.name||"",c.content=d.content||c.content||"",c.disabled=d.disabled??c.disabled,c.isContext=d.isContext??c.isContext,c.parameters=d.parameters||c.parameters||[],c.tags=d.tags||c.tags,c.type=d.type||c.type;continue}t.push({...d,action:u=>s(d,u)})}};this.registerSource(e,async r=>{if(n&&o.includes(r))return t;let d={type:"search",userID:this.ai?.userID||"",query:r},c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let u=await c.json();return n=!u.noCache,o.includes(r)||o.push(r),a(u.items),t})}clone(){let i=new l(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${ke++}`);let e=new pe(i);return this.registerSource(i.id,t=>e.search(t)),e}};var z=class{constructor(i){this.messages=i}text(){return this.messages?.flatMap(i=>i.sections)?.filter(i=>i?.type=="text")?.map(i=>i?.text||"")?.filter(i=>!!i)?.join(`
|
|
21
|
+
${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!t.url||typeof t.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(t.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${t.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!t.path||typeof t.path!="string")throw new Error("Path parameter is required and must be a string.");let i=new URL(t.path,window.location.origin).pathname;return window.location.href=i,`Changed route to: ${i}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!t.email_address||typeof t.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!t.subject||typeof t.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!t.body||typeof t.body!="string")throw new Error("Body parameter is required and must be a string.");let i=encodeURIComponent(t.email_address),o=encodeURIComponent(t.subject),n=encodeURIComponent(t.body),s=`mailto:${i}?subject=${o}&body=${n}`;try{window.location.href=s}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${t.email_address}, Subject: ${t.subject}`}}];import{Client as Oe}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as xt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Mt}from"@modelcontextprotocol/sdk/client/sse.js";import{LoggingMessageNotificationSchema as It,ToolListChangedNotificationSchema as Tt}from"@modelcontextprotocol/sdk/types.js";var f=new m("MCPKnowledgeClient"),pe=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(){f.debug("Connecting to MCP client");let t=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Oe({name:I.name,version:I.version}),i=new xt(new URL(this.config.baseURL));return await e.connect(i),f.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let i=new Oe({name:I.name,version:I.version}),o=new Mt(new URL(this.config.baseURL));return await i.connect(o),f.debug("Connected with SSE mode"),i});return await this.disconnect(),this.client=t,t.onerror=e=>{f.error(`MCP client error: ${e.message}`)},t.onclose=()=>{f.debug("MCP client connection closed"),this.client=void 0},t.setNotificationHandler(It,e=>{e.params.level=="critical"?f.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?f.error(`[Server] ${e.params.data}`):e.params.level=="error"?f.error(`[Server] ${e.params.data}`):e.params.level=="warning"?f.warn(`[Server] ${e.params.data}`):e.params.level=="info"?f.info(`[Server] ${e.params.data}`):e.params.level=="debug"?f.debug(`[Server] ${e.params.data}`):f.log(`[Server] ${e.params.data}`)}),t.setNotificationHandler(Tt,e=>{f.debug("Tool list changed",e),this.fetchTools()}),f.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 o=await this.client.listTools({cursor:e});e=o.nextCursor;for(let n of o.tools||[])t.push(n);if(!o?.tools?.length||!e)break}let i=[];for(let o of t){let n=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible);i.push({id:o.name,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:s=>this.performToolCall(o.name,s),disabled:n})}f.debug(`Fetched ${t.length} tools from MCP server.`),this.tools=t,this.iwActions=i}async search(t){if(t==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),i=await this.performSearchCall(t);return e=e.concat(i),this.lastSearchQuery=t,this.lastSearchResults=e,f.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(t){let e=[];if(!this.config.searchToolName)return e;let i=this.tools.find(n=>n.name==this.config.searchToolName);if(!i)return f.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let o;if(i.inputSchema.required?.length==1){let n=i.inputSchema.required[0];o=await this.performToolCall(this.config.searchToolName,{[n]:t})}else if(i.inputSchema.properties&&Object.keys(i.inputSchema.properties).length==1){let n=Object.keys(i.inputSchema.properties)[0];o=await this.performToolCall(this.config.searchToolName,{[n]:t})}else o=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(o))for(let n=0;n<o.length;n++){let s=o[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)});return e}async performToolCall(t,e){await this.connect(),f.debug(`Performing tool call for ${t} with params:`,e),this.stats.toolsCalled+=1;let i=await this.client.callTool({name:t,arguments:e});if(i.isError){let o=i.content?.[0]?.text||"Unknown error";throw f.error(`Error calling tool ${t}: ${o}`),new Error(`Error calling tool ${t}: ${o}`)}if(Array.isArray(i.content)&&i.content.length==1&&i.content[0].type=="text")try{return JSON.parse(i.content[0].text)}catch{}return i.content||[]}};var G=new m("KnowledgeBase"),Ce=1,he=class l{constructor(t){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.ai=t,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(t=>t.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>je(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(t,e){let i=t;return typeof t=="function"&&(e=t,i=`source.${Ce++}`),this._sources.push({id:i,query:e}),i}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 this.allowGlobalConfigSources&&h().knowledgeBaseSources&&(t=t.concat(h().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(t=t.concat(this._windowSources)),t=t.filter(e=>!e.disabled),t}async search(t){G.debug(`Searching knowledge base for: ${t}`);let e=Date.now(),i=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});i.query=t,i.entries=[],i.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(i),this._windowSources=i.sources):this._windowSources=[];let n=(await Promise.all(this.sources.map(async d=>{try{let c=Date.now(),u=await d.query(t);return G.debug(`Source '${d.id}' took ${Date.now()-c}ms`),u||[]}catch(c){return G.warn(`Knowledge source '${d.id}' failed:`,c),[]}}))).flat();n=n.concat(i.entries),n=n.concat(this.manualEntries),this.allowGlobalConfigSources&&h().knowledgeBase&&(n=n.concat(h().knowledgeBase)),n=n.filter(d=>d&&!d.disabled);for(let d=0;d<n.length;d++){let c=n[d];c.id=c.id||`temp.${d}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new St({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(n);let r=s.search(t).map(d=>n.find(c=>c.id==d.id));for(let d of n)d.isContext&&(r.find(c=>c.id===d.id)||r.push(d));return this.lastResults=r,b(this.ai,{event_type:"kb_search",value:r.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),G.debug("Found results:",r),r}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${Ce++}`),G.debug(`Registering remote knowledge base source: ${t}`);let i=[],o=[],n=!0,s=async(r,d)=>{G.debug(`Calling remote knowledge base action: ${r.id}`);let c={type:"action",userID:this.ai.userID,actionID:r.id,parameters:d},u=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return a(p.updateItems||[]),p.response},a=r=>{for(let d of r){if(!d.id){G.warn("KB item skipped since it has no ID.",d);continue}let c=i.find(u=>u.id==d.id);if(c){c.name=d.name||c.name||"",c.content=d.content||c.content||"",c.disabled=d.disabled??c.disabled,c.isContext=d.isContext??c.isContext,c.parameters=d.parameters||c.parameters||[],c.tags=d.tags||c.tags,c.type=d.type||c.type;continue}i.push({...d,action:u=>s(d,u)})}};this.registerSource(e,async r=>{if(n&&o.includes(r))return i;let d={type:"search",userID:this.ai?.userID||"",query:r},c=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!c.ok)throw new Error(`HTTP Error ${c.status} ${c.statusText}`);let u=await c.json();return n=!u.noCache,o.includes(r)||o.push(r),a(u.items),i})}clone(){let t=new l(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t.ensureInternalKnowledge(),t}registerMCPSource(t){t.id||(t.id=`external.${Ce++}`);let e=new pe(t);return this.registerSource(t.id,i=>e.search(i)),e}};var B=class{constructor(t){this.messages=t}text(){return this.messages?.flatMap(t=>t.sections)?.filter(t=>t?.type=="text")?.map(t=>t?.text||"")?.filter(t=>!!t)?.join(`
|
|
22
22
|
|
|
23
|
-
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((
|
|
23
|
+
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((t,e)=>t+(e.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((t,e)=>t+(e.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((t,e)=>t+(e.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((t,e)=>t+(e.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(t=>t.sections||[])||[]}toolCalls(){return this.messages?.flatMap(t=>t.sections?.filter(e=>e.type=="tool_call")||[])||[]}toolResult(t){return this.messages?.map(e=>e.sections?.find(i=>i.type=="tool_result"&&i.toolCallInstanceID==t)).filter(e=>!!e)[0]||null}};import{v4 as _e}from"uuid";var me=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
|
|
24
24
|
|
|
25
|
-
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(
|
|
25
|
+
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}
|
|
26
26
|
|
|
27
27
|
Reply only with one of the following options:
|
|
28
|
-
${
|
|
28
|
+
${t.options.map(i=>`- "${i}"`).join(`
|
|
29
29
|
`)}
|
|
30
30
|
|
|
31
|
-
Do not include any additional text or explanations.`});return
|
|
32
|
-
You will receive some data. Extraction instructions: ${
|
|
31
|
+
Do not include any additional text or explanations.`});return t.options.includes(e)?e:t.options.find(i=>e.toLowerCase().includes(i.toLowerCase()))}async extract(t){let e=`
|
|
32
|
+
You will receive some data. Extraction instructions: ${t.instruction}
|
|
33
33
|
|
|
34
|
-
${
|
|
34
|
+
${t.allowMultiple?"Return a JSONL string only, one JSON object on each line.":"Return a valid JSON object only."}
|
|
35
35
|
|
|
36
36
|
Objects should have the following keys:
|
|
37
|
-
${
|
|
37
|
+
${t.extractions.map(o=>`- ${o.name} (${o.type}): ${o.description||"No description provided."}`).join(`
|
|
38
38
|
`)}
|
|
39
|
-
`,
|
|
40
|
-
`).map(s=>s.trim()).filter(s=>!!s.trim()),n=[];for(let s of o)try{n.push(JSON.parse(s))}catch(a){console.error("Failed to parse line as JSON:",s,a.message)}return n}else return[JSON.parse(
|
|
39
|
+
`,i=await this.instruct({...t,instruction:e});if(i=i.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),t.allowMultiple){let o=i.split(`
|
|
40
|
+
`).map(s=>s.trim()).filter(s=>!!s.trim()),n=[];for(let s of o)try{n.push(JSON.parse(s))}catch(a){console.error("Failed to parse line as JSON:",s,a.message)}return n}else return[JSON.parse(i.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",i=>{t.callback(i.detail.message)}),t.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof t.data=="string"?t.data:JSON.stringify(t.data)).then(i=>i.text())}};var ge=class{constructor(t){this.subagents=[];this.cachedSubagents={};this.ai=t}register(t){if(this.subagents.find(e=>e.id==t.id))throw new Error(`Sub-agent with ID ${t.id} already exists`);this.subagents.push(t),this.ai.knowledgeBase.registerSource("subagent:"+t.id,e=>[{type:"action",id:"ask:"+t.id,name:`Ask ${t.name||"subagent"}`,content:t.usageInstructions||`Use this tool to ask ${t.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(i,o)=>await this.runQuery(t,i.query)}])}remove(t){this.subagents=this.subagents.filter(e=>e.id!=t),this.ai.knowledgeBase.removeSource("subagent:"+t)}async runQuery(t,e){let i=t.apiKey||this.ai.apiKey,o=this.cachedSubagents[i];return o||(o=new A,await o.load(i,t.config),this.cachedSubagents[i]=o),o=o.clone(),o.knowledgeBase.allowGlobalConfigSources=!1,o.knowledgeBase.allowWindowSources=!1,t.clearExistingKnowledge&&o.knowledgeBase.reset(),t.knowledge&&o.knowledgeBase.registerSource(t.knowledge),t.onAgentLoaded&&await t.onAgentLoaded(o),(await o.sendMessage(e)).text()}};var T=new m("Main"),Ye=new Set,E=class E extends EventTarget{constructor(){super(...arguments);this.conversationID=_e();this.knowledgeBase=new he(this);this.subAgents=new ge(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new me(this);this.userID=Ee();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:E.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(e,i){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{T.debug("Loading configuration...");let o=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!o.ok)throw new Error(`Failed to load configuration: ${o.status} ${o.statusText}`);try{this.config=await o.json(),T.debug("Config loaded successfully:",this.config),i&&(this.config={...this.config,...i}),this.config&&T.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(n){T.error("Failed to parse JSON response:",n);try{let s=await o.clone().text();T.error("Raw response that failed parsing:",s)}catch{T.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${n}`)}})(),(async()=>{try{let o=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!o.ok)throw new Error(`Failed to load VAD model: ${o.status} ${o.statusText}`);this.vadModel=await o.blob()}catch(o){T.warn(`Failed to load VAD model, some features will be unavailable. ${o.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let o of this.config.knowledge||[])o.url&&o.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:o.id,searchToolName:o.mcpSearchToolName,baseURL:o.url}):o.url&&this.knowledgeBase.registerSourceFromURL(o.url);for(let o of this.config.knowledge||[])o.entries?.length&&this.knowledgeBase.registerSource(o.id,()=>o.entries||[]);if(this.config.mcpServers)for(let o of this.config.mcpServers)this.knowledgeBase.registerMCPSource(o);for(let o of this.config.subagents||[])this.subAgents.register(o);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(o){throw T.warn("Failed to load:",o),this.error=o,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:o}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:o}})),o}}setModel(e){let i=this.models.find(n=>n.id==e);if(!i)throw new Error(`Model with ID "${e}" not found.`);let o={...i.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(n,s)=>{let a=this.knowledgeBase.getCachedEntry(n);this.onAIToolStart?.(a?.id||n,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(o):i.config.providerID==="anthropic"?this.currentModel=new ue(o):this.currentModel=new de(o),this.currentModel.id=i.id,this.currentModel.metadata=i}async getContextPrefix(){let e=h().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let i=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:i}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,data:Q(`
|
|
41
41
|
# RAG search
|
|
42
42
|
Use the \`search\` tool proactively as much as possible to find missing information or tools.
|
|
43
43
|
Use the \`search\` tool when you are unsure about specific details or actions to take.
|
|
@@ -46,12 +46,12 @@ ${i.extractions.map(o=>`- ${o.name} (${o.type}): ${o.description||"No descriptio
|
|
|
46
46
|
`)}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,data:`# Knowledge Database${e.length==0?`
|
|
47
47
|
|
|
48
48
|
(no items found)`:""}`});for(let o of e)if(o.type=="info"||o.type=="tour"||o.type=="input-event"){let n=Q(o.content);this.currentModel.contextGroup.add({id:o.id,data:`## ${o.type}: ${o.name}
|
|
49
|
-
${n}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="function"?o.disabled(this):o.disabled})}else if(o.type=="action"){let n={name:o._functionID,description:Q(o.content),params:
|
|
49
|
+
${n}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="function"?o.disabled(this):o.disabled})}else if(o.type=="action"){let n={name:o._functionID,description:Q(o.content),params:We(o.parameters||[{name:"value",type:"string",description:"Input"}]),callback:s=>this.toolRunKBAction(o,s),canRemove:!o.isContext,kbItem:o};this.currentModel.registerTool(n)}else continue}processIncomingMessage(e,i){if(!i){let o=this.currentModel?.stats?.tokensUsed||0,n=e.reduce((s,a)=>s+(a.usage?.totalTokens||0),0);b(this,{event_type:"message_receive",value:n,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:o}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:i,messages:e}})),this.onAIMessage?.(e,!!i)}async sendMessage(e,i){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),Ye.has(this.conversationID)||(Ye.add(this.conversationID),b(this,{event_type:"session_start"})),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});let o=await this.currentModel.sendMessage(e),n=new B(o),s=this.currentModel.contextGroup.getAllAsString();s+=`
|
|
50
50
|
|
|
51
51
|
=== TOOLS ===
|
|
52
52
|
|
|
53
53
|
`+this.currentModel.toolGroup.getAll().map(a=>"- "+a.data?.name).join(`
|
|
54
|
-
`),this._lastSystemMsg!=s&&(this._lastSystemMsg=s,this.submitAnalyticsEvent({type:"system-msg",txt:s}));for(let a of o)for(let r of a.sections||[])if(r.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:r.text||""});else if(r.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:r.text||""});else if(r.type=="tool_call"){let d=n.toolResult(r.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:r.toolKbID||"",actionName:r.toolKbName||"",value:r.toolParameters,result:d?.toolErrorResponse||d?.toolSuccessResponse,isError:!!d?.toolErrorResponse})}else r.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return n}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let o=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:t,ai:this}}));let n=await e.action(t,this),s=Date.now()-o;return y(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:s,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,result:n}})),n}catch(n){let s=Date.now()-o;throw y(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:s,success:!1,error_message:n.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,error:n}})),n}}submitAnalyticsEvent(e){h().analytics===!1||this.config?.analytics===!1||fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(t=>{T.debug("Failed to submit analytics event:",t)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=Oe(),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/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let t of e.messages)this.currentModel.messageGroup.add(t)}clone(){let e=new A;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.knowledgeBase=this.knowledgeBase.clone(),e}get messages(){return this.currentModel?.messageGroup.items||[]}};A.version=I.version,A.builtInActionsVersion="1.0.0",T.debug(`Loaded: version=${I.version} builtInActionsVersion=${A.builtInActionsVersion}`);var B=A;var v=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(e={},t=""){this.register();let o=document.createElement(this.tagName);for(let n in e)o.setAttribute(n,e[n]);return o.onBeforeCreate(),o.innerHTML=t,o}static add(e={},t=""){this.register();let o=n=>n.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">");return`<${this.tagName} ${Object.keys(e).map(n=>`${n}="${o(e[n]+"")}"`).join(" ")}>${t}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(e,t,o){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(e,t)=>this.getAttribute(t.toString())||"",set:(e,t,o)=>(this.getAttribute(t.toString())===o||(o?this.setAttribute(t.toString(),o):this.removeAttribute(t.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(e,t)=>this._state[t],set:(e,t,o)=>(this._state[t]=o,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(e){return!!this.root?.getElementById(e)}child(e){let t=this.root?.getElementById(e);if(!t)throw new Error(`Child with ID ${e} not found`);return t}};v.observedAttributes=[],v.tagName="",v._isRegistered=!1;var _e='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var Ue='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Ke='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var U=class extends v{constructor(){super(...arguments);this.html=()=>`
|
|
54
|
+
`),this._lastSystemMsg!=s&&(this._lastSystemMsg=s,this.submitAnalyticsEvent({type:"system-msg",txt:s}));for(let a of o)for(let r of a.sections||[])if(r.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:r.text||""});else if(r.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:r.text||""});else if(r.type=="tool_call"){let d=n.toolResult(r.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:r.toolKbID||"",actionName:r.toolKbName||"",value:r.toolParameters,result:d?.toolErrorResponse||d?.toolSuccessResponse,isError:!!d?.toolErrorResponse})}else r.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return n}finally{this.isProcessing=!1}}async toolRunKBAction(e,i){let o=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:i,ai:this}}));let n=await e.action(i,this),s=Date.now()-o;return b(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:i,execution_time_ms:s,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:i,ai:this,result:n}})),n}catch(n){let s=Date.now()-o;throw b(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:i,execution_time_ms:s,success:!1,error_message:n.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:i,ai:this,error:n}})),n}}submitAnalyticsEvent(e){if(h().analytics===!1||this.config?.analytics===!1)return;let i=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(o=>{T.debug("Failed to submit analytics event:",o)});this.activeAnalyticsPromises.push(i),i.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(o=>o!==i)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=_e(),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/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let i of e.messages)this.currentModel.messageGroup.add(i)}clone(){let e=new E;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.knowledgeBase=this.knowledgeBase.clone(),e}get messages(){return this.currentModel?.messageGroup.items||[]}};E.version=I.version,E.builtInActionsVersion="1.0.0",T.debug(`Loaded: version=${I.version} builtInActionsVersion=${E.builtInActionsVersion}`);var A=E;var v=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(e={},i=""){this.register();let o=document.createElement(this.tagName);for(let n in e)o.setAttribute(n,e[n]);return o.onBeforeCreate(),o.innerHTML=i,o}static add(e={},i=""){this.register();let o=n=>n.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">");return`<${this.tagName} ${Object.keys(e).map(n=>`${n}="${o(e[n]+"")}"`).join(" ")}>${i}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(e,i,o){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(e,i)=>this.getAttribute(i.toString())||"",set:(e,i,o)=>(this.getAttribute(i.toString())===o||(o?this.setAttribute(i.toString(),o):this.removeAttribute(i.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(e,i)=>this._state[i],set:(e,i,o)=>(this._state[i]=o,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(e){return!!this.root?.getElementById(e)}child(e){let i=this.root?.getElementById(e);if(!i)throw new Error(`Child with ID ${e} not found`);return i}};v.observedAttributes=[],v.tagName="",v._isRegistered=!1;var Ke='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var Ue='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Fe='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var K=class extends v{constructor(){super(...arguments);this.html=()=>`
|
|
55
55
|
|
|
56
56
|
<!-- Styling -->
|
|
57
57
|
<style>
|
|
@@ -95,7 +95,7 @@ ${n}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
95
95
|
}
|
|
96
96
|
|
|
97
97
|
:host #loader {
|
|
98
|
-
background-image: url('${
|
|
98
|
+
background-image: url('${Ke}');
|
|
99
99
|
background-size: 64px 64px;
|
|
100
100
|
background-position: center;
|
|
101
101
|
background-repeat: no-repeat;
|
|
@@ -142,7 +142,7 @@ ${n}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
142
142
|
}
|
|
143
143
|
|
|
144
144
|
:host #cancel-speech-button {
|
|
145
|
-
background-image: url('${
|
|
145
|
+
background-image: url('${Fe}');
|
|
146
146
|
z-index: 2;
|
|
147
147
|
}
|
|
148
148
|
|
|
@@ -166,7 +166,7 @@ ${n}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
166
166
|
<!-- Loader bar -->
|
|
167
167
|
<div id='loader'></div>
|
|
168
168
|
|
|
169
|
-
`;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",e=>this.onInputKeyPress(e),{capture:!0}),this.child("input-field").addEventListener("keydown",e=>e.stopPropagation(),{capture:!0}),this.child("llm-button").addEventListener("click",e=>this.onLLMButtonClick(e)),this.child("microphone-button").addEventListener("click",e=>this.onMicButtonClick(e)),this.child("cancel-speech-button").addEventListener("click",e=>this.onCancelSpeechButtonClick(e))}connectAI(e){this.ai=e,this.ai.audio?.speechRecognition.addEventListener("speech",
|
|
169
|
+
`;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",e=>this.onInputKeyPress(e),{capture:!0}),this.child("input-field").addEventListener("keydown",e=>e.stopPropagation(),{capture:!0}),this.child("llm-button").addEventListener("click",e=>this.onLLMButtonClick(e)),this.child("microphone-button").addEventListener("click",e=>this.onMicButtonClick(e)),this.child("cancel-speech-button").addEventListener("click",e=>this.onCancelSpeechButtonClick(e))}connectAI(e){this.ai=e,this.ai.audio?.speechRecognition.addEventListener("speech",i=>this.onSpeechEvent(i)),this.ai.audio?.speechRecognition.addEventListener("start",i=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",i=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",i=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",i=>this.onUpdate()),this.onUpdate()}onUpdate(){this.attr.textColor&&document.documentElement.style.setProperty("--intelliweave-text-color",this.attr.textColor),this.child("input-field").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("llm-button").style.display=this.attr.loading||!this.attr.llmButtonVisible||this.state.micActiv?"none":"",this.child("llm-button").innerText=this.attr.llmName||"LLM",this.child("loader").style.display=this.attr.loading?"block":"",this.child("microphone-button").style.display=!this.ai?.audio?.speechRecognition?.isSupported||this.attr.loading&&!this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("cancel-speech-button").style.display="none",this.ai?.audio?.speechRecognition.isRunning&&this.ai?.audio?.speechOutput.isSpeaking&&(this.child("microphone-button").style.display="none",this.child("cancel-speech-button").style.display=""),!this.attr.loading&&this._wasLoading&&this.child("input-field").focus(),this._wasLoading=this.attr.loading,this.child("microphone-button-bg").classList.toggle("active",!!this.ai?.audio?.speechRecognition.isRunning);let e=this.ai?.audio?.speechRecognition.isRunning&&!this.attr.loading;e&&!this.micStateAnimationTimer?this.micStateAnimationTimer=setInterval(()=>this.onMicAnimation(),1e3/60):!e&&this.micStateAnimationTimer&&(this.voiceAnimationPieces.forEach(i=>i.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(e){if(e.stopPropagation(),e.key!="Enter")return;let i=this.child("input-field"),o=i.value?.trim();i.value="",o&&this.dispatchEvent(new CustomEvent("input-message",{detail:o}))}onLLMButtonClick(e){e.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onMicButtonClick(e){e.preventDefault(),this.ai.audio?.speechRecognition.isRunning?this.ai.audio?.speechRecognition.stop():this.ai.audio?.speechRecognition.start()}onMicAnimation(){if(!this.attr.loading){if(this._micAnimFrameCounter++,this._micAnimFrameCounter%5==0){let e="rgba(140, 170, 200, 0.5)";this.ai?.audio?.speechRecognition.voiceDetection?.isModelLoaded||(e="rgba(255, 0, 0, 0.5)"),this.ai?.audio?.speechRecognition.voiceDetection?.isTranscribing&&(e="rgba(96, 66, 245, 0.9)"),this.ai?.audio?.speechRecognition.wordsCurrentlyBeingSpoken&&(e="rgba(0, 128, 255, 0.9)"),this.ai?.audio?.speechRecognition.voiceDetection?.isVoicePossiblyEnding&&(e="rgba(0, 128, 255, 0.5)"),this.ai?.isProcessing&&(e="rgba(255, 255, 0, 0.5)"),this.ai?.audio?.speechOutput.isSpeaking&&(e="rgba(0, 255, 0, 0.5)");let i=this.ai?.audio?.speechRecognition.volumeLevel||0,o=30,n=6,s=Math.round(i*(o-n)+n),a=document.createElement("div");a.posX=50,a.style.cssText=`position: absolute; top: calc(50% - ${s}px/2); left: 0px; width: 6px; height: ${s}px; background-color: ${e}; border-radius: 3px; pointer-events: none; `,this.root?.appendChild(a),this.voiceAnimationPieces.push(a)}for(let e=0;e<this.voiceAnimationPieces.length;e++){let i=this.voiceAnimationPieces[e];i.posX+=2,i.style.transform=`translate(${i.posX}px, 0px)`,!(i.posX<400)&&(this.voiceAnimationPieces.splice(e--,1),i.remove())}}}onSpeechEvent(e){this.attr.loading||e.detail.isFinal&&this.dispatchEvent(new CustomEvent("input-message",{detail:e.detail.transcript}))}onCancelSpeechButtonClick(e){this.ai.audio?.speechOutput.interrupt(),this.onUpdate()}};K.observedAttributes=["loading","llmName","llmButtonVisible","textColor"];var He='data:image/svg+xml,<svg id="eLjt8NmVnoY1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 300 300" shape-rendering="geometricPrecision" text-rendering="geometricPrecision" project-id="defaf4a7213e40159eb368f9622a2af1" export-id="e0405e7e1d4a45c0a08fbbedb06a02a8" cached="false"><defs><radialGradient id="eLjt8NmVnoY6-fill" cx="0" cy="0" r="1" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-58.520001 292.985 -172.197 -34.394001 203.907 57.158)"><stop id="eLjt8NmVnoY6-fill-0" offset="0%" stop-color="%232b3d43"/><stop id="eLjt8NmVnoY6-fill-1" offset="33%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-2" offset="58%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-3" offset="100%" stop-color="%237ebf96"/></radialGradient><radialGradient id="eLjt8NmVnoY7-fill" cx="0" cy="0" r="1.112049" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(182.129 -94.016999 94.016999 182.129 43.4553 184.626)"><stop id="eLjt8NmVnoY7-fill-0" offset="0%" stop-color="%233f2d2d"/><stop id="eLjt8NmVnoY7-fill-1" offset="28%" stop-color="%23c83b35"/><stop id="eLjt8NmVnoY7-fill-2" offset="81%" stop-color="%23f69153"/><stop id="eLjt8NmVnoY7-fill-3" offset="100%" stop-color="%23ffe388"/></radialGradient><radialGradient id="eLjt8NmVnoY9-fill" cx="0" cy="0" r="593.59" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-0.196117 0.98058 -0.578542 -0.115709 406.499077 117.274778)"><stop id="eLjt8NmVnoY9-fill-0" offset="0%" stop-color="%23252d3a"/><stop id="eLjt8NmVnoY9-fill-1" offset="60%" stop-color="%23c50"/><stop id="eLjt8NmVnoY9-fill-2" offset="100%" stop-color="%23fddc85"/></radialGradient><radialGradient id="eLjt8NmVnoY10-fill" cx="0" cy="0" r="454.77" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="translate(87.33 340.7)"><stop id="eLjt8NmVnoY10-fill-0" offset="0%" stop-color="%23002936"/><stop id="eLjt8NmVnoY10-fill-1" offset="44%" stop-color="%23007aa1"/><stop id="eLjt8NmVnoY10-fill-2" offset="67%" stop-color="%2326ab7f"/><stop id="eLjt8NmVnoY10-fill-3" offset="100%" stop-color="%2395e0c8"/></radialGradient></defs><g transform="matrix(.339855 0 0 0.339855 65.056641 64.89012)"><path d="M337.93,111.85c17.31-4.12,30.6-2.15,38.55,5.96c12.9,13.16,10.13,41.58-7.64,77.95-34.66,70.98-116.01,153.37-181.35,183.6-4.15,1.92-8.16,3.6-12.02,5.03l.05.18C83.95,418.36,13.7,365.53,1.49,278.27C15.34,403.24,121.28,500.43,249.94,500.43c138.07,0,250-111.93,250-250c0-9.8-.58-19.46-1.68-28.96-12-82.27-75.81-133.5-160.33-109.62Z" fill="url(%23eLjt8NmVnoY9-fill)"/><path d="M249.94,0.43c-138.07,0-250,111.93-250,250c0,9.41.54,18.69,1.55,27.84C13.7,365.54,83.95,418.36,175.52,384.58l-.05-.18c-11.22,4.17-21.17,6.24-29.61,6.24-9.59,0-17.18-2.67-22.44-8.03-12.9-13.19-10.13-41.61,7.64-77.98c18.26-37.41,49.51-77.98,84.51-112.41c31.45-32.33,62.2-54.66,91.14-68.47.16-.08.34-.16.49-.23c1.74-.85,3.47-1.68,5.18-2.49c9.22-4.27,17.77-7.33,25.54-9.17c84.52-23.88,148.33,27.35,160.33,109.62C483.91,97.04,378.22,0.43,249.94,0.43Z" fill="url(%23eLjt8NmVnoY10-fill)"/><path d="M337.93,111.85c-7.77,1.84-16.32,4.9-25.54,9.17-1.71.8-3.45,1.63-5.18,2.49-.16.08-.34.16-.49.23-28.94,13.81-59.69,36.14-91.14,68.47-35,34.43-66.24,75-84.51,112.41-17.77,36.37-20.54,64.79-7.64,77.98c5.26,5.36,12.85,8.03,22.44,8.03c8.45,0,18.39-2.07,29.61-6.24c3.86-1.42,7.88-3.11,12.02-5.03c65.34-30.23,146.68-112.62,181.35-183.6c17.77-36.37,20.54-64.79,7.64-77.95-7.95-8.11-21.24-10.08-38.55-5.96h-.01Z" fill="%23252d3a"/></g></svg>%0D%0A';var U=class extends v{constructor(){super(...arguments);this.html=()=>`
|
|
170
170
|
|
|
171
171
|
<!-- Styling -->
|
|
172
172
|
<style>
|
|
@@ -219,7 +219,7 @@ ${n}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
219
219
|
<!-- Logo -->
|
|
220
220
|
<img id='root' />
|
|
221
221
|
|
|
222
|
-
`;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let
|
|
222
|
+
`;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let i=this.attr.logo||He;this._lastLogoSrc!=i&&(this._lastLogoSrc=i,e.src=i);let o=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(o){let n=window.visualViewport?.offsetTop||0,s=window.visualViewport?.offsetLeft||0,a=o.getBoundingClientRect();if(!a)return;e.classList.add("focused-mode"),e.style.width="128px",e.style.height="128px",e.style.left=Math.round(a.x+a.width/2-128/2+s)+"px",e.style.top=Math.round(a.y+a.height/2-128/2+n)+"px"}else e.classList.remove("focused-mode"),e.style.width="",e.style.height="",e.style.left="",e.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};U.observedAttributes=["logo","focusID"];import Je from"rehype-external-links";import Qe from"rehype-format";import $e from"rehype-stringify";import qe from"remark-parse";import et from"remark-rehype";import{unified as tt}from"unified";var F=class extends v{constructor(){super(...arguments);this.html=()=>`
|
|
223
223
|
|
|
224
224
|
<!-- Styling -->
|
|
225
225
|
<style>
|
|
@@ -302,11 +302,11 @@ ${n}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
302
302
|
<div id='llm-selector-list'></div>
|
|
303
303
|
</div>
|
|
304
304
|
|
|
305
|
-
`}onUpdate(){this.child("llm-selector-panel").className=this.attr.open?"open":"closed";let e=this.child("llm-selector-list");for(;e.lastChild;)e.lastChild.remove();for(let
|
|
306
|
-
<div class='llm-selector-item-icon' style="background-image: url('${
|
|
307
|
-
<div class='llm-selector-item-name'>${
|
|
308
|
-
<div class='llm-selector-item-provider'>${
|
|
309
|
-
`,o.addEventListener("click",n=>{this.dispatchEvent(new CustomEvent("select",{detail:
|
|
305
|
+
`}onUpdate(){this.child("llm-selector-panel").className=this.attr.open?"open":"closed";let e=this.child("llm-selector-list");for(;e.lastChild;)e.lastChild.remove();for(let i of this.state.items||[]){let o=document.createElement("div");o.className="llm-selector-item"+(i.id==this.state.selectedID?" selected":""),o.innerHTML=`
|
|
306
|
+
<div class='llm-selector-item-icon' style="background-image: url('${i.icon}'); "></div>
|
|
307
|
+
<div class='llm-selector-item-name'>${i.name}</div>
|
|
308
|
+
<div class='llm-selector-item-provider'>${i.provider}</div>
|
|
309
|
+
`,o.addEventListener("click",n=>{this.dispatchEvent(new CustomEvent("select",{detail:i.id}))}),e.appendChild(o)}}};F.observedAttributes=["open"];var w=new m("Embed"),j=class extends v{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
|
|
310
310
|
|
|
311
311
|
<!-- Styling -->
|
|
312
312
|
<style>
|
|
@@ -643,7 +643,7 @@ ${n}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
643
643
|
<div id='root' class='hidden'>
|
|
644
644
|
|
|
645
645
|
<!-- Logo -->
|
|
646
|
-
${
|
|
646
|
+
${U.add({id:"web-weaver-logo",logo:this.attr.logo})}
|
|
647
647
|
<div id='pulseanim' class="circle pulse"></div>
|
|
648
648
|
|
|
649
649
|
|
|
@@ -656,7 +656,7 @@ ${n}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
656
656
|
${F.add({id:"llm-selector-panel"})}
|
|
657
657
|
|
|
658
658
|
<!-- Interaction panel -->
|
|
659
|
-
${
|
|
659
|
+
${K.add({id:"interaction-bar"})}
|
|
660
660
|
|
|
661
661
|
|
|
662
662
|
<!-- Powered by IW banner -->
|
|
@@ -666,9 +666,9 @@ ${n}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
|
|
|
666
666
|
|
|
667
667
|
</div>
|
|
668
668
|
|
|
669
|
-
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new B,C.isSupported&&(this.ai.audio=new C(this.ai))}onCreate(){h().embed&&w.warn("Only one <web-weaver-embed> element should be on the page."),h().embed=this;let e=h();w.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(w.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.layout&&!this.attr.layout&&(w.debug("[WebWeaverEmbed] Setting layout from client config:",e.layout),this.attr.layout=e.layout),e.positioningMode&&!this.attr.positioningMode&&(w.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(w.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(w.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(w.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(w.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),w.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",n=>this.onContainerClick(n)),this.child("web-weaver-logo").addEventListener("click",n=>this.onLogoClick(n)),this.child("interaction-bar").addEventListener("input-message",n=>this.processInput(n.detail)),this.child("interaction-bar").addEventListener("llm-button-click",n=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",n=>this.onLLMModelSelect(n)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:n=>(this.suggestions.push(n.text),"Suggestion button added")});let o=this.attr.apiKey||h().apiKey;if(!o)return w.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(o).then(n=>{this.config=n.config,h().introductionMessage=this.config.introductionMessage,h().analytics=this.config.analytics!==void 0?!!this.config.analytics:h().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(n=>{w.error("Failed to load AI configuration:",n),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(e,t){if(!t){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.removeProperty("--intelliweave-interaction-bg");return}let o=this.parseColorToRGB(t);if(!o){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.setProperty("--intelliweave-interaction-bg",t);return}let{r:n,g:s,b:a}=o;e.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${n}, ${s}, ${a}, 0.65)`),e.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(n*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),e.style.setProperty("--intelliweave-interaction-bg",`rgba(${n}, ${s}, ${a}, 0.9)`)}parseColorToRGB(e){if(!e)return null;let t=e.trim();if(t.startsWith("#")){let o=t.slice(1);if(o.length===3){let n=parseInt(o[0]+o[0],16),s=parseInt(o[1]+o[1],16),a=parseInt(o[2]+o[2],16);return{r:n,g:s,b:a}}if(o.length===6){let n=parseInt(o.slice(0,2),16),s=parseInt(o.slice(2,4),16),a=parseInt(o.slice(4,6),16);return{r:n,g:s,b:a}}return null}if(t.startsWith("rgb")){let o=t.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return o?{r:Math.max(0,Math.min(255,Math.round(Number(o[1])))),g:Math.max(0,Math.min(255,Math.round(Number(o[2])))),b:Math.max(0,Math.min(255,Math.round(Number(o[3]))))}:null}return null}applyConfigStylesAndAttributes(){let e=this.config,t=this.child("root");if(!t)return;let o=!1,s=this.attr.logo||e.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,o=!0;let J=this.child("web-weaver-logo");J&&J.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),r=this.root?.getElementById("fullscreen-name"),d=e.name||"";d!==this._lastPersonaName&&(this._lastPersonaName=d,r&&(r.textContent=d),o=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),o=!0);let c=this.root?.getElementById("fullscreen-header"),u=(this.attr.header||"").toLowerCase();if(c){let J=u==="hidden"||u==="none"||u==="false";c.style.display=!J&&(s||d)?"":"none"}let g=this.attr.background||e.background;g!==this._lastBackground&&(this._lastBackground=g,o=!0,g?(t.style.background=g,t.style.setProperty("--intelliweave-persona-bg",g),this.applyPersonaColorVariants(t,g)):(t.style.background="",t.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(t,void 0)));let x=this.attr.textColor||e.textColor,E=this.child("interaction-bar");x!==this._lastTextColor&&(this._lastTextColor=x,o=!0,x?(t.style.color=x,t.style.setProperty("--intelliweave-user-bubble-text",x),t.style.setProperty("--intelliweave-assistant-bubble-text",x),E&&E.setAttribute("textColor",x)):(t.style.color="",t.style.removeProperty("--intelliweave-user-bubble-text"),t.style.removeProperty("--intelliweave-assistant-bubble-text"),E&&E.removeAttribute("textColor")));let H=this.attr.displayMode||e.displayMode||"closed";H!==this._lastDisplayMode&&(this._lastDisplayMode=H,o=!0,H==="open"&&!this.attr.open&&(this.attr.open=!0));let fe=this.attr.layout||e.layout||"widget";fe!==this._lastLayout&&(this._lastLayout=fe,o=!0);let ye=this.attr.positioningMode||e.positioningMode||"fixed";ye!==this._lastPositioningMode&&(this._lastPositioningMode=ye,o=!0);let be=this.attr.positionX||e.positionX||"right";be!==this._lastPositionX&&(this._lastPositionX=be,o=!0);let we=this.attr.positionY||e.positionY||"bottom";we!==this._lastPositionY&&(this._lastPositionY=we,o=!0);let Ne=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,ve=Ne!==void 0?Ne:e.offsetX!==void 0?e.offsetX:20;ve!==this._lastOffsetX&&(this._lastOffsetX=ve,o=!0);let Le=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,xe=Le!==void 0?Le:e.offsetY!==void 0?e.offsetY:20;xe!==this._lastOffsetY&&(this._lastOffsetY=xe,o=!0),o&&w.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:t.style.background,finalTextColor:t.style.color,finalDisplayMode:H,finalLayout:fe,finalPositioningMode:ye,finalPositionX:be,finalPositionY:we,finalOffsetX:ve,finalOffsetY:xe})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),y(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let d=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;y(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:d}})}this._previousOpenState=this.attr.open;let e=this.child("root");this.attr.open?e.classList.add("open"):e.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(e.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):e.classList.remove("layout-fullscreen");let o=this._lastPositioningMode||"fixed",n=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,r=this._lastOffsetY!==void 0?this._lastOffsetY:20;o==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),o!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",n==="left"?e.style.left=a+"px":e.style.right=a+"px",s==="top"?e.style.top=r+"px":e.style.bottom=r+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((d,c)=>(c.priority||0)-(d.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){h().embed==this&&(h().embed=void 0)}onContainerClick(e){let t=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&t!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.open=!0))}onLogoClick(e){if(e.preventDefault(),e.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let t=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||t==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=h().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let o of h().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=o,n.addEventListener("click",s=>this.onSuggestionClick(s,o)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let t=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let d of Array.from(t.querySelectorAll(".suggestion-button")))d.remove();this.attr.focusID="";let o=document.createElement("div");o.className="input",o.innerText=e,t.appendChild(o);let n=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",t.appendChild(this.currentOutputElement);let s=Math.ceil(t.clientHeight-300);s<0&&(s=0),s>600&&(s=600),n&&(n.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"});let a=await this.ai.sendMessage(e);for(let d of this.suggestions){let c=document.createElement("div");c.className="suggestion-button",c.innerText=d,c.addEventListener("click",u=>this.onSuggestionClick(u,d)),this.currentOutputElement.appendChild(c)}let r=a.text()||"";this.ai.audio?.speechRecognition?.isRunning&&this.ai.audio.speechOutput.speak(r)}catch(o){w.error("Failed to process input:",o);let n=document.createElement("div");n.className="output",n.innerText="Sorry, there was a problem getting a response. "+o.message,t.appendChild(n);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),t.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e,t){let o=[];for(let n of e)for(let s=0;s<(n.sections?.length||0);s++){let a=n.sections[s],r=`msgelem-${n.id||""}_${s}_${a.type||"unknown"}`;if(r=r.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let d=a.text||"";d.includes(`
|
|
669
|
+
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new A,C.isSupported&&(this.ai.audio=new C(this.ai))}onCreate(){h().embed&&w.warn("Only one <web-weaver-embed> element should be on the page."),h().embed=this;let e=h();w.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(w.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.layout&&!this.attr.layout&&(w.debug("[WebWeaverEmbed] Setting layout from client config:",e.layout),this.attr.layout=e.layout),e.positioningMode&&!this.attr.positioningMode&&(w.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(w.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(w.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(w.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(w.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),w.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",n=>this.onContainerClick(n)),this.child("web-weaver-logo").addEventListener("click",n=>this.onLogoClick(n)),this.child("interaction-bar").addEventListener("input-message",n=>this.processInput(n.detail)),this.child("interaction-bar").addEventListener("llm-button-click",n=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",n=>this.onLLMModelSelect(n)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:n=>(this.suggestions.push(n.text),"Suggestion button added")});let o=this.attr.apiKey||h().apiKey;if(!o)return w.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(o).then(n=>{this.config=n.config,h().introductionMessage=this.config.introductionMessage,h().analytics=this.config.analytics!==void 0?!!this.config.analytics:h().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(n=>{w.error("Failed to load AI configuration:",n),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(e,i){if(!i){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.removeProperty("--intelliweave-interaction-bg");return}let o=this.parseColorToRGB(i);if(!o){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.setProperty("--intelliweave-interaction-bg",i);return}let{r:n,g:s,b:a}=o;e.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${n}, ${s}, ${a}, 0.65)`),e.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(n*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),e.style.setProperty("--intelliweave-interaction-bg",`rgba(${n}, ${s}, ${a}, 0.9)`)}parseColorToRGB(e){if(!e)return null;let i=e.trim();if(i.startsWith("#")){let o=i.slice(1);if(o.length===3){let n=parseInt(o[0]+o[0],16),s=parseInt(o[1]+o[1],16),a=parseInt(o[2]+o[2],16);return{r:n,g:s,b:a}}if(o.length===6){let n=parseInt(o.slice(0,2),16),s=parseInt(o.slice(2,4),16),a=parseInt(o.slice(4,6),16);return{r:n,g:s,b:a}}return null}if(i.startsWith("rgb")){let o=i.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return o?{r:Math.max(0,Math.min(255,Math.round(Number(o[1])))),g:Math.max(0,Math.min(255,Math.round(Number(o[2])))),b:Math.max(0,Math.min(255,Math.round(Number(o[3]))))}:null}return null}applyConfigStylesAndAttributes(){let e=this.config,i=this.child("root");if(!i)return;let o=!1,s=this.attr.logo||e.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,o=!0;let J=this.child("web-weaver-logo");J&&J.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),r=this.root?.getElementById("fullscreen-name"),d=e.name||"";d!==this._lastPersonaName&&(this._lastPersonaName=d,r&&(r.textContent=d),o=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),o=!0);let c=this.root?.getElementById("fullscreen-header"),u=(this.attr.header||"").toLowerCase();if(c){let J=u==="hidden"||u==="none"||u==="false";c.style.display=!J&&(s||d)?"":"none"}let g=this.attr.background||e.background;g!==this._lastBackground&&(this._lastBackground=g,o=!0,g?(i.style.background=g,i.style.setProperty("--intelliweave-persona-bg",g),this.applyPersonaColorVariants(i,g)):(i.style.background="",i.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(i,void 0)));let x=this.attr.textColor||e.textColor,W=this.child("interaction-bar");x!==this._lastTextColor&&(this._lastTextColor=x,o=!0,x?(i.style.color=x,i.style.setProperty("--intelliweave-user-bubble-text",x),i.style.setProperty("--intelliweave-assistant-bubble-text",x),W&&W.setAttribute("textColor",x)):(i.style.color="",i.style.removeProperty("--intelliweave-user-bubble-text"),i.style.removeProperty("--intelliweave-assistant-bubble-text"),W&&W.removeAttribute("textColor")));let H=this.attr.displayMode||e.displayMode||"closed";H!==this._lastDisplayMode&&(this._lastDisplayMode=H,o=!0,H==="open"&&!this.attr.open&&(this.attr.open=!0));let ye=this.attr.layout||e.layout||"widget";ye!==this._lastLayout&&(this._lastLayout=ye,o=!0);let be=this.attr.positioningMode||e.positioningMode||"fixed";be!==this._lastPositioningMode&&(this._lastPositioningMode=be,o=!0);let we=this.attr.positionX||e.positionX||"right";we!==this._lastPositionX&&(this._lastPositionX=we,o=!0);let ve=this.attr.positionY||e.positionY||"bottom";ve!==this._lastPositionY&&(this._lastPositionY=ve,o=!0);let Ae=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,xe=Ae!==void 0?Ae:e.offsetX!==void 0?e.offsetX:20;xe!==this._lastOffsetX&&(this._lastOffsetX=xe,o=!0);let Le=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,Me=Le!==void 0?Le:e.offsetY!==void 0?e.offsetY:20;Me!==this._lastOffsetY&&(this._lastOffsetY=Me,o=!0),o&&w.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:i.style.background,finalTextColor:i.style.color,finalDisplayMode:H,finalLayout:ye,finalPositioningMode:be,finalPositionX:we,finalPositionY:ve,finalOffsetX:xe,finalOffsetY:Me})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),b(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let d=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;b(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:d}})}this._previousOpenState=this.attr.open;let e=this.child("root");this.attr.open?e.classList.add("open"):e.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(e.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):e.classList.remove("layout-fullscreen");let o=this._lastPositioningMode||"fixed",n=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,r=this._lastOffsetY!==void 0?this._lastOffsetY:20;o==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),o!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",n==="left"?e.style.left=a+"px":e.style.right=a+"px",s==="top"?e.style.top=r+"px":e.style.bottom=r+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((d,c)=>(c.priority||0)-(d.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){h().embed==this&&(h().embed=void 0)}onContainerClick(e){let i=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&i!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.open=!0))}onLogoClick(e){if(e.preventDefault(),e.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let i=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||i==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let i=document.createElement("div");i.className="introduction-message",i.innerHTML=h().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(i),this.ai.insertAssistantMessage(i.innerText);for(let o of h().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=o,n.addEventListener("click",s=>this.onSuggestionClick(s,o)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let i=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let d of Array.from(i.querySelectorAll(".suggestion-button")))d.remove();this.attr.focusID="";let o=document.createElement("div");o.className="input",o.innerText=e,i.appendChild(o);let n=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",i.appendChild(this.currentOutputElement);let s=Math.ceil(i.clientHeight-300);s<0&&(s=0),s>600&&(s=600),n&&(n.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"});let a=await this.ai.sendMessage(e);for(let d of this.suggestions){let c=document.createElement("div");c.className="suggestion-button",c.innerText=d,c.addEventListener("click",u=>this.onSuggestionClick(u,d)),this.currentOutputElement.appendChild(c)}let r=a.text()||"";this.ai.audio?.speechRecognition?.isRunning&&this.ai.audio.speechOutput.speak(r)}catch(o){w.error("Failed to process input:",o);let n=document.createElement("div");n.className="output",n.innerText="Sorry, there was a problem getting a response. "+o.message,i.appendChild(n);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),i.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e,i){let o=[];for(let n of e)for(let s=0;s<(n.sections?.length||0);s++){let a=n.sections[s],r=`msgelem-${n.id||""}_${s}_${a.type||"unknown"}`;if(r=r.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let d=a.text||"";d.includes(`
|
|
670
670
|
`)&&(d=d.split(`
|
|
671
|
-
`)[0]),this.updateInfoElement(r,d,"thinking-icon"),o.push(r)}else if(a.type=="tool_call"){let c=new
|
|
671
|
+
`)[0]),this.updateInfoElement(r,d,"thinking-icon"),o.push(r)}else if(a.type=="tool_call"){let c=new B(e).toolResult(a.toolCallInstanceID||"");if(a.toolCallHiddenInUI!="always"){if(c?.toolErrorResponse)this.updateInfoElement(r,"**Error:** "+c.toolErrorResponse||"","tool-icon"),o.push(r);else if(!(a.toolCallHiddenInUI=="after-complete"&&c))if(a.toolKbID=="search"){let u=a.toolParameters?.query?`**Search:** ${a.toolParameters.query}`:"**Search**";this.updateInfoElement(r,u,"tool-icon"),o.push(r)}else if(a.toolKbID?.startsWith("ask:")&&a.toolParameters?.query){let u=a.toolKbID.substring(4),g=`**Ask ${this.ai.subAgents.subagents.find(y=>y.id===u)?.name||"agent"}:** ${a.toolParameters.query}`;this.updateInfoElement(r,g,"tool-icon"),o.push(r)}else this.updateInfoElement(r,a.toolKbName||"","tool-icon"),o.push(r)}}else if(a.type!="tool_result"){if(!a.text)continue;this.updateTextElement(r,a.text||""),o.push(r)}}for(let n of Array.from(this.currentOutputElement.children))o.includes(n.id)||n.remove()}updateTextElement(e,i){let o=this.currentOutputElement.querySelector(`#${e}`);o||(o=document.createElement("div"),o.id=e,o.className="output",this.currentOutputElement.appendChild(o));let n=tt().use(qe).use(et).use(Je,{target:"_blank",rel:["noopener","noreferrer"]}).use(Qe).use($e).processSync(i||"");o.innerHTML=n.toString("utf-8")}updateInfoElement(e,i,o){let n=this.currentOutputElement.querySelector(`#${e}`);n||(n=document.createElement("div"),n.id=e,n.className="info-block",n.innerHTML=`
|
|
672
672
|
<div class='info-block-icon'></div>
|
|
673
673
|
<div class='info-block-text'></div>
|
|
674
|
-
`,this.currentOutputElement.appendChild(n));let s=
|
|
674
|
+
`,this.currentOutputElement.appendChild(n));let s=tt().use(qe).use(et).use(Je,{target:"_blank",rel:["noopener","noreferrer"]}).use(Qe).use($e).processSync(i||"");n.querySelector(".info-block-icon").className="info-block-icon "+o,n.querySelector(".info-block-text").innerHTML=s.toString("utf-8")}onSuggestionClick(e,i){this.processInput(i)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}};j.tagName="intelliweave-embed",j.observedAttributes=["logo","focusID","open","background","textColor","displayMode","layout","header","positioningMode","positionX","positionY","offsetX","offsetY"];import it,{createContext as Lt,useContext as Gt,useEffect as fe,useMemo as Et,useState as Ne}from"react";var ot=new m("React"),On=l=>typeof window>"u"?null:(j.register(),h().analytics=l.analytics??h().analytics,h().debug=l.debug??h().debug,l.context&&(h().pageSummary=l.context),l.introductionMessage&&(h().introductionMessage=l.introductionMessage),l.introductionSuggestions&&(h().introductionSuggestions=l.introductionSuggestions),l.userID&&(h().userID=l.userID),fe(()=>{let t=e=>{for(let i of l.knowledgeBase||[])e.entries.push(i);for(let i of l.sources||[])e.sources.push(i)};return document.addEventListener("webweaver_kb_search",t),()=>document.removeEventListener("webweaver_kb_search",t)},[l.knowledgeBase]),it.createElement("intelliweave-embed",{logo:l.logo,background:l.background,textColor:l.textColor,apiKey:l.apiKey,offsetX:l.offsetX||20,offsetY:l.offsetY||20,hubAPI:l.hubAPI,displayMode:l.displayMode,layout:l.layout,header:l.header,positioningMode:l.positioningMode,positionX:l.positionX,positionY:l.positionY})),nt=Lt(void 0);function _n(l){function t(){ot.debug("Creating new IntelliWeave instance for <IntelliWeaveProvider />");let i=new A;return C.isSupported&&(i.audio=new C(i)),i.load(l.apiKey),i}h().analytics=l.analytics??h().analytics,h().debug=l.debug??h().debug;let e=Et(()=>l.ai||t(),[l.ai,l.apiKey]);return fe(()=>{let i=o=>{let n=o;n.detail.isFinal&&e.sendMessage(n.detail.transcript)};return e.audio?.speechRecognition.addEventListener("speech",i),()=>{e.audio?.speechRecognition.removeEventListener("speech",i)}}),it.createElement(nt.Provider,{value:e},l.children)}function Yn(){let[l,t]=Ne(0),e=Gt(nt)||h().embed?.ai;e||ot.warn("Couldn't find IntelliWeave instance. Make sure you have <IntelliWeaveProvider /> somewhere in your scene graph, or use the <WebWeaverUI /> component.");let[,i]=Ne(!!e?.loaded),[,o]=Ne(e?.error);return fe(()=>{let n=r=>i(r.detail.ai.loaded),s=r=>o(r.detail.ai.error),a=()=>t(r=>r+1);return e?.addEventListener("load",n),e?.addEventListener("error",s),e?.addEventListener("input",a),e?.addEventListener("output",a),e?.addEventListener("toolstart",a),e?.addEventListener("tool",a),()=>{e?.removeEventListener("load",n),e?.removeEventListener("error",s),e?.removeEventListener("input",a),e?.removeEventListener("output",a),e?.removeEventListener("toolstart",a),e?.removeEventListener("tool",a)}},[e]),e}function Kn(l,t=[]){fe(()=>{let e=i=>i.sources.push({query:l});return document.addEventListener("webweaver_kb_search",e),()=>document.removeEventListener("webweaver_kb_search",e)},t)}export{ue as AnthropicChat,C as AudioSystem,se as BufferedWebSocket,z as ChatBase,de as ChatGPT,Pe as FixedBufferStream,A as IntelliWeave,B as IntelliWeaveMessageParser,_n as IntelliWeaveProvider,ae as IntelliWeaveTranscriptionNode,he as KnowledgeBase,m as Logging,pe as MCPKnowledgeClient,S as ONNXModel,ne as OpenAITranscriptionNode,D as PCMPlayerNode,X as PCMReceiverNode,Ve as Resampler,N as TokenWindow,Se as TokenWindowGroup,L as TokenWindowGroupItemSectionType,V as VoiceChunkOutputNode,P as VoiceDetectionNode,j as WebWeaverEmbed,On as WebWeaverUI,te as audioToWav,We as convertParamsToJSONSchema,Bi as floatTo16BitPCM,ji as floatTo64BitPCM,Ee as getDefaultUserID,Oi as int16ToFloat32BitPCM,h as intelliweaveConfig,k as intelliweaveGlobalThis,Vt as sseEvents,Q as trimWhitespaceInText,Yn as useIntelliWeave,Kn as useIntelliWeaveKnowledge};
|