@intelliweave/embedded 2.1.78 → 2.2.80
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/AGENTS.md +12 -0
- package/dist/component/component.d.ts +72 -1
- package/dist/component/component.js +825 -97
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.d.ts +72 -1
- package/dist/node/node.js +23 -23
- package/dist/react/react.d.ts +4 -0
- package/dist/react/react.js +781 -53
- package/dist/script-tag/script-tag.js +825 -97
- package/dist/webpack/index.d.ts +72 -1
- package/dist/webpack/index.js +777 -49
- package/package.json +1 -1
package/dist/webpack/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
import{v4 as
|
|
1
|
+
import{v4 as qe}from"uuid";function le(l){let i=(l||"").split(`
|
|
2
2
|
`);for(;i.length>0&&i[0].trim()=="";)i.shift();for(;i.length>0&&i[i.length-1].trim()=="";)i.pop();let e=1/0;for(let t of i){let n=t.match(/^\s*/)?.[0].length||0;e=Math.min(e,n)}return e>0&&e<1/0&&(i=i.map(t=>t.substring(e))),i.join(`
|
|
3
|
-
`)}var
|
|
3
|
+
`)}var Lt={};function W(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:Lt}function f(){return W().intelliweave=W().intelliweave||W().webWeaver||{},W().intelliweave}async function*yi(l){let i="",e=function*(){for(;;){let o=i.indexOf(`
|
|
4
4
|
|
|
5
|
-
`);if(o==-1)break;let s=i.slice(0,o);i=i.slice(o+2);let r={},
|
|
6
|
-
`);for(let
|
|
7
|
-
`+
|
|
5
|
+
`);if(o==-1)break;let s=i.slice(0,o);i=i.slice(o+2);let r={},a=s.split(`
|
|
6
|
+
`);for(let u of a){o=u.indexOf(": ");let d=u.slice(0,o),c=u.slice(o+2);o==-1&&(d=u,c=""),d&&(r[d]!==void 0?r[d]+=`
|
|
7
|
+
`+c:r[d]=c)}yield r}},t=new TextDecoder,n=l.getReader();for(;;){let{done:o,value:s}=await n.read();if(o)break;i+=t.decode(s,{stream:!0}),yield*e()}i+=t.decode()+`
|
|
8
8
|
|
|
9
|
-
`,yield*e()}function Fe(){if(g().userID)return g().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let a=localStorage.getItem("intelliweave.uid")||"";return a||(a=Ue(),localStorage.setItem("intelliweave.uid",a),a)}else return Ue()}function He(a){let i=a;if(i?.type=="object"&&i.properties)return a;let e={type:"object",properties:{},required:[]};if(a&&Array.isArray(a)){let t=a;for(let n of t)e.properties[n.name]={type:n.type||"string",description:n.description||""}}return e}var ne=class ne{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return ne.debug?!0:typeof window<"u"&&g().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),(...n)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...n)}};ne.debug=!1;var m=ne;var V=new m("ONNXModel"),E=class a{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,V.debug(`Model input parameters: ${i.inputNames.join(", ")}`),V.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!a.lib}static async load(i){if(!a.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(V.debug("Loading ONNX runtime"),this.onnx=await a.lib()),V.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new a(e)}makeTensor(i,e,t=0){let n=1;for(let s of e)n*=s;let o;if(i=="float32")o=new a.onnx.Tensor(new Float32Array(n),e);else if(i=="int8")o=new a.onnx.Tensor(new Int8Array(n),e);else if(i=="int16")o=new a.onnx.Tensor(new Int16Array(n),e);else if(i=="int32")o=new a.onnx.Tensor(new Int32Array(n),e);else if(i=="int64")o=new a.onnx.Tensor(new BigInt64Array(n),e);else if(i=="uint8")o=new a.onnx.Tensor(new Uint8Array(n),e);else if(i=="uint16")o=new a.onnx.Tensor(new Uint16Array(n),e);else if(i=="uint32")o=new a.onnx.Tensor(new Uint32Array(n),e);else if(i=="uint64")o=new a.onnx.Tensor(new BigUint64Array(n),e);else throw new Error(`Invalid type: ${i}`);return t!==0&&(i=="int64"||i=="uint64")?o.data.fill(BigInt(t)):t!==0&&o.data.fill(t),o}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,n=0){return this.registerConstant(i,this.makeTensor(e,t,n))}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,n,o=0){return this.registerState(i,e,this.makeTensor(t,n,o))}async run(i={}){if(this._runActive&&this.ignoreIfBusy)return V.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 n=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=n}return e}finally{this._runActive=!1}}resetState(){V.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var Je="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJz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Ttmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var kt=new m("PCMPlayerNode"),z=class extends AudioWorkletNode{constructor(e,t,n){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(!n||n!="int16"&&n!="float32")throw new Error(`Invalid format: ${n}`);this.sampleRate=t,this.format=n,this.port.onmessage=o=>this.onWorkletMessage(o),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:n})}static async registerModule(e){await e.audioWorklet.addModule(Je)}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:n,value:o}=await t.read();if(n||!o)break;this.feed(o)}}catch(t){kt.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?.()}};import{v4 as Ct}from"uuid";var L=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new We;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,n)=>t+n.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((o,s)=>{let r=Math.floor(o.weight/e*this.size),l=Math.floor(s.weight/e*this.size),d=o.tokenCount-r;return s.tokenCount-l-d}),n=this.removeOneItem(t);if(!n)throw new Error("Too many items in the token window that cannot be removed.");i-=n.tokenCount}}removeOneItem(i){for(let e of i){let t=e.items.findIndex(o=>!o.cannotRemove);if(t===-1)continue;let n=e.items[t];return e.items.splice(t,1),e.tokenCount-=n.tokenCount,n}return null}},We=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
10
|
-
`;this.itemPadding=0;this.sortFunction=(i,e)=>i.sortOrder!==e.sortOrder?i.sortOrder-e.sortOrder:i.dateAdded!==e.dateAdded?i.dateAdded-e.dateAdded:0}setItemPadding(i){return this.itemPadding=i,this.recalculateTokens(),this}sortBy(i){return this.sortFunction=i,this.items.sort(this.sortFunction),this}setSeparator(i){return this.separator==i?this:(this.separator=i,this.recalculateTokens(),this)}setWeight(i){return this.weight=i,this}recalculateTokens(){this.tokenCount=this.items.reduce((i,e)=>(e.tokenCount=
|
|
9
|
+
`,yield*e()}function et(){if(f().userID)return f().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let l=localStorage.getItem("intelliweave.uid")||"";return l||(l=qe(),localStorage.setItem("intelliweave.uid",l),l)}else return qe()}function tt(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 n of t)e.properties[n.name]={type:n.type||"string",description:n.description||""}}return e}var ce=class ce{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return ce.debug?!0:typeof window<"u"&&f().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),(...n)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...n)}};ce.debug=!1;var g=ce;var O=new g("ONNXModel"),D=class l{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,O.debug(`Model input parameters: ${i.inputNames.join(", ")}`),O.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||(O.debug("Loading ONNX runtime"),this.onnx=await l.lib()),O.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new l(e)}makeTensor(i,e,t=0){let n=1;for(let s of e)n*=s;let o;if(i=="float32")o=new l.onnx.Tensor(new Float32Array(n),e);else if(i=="int8")o=new l.onnx.Tensor(new Int8Array(n),e);else if(i=="int16")o=new l.onnx.Tensor(new Int16Array(n),e);else if(i=="int32")o=new l.onnx.Tensor(new Int32Array(n),e);else if(i=="int64")o=new l.onnx.Tensor(new BigInt64Array(n),e);else if(i=="uint8")o=new l.onnx.Tensor(new Uint8Array(n),e);else if(i=="uint16")o=new l.onnx.Tensor(new Uint16Array(n),e);else if(i=="uint32")o=new l.onnx.Tensor(new Uint32Array(n),e);else if(i=="uint64")o=new l.onnx.Tensor(new BigUint64Array(n),e);else throw new Error(`Invalid type: ${i}`);return t!==0&&(i=="int64"||i=="uint64")?o.data.fill(BigInt(t)):t!==0&&o.data.fill(t),o}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,n=0){return this.registerConstant(i,this.makeTensor(e,t,n))}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,n,o=0){return this.registerState(i,e,this.makeTensor(t,n,o))}async run(i={}){if(this._runActive&&this.ignoreIfBusy)return O.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 n=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=n}return e}finally{this._runActive=!1}}resetState(){O.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var it="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMC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bdGhpcy5jaHVua1Bvc2l0aW9uXTtyZXR1cm4gdGhpcy5jaHVua1Bvc2l0aW9uKyssdGhpcy5jaHVua1Bvc2l0aW9uPHRoaXMuY2h1bmtzWzBdLmxlbmd0aHx8KHRoaXMuY2h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var Dt=new g("PCMPlayerNode"),V=class extends AudioWorkletNode{constructor(e,t,n){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(!n||n!="int16"&&n!="float32")throw new Error(`Invalid format: ${n}`);this.sampleRate=t,this.format=n,this.port.onmessage=o=>this.onWorkletMessage(o),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:n})}static async registerModule(e){await e.audioWorklet.addModule(it)}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:n,value:o}=await t.read();if(n||!o)break;this.feed(o)}}catch(t){Dt.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?.()}};import{v4 as Wt}from"uuid";var G=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new Be;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,n)=>t+n.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((o,s)=>{let r=Math.floor(o.weight/e*this.size),a=Math.floor(s.weight/e*this.size),u=o.tokenCount-r;return s.tokenCount-a-u}),n=this.removeOneItem(t);if(!n)throw new Error("Too many items in the token window that cannot be removed.");i-=n.tokenCount}}removeOneItem(i){for(let e of i){let t=e.items.findIndex(o=>!o.cannotRemove);if(t===-1)continue;let n=e.items[t];return e.items.splice(t,1),e.tokenCount-=n.tokenCount,n}return null}},Be=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
10
|
+
`;this.itemPadding=0;this.sortFunction=(i,e)=>i.sortOrder!==e.sortOrder?i.sortOrder-e.sortOrder:i.dateAdded!==e.dateAdded?i.dateAdded-e.dateAdded:0}setItemPadding(i){return this.itemPadding=i,this.recalculateTokens(),this}sortBy(i){return this.sortFunction=i,this.items.sort(this.sortFunction),this}setSeparator(i){return this.separator==i?this:(this.separator=i,this.recalculateTokens(),this)}setWeight(i){return this.weight=i,this}recalculateTokens(){this.tokenCount=this.items.reduce((i,e)=>(e.tokenCount=G.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+G.countTokensInText(this.separator)+this.itemPadding,i+e.tokenCount),0)}add(i){typeof i=="string"&&(i={source:"user",data:i});let e=i;e.id===void 0&&(e.id=Wt()),!e.sections?.length&&typeof e.data=="string"?e.text=e.data:e.text=e.sections?.map(n=>{if(n.type==="text")return n.text||"";if(n.type==="tool_call")return`[Tool Call: ${n.toolKbName||n.toolName}] `;if(n.type==="tool_result"&&n.toolErrorResponse)return`[Tool Error: ${n.toolErrorResponse}] `}).filter(n=>!!n).join(`
|
|
11
11
|
|
|
12
|
-
`)||"";let t=this.items.find(n=>n.id===e.id);return t?(this.tokenCount-=t.tokenCount,Object.assign(t,e),e=t):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:L.countTokensInText(typeof i.data=="string"?i.data:JSON.stringify(i.data))+L.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}remove(i){let e=this.items.findIndex(t=>t.id===i);return e===-1?!1:(this.tokenCount-=this.items[e].tokenCount||0,this.items.splice(e,1),!0)}getAllAsString(){return this.getAll().map(i=>i.text).join(this.separator)}getAll(){return this.items.filter(i=>!i.disabled)}empty(){this.items=[],this.tokenCount=0}},W=(o=>(o.Text="text",o.ToolCall="tool_call",o.ToolResult="tool_result",o.Thinking="thinking",o.Other="other",o))(W||{});var S=new m("ElevenLabs");function Ge(a,i,e="pcm_24000"){let t=[],n=Date.now(),o=!1,s,r;return{stream:new ReadableStream({start:u=>{s=u,r=new WebSocket(`wss://api.elevenlabs.io/v1/text-to-speech/${i}/stream-input?inactivity_timeout=120&output_format=${e}`),r.addEventListener("open",()=>{S.debug(`[at ${Date.now()-n}ms] WebSocket connected`),r.send(JSON.stringify({text:" ","xi-api-key":a}));for(let p of t)r.send(JSON.stringify({text:p}));t.length=0}),r.addEventListener("close",()=>{S.debug(`[at ${Date.now()-n}ms] WebSocket closed`),s?.close(),o=!0}),r.addEventListener("message",p=>{let h=JSON.parse(p.data);if(h.final){r.close(),s?.close();return}if(S.debug(`[at ${Date.now()-n}ms] Message received: ${h.audio?.length||0} bytes of audio data`),!h.audio)return;let f=Uint8Array.from(atob(h.audio),y=>y.charCodeAt(0));s?.enqueue(f)})},cancel:()=>{S.debug(`[at ${Date.now()-n}ms] Stream cancelled`),r?.close(),o=!0}}),sendText:u=>{u&&(S.debug(`[at ${Date.now()-n}ms] Sending text: "${u}"`),r?.readyState===WebSocket.OPEN?r.send(JSON.stringify({text:u})):t.push(u))},endText:()=>{r?.readyState===WebSocket.OPEN?r.send(JSON.stringify({text:""})):t.push("")},get isClosed(){return o}}}function Qe(a,i="pcm_16000",e=16e3,t="vad"){let n=[],o=Date.now(),s=!1,r,l;return{stream:new ReadableStream({start:async h=>{r=h;let f=await fetch("https://api.elevenlabs.io/v1/single-use-token/realtime_scribe",{method:"POST",headers:{"xi-api-key":a}});if(!f.ok)throw new Error(`Failed to generate single-use token: ${f.status} ${f.statusText}`);let y=await f.json(),M=y.token;if(!M)throw new Error(`No token found in response: ${JSON.stringify(y)}`);l=new WebSocket(`wss://api.elevenlabs.io/v1/speech-to-text/realtime?token=${encodeURIComponent(M)}&audio_format=${i}&commit_strategy=${t}`),l.addEventListener("open",()=>{S.debug(`[at ${Date.now()-o}ms] WebSocket connected`);for(let T of n)l.send(T);n.length=0}),l.addEventListener("close",()=>{S.debug(`[at ${Date.now()-o}ms] WebSocket closed`),r?.close(),s=!0}),l.addEventListener("message",T=>{let C=JSON.parse(T.data);C.message_type=="committed_transcript"?(S.debug(`[at ${Date.now()-o}ms] Committed transcript received: "${C.text}"`),r?.enqueue(C.text)):C.error&&(S.warn(`[at ${Date.now()-o}ms] Error received: ${C.error}`),r?.error(new Error(C.error)),l?.close(),s=!0)})},cancel:()=>{S.debug(`[at ${Date.now()-o}ms] Stream cancelled`),l?.close(),s=!0}}),sendAudio:h=>{let f=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:btoa(String.fromCharCode(...new Uint8Array(h))),commit:!1,sample_rate:e});S.debug(`[at ${Date.now()-o}ms] Sending audio: ${h.byteLength} bytes`),l?.readyState===WebSocket.OPEN?l.send(f):n.push(f)},commit:()=>{let h=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:e});l?.readyState===WebSocket.OPEN?l.send(h):n.push(h)},close:()=>{S.debug("Closing connection"),l?.close(),s=!0,setTimeout(()=>{r?.close()},1e3)},get isClosed(){return s}}}var oe=new m("SpeechOutput"),$e=.5,Et=.8,se=class extends EventTarget{constructor(e){super();this.autoSpeak=!0;this.preemptiveConnection=!0;this.processedMessages=new Set;this.maxVolumeHeard=0;this._queuedText=[];this._queueActive=!1;this.ai=e,this.ai.addEventListener("output",t=>this.onOutputFromAI(t)),this.ai.audio?.speechRecognition.addEventListener("speechstart",t=>this.interrupt())}onOutputFromAI(e){let t=e.detail.messages,n=e.detail.isPartial;if(!(!this.ai?.audio?.speechRecognition.isRunning||!this.autoSpeak)){for(let o of t)if(!o.streamingInProgress&&!(!o.id||this.processedMessages.has(o.id))){this.processedMessages.add(o.id);for(let s of o.sections||[])s.type=="text"&&s.text&&this.speak(s.text)}n||this.processedMessages.clear()}}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let n of this.analyserBuffer)e+=n*n;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 oe.warn("No voice provider configured");this.ai._voiceTracker?.(`Added text to queue: ${e}`),this._queuedText.push(e),this._runQueue()}async _runQueue(){if(this._queueActive)return;let e=this._queuedText.shift();if(!e)return;this._queueActive=!0;let t=`speech-${Nt++}`;try{await this.ai.audio.beginAccess(t),await this._speakWithLock(e)}finally{this._queueActive=!1,this.ai.audio.endAccess(t)}this._queuedText.length?await this._runQueue():this.onSpeechEnd()}_getElevenLabsConnection(){let e=this._elevenLabsPrecachedConnection;return(!e||e.isClosed)&&(e=Ge(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),this.preemptiveConnection&&(this._elevenLabsPrecachedConnection=Ge(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),e}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.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Et);let n=this.ai?._voiceTracker||oe.timer(`${this.ai.config.voice.providerID} voice`);n(`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 o=new z(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",l=>{let d=l;n(`PCM stream ${d.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!d.detail.interrupted&&(this.currentPlayer=void 0)});let s=Date.now(),r=null;if(this.ai.config.voice.providerID=="openai"){let l=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"})});if(!l.ok){oe.warn(`Failed to generate voice sample: ${l.status} ${l.statusText}`);return}r=l.body}else if(this.ai.config.voice.providerID=="elevenlabs"){let l=this._getElevenLabsConnection();l.sendText(e),l.endText(),r=l.stream}else{oe.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}n(`Received response in ${Date.now()-s}ms`),this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),n("Playing PCM stream"),await o.play(r),n("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(this._queuedText=[],!this.currentPlayerVolume)return;this.ai._voiceTracker?.("Interrupted");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=$e);let n=400;e.gain.linearRampToValueAtTime(0,n/1e3),await new Promise(o=>setTimeout(o,n+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=$e)}},Nt=1;function re(a,i){let e=i.reduce((l,d)=>l+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 n=1,o=32,s=n*o/8,r=a*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,n,!0),t.setUint32(24,a,!0),t.setUint32(28,r,!0),t.setUint16(32,s,!0),t.setUint16(34,o,!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 qe="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoZSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGUpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWUsdGhpcy5vdXRwdXRCdWZ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ndGgsdFswXS5sZW5ndGgpO2ZvcihsZXQgcj0wO3I8cztyKyspaVthXVtyXS5zZXQodFswXVtyXSl9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var _=class extends AudioWorkletNode{constructor(e,t,n,o){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=n;let s=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!s.includes(n))throw new Error(`Invalid format ${n}, must be one of: ${s.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=r=>this.onWorkletMessage(r),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:n,bufferSize:o})}static async registerModule(e){await e.audioWorklet.addModule(qe)}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 Ze=16e3,ae=256,j=8,H=new m("VoiceDetectionNode"),J=class J extends _{constructor(e){super(e,Ze,"float32",ae*j);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(!J.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 Ze}get numberOfSamples(){return ae}get numberOfSampleChunks(){return j}get outputBufferSize(){return ae*j}get isModelLoaded(){return!!this.vad}async loadModel(){H.debug("Loading VAD model"),this.vad=await E.load(J.vadModelURL),this.vad.ignoreIfBusy=!0,H.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],Ze),this.vad.makeState("h","hn","float32",[2,j,64]),this.vad.makeState("c","cn","float32",[2,j,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new E.onnx.Tensor(e,[j,ae])});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 n=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>n;if(!o&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=o,o&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),H.debug("Started speaking")):o?this.lastVoiceActiveDate=Date.now():!o&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!o&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),H.debug("Stopped speaking after timeout")),!o){let s=Date.now();s>this.nextVadReset&&(this.nextVadReset=s+5e3,this.vad.resetState())}}catch(t){H.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};J.vadModelURL="";var O=J;var et=new m("VoiceChunkOutputNode"),G=class extends O{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){et.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((n,o)=>n+o.length,0);et.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 le=new m("OpenAITranscriptionNode"),ce=class extends G{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=le.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let n=re(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let s=new FormData;s.append("file",n),s.append("model","whisper-1"),s.append("response_format","text");let r=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s,signal:this.lastRequestAbortController.signal});if(!r.ok)throw new Error(`Failed to generate voice sample: ${r.status} ${r.statusText}`);t("Response received"),o=await r.text(),t("Content received: "+o),this.lastRequestAbortController=void 0}catch(s){le.error(`Failed to transcribe speech: ${s.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return le.debug("Transcription complete, but no text was found");le.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(e){}};var de=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 k=new m("IntelliWeaveTranscriptionNode"),Lt="wss://speech.intelliweave.ai/api/v1/transcribe",pe=class pe extends G{constructor(e,t){super(e);this.apiAddress=Lt;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(k.debug("Opening WebSocket connection"),this.ws=new de(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=()=>{k.debug("WebSocket connection opened")},this.ws.addEventListener("message",n=>{let o=JSON.parse(n.data);if(o.error)return k.warn("Error: "+o.error);if(o.type!="transcription")return k.warn("Invalid response type",o);if(o.streaming&&!o.final)return k.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return k.warn(`Empty transcription (${o.processingTime}ms)`);k.debug(`Transcription: ${o.text} (${o.processingTime}ms)`),this.onVoiceTranscription(o.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",n=>k.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{k.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),pe.debugExportWav){let t=re(this.sampleRate,e),n=document.createElement("a");n.href=URL.createObjectURL(t),n.download="recording.wav",n.click()}}onVoiceTranscription(e){}onSocketClose(){k.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};pe.debugExportWav=!1;var ue=pe;var Z={name:"@intelliweave/embedded",version:"2.1.78",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{v4 as Gt}from"uuid";var Zt=new m("Statistics"),Q=[];async function w(a,i){let e={...i,event_id:Gt(),event_date:new Date().toISOString(),sdk_version:Z.version,conversation_id:a?.conversationID||"",api_key:a?.apiKey||"",user_id:a?.userID||""};if(Q.push(e),!a||(await new Promise(n=>setTimeout(n,5e3)),Q.length===0))return;let t=Q.slice();Q.length=0;try{let n=await fetch(a.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){Zt.warn("Failed to submit analytics event:",n),Q.push(...t);return}}var Y=new m("ElevenLabsTranscriptionNode"),he=class extends G{constructor(e,t){super(e);this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0;let t=new Int16Array(e.length);for(let o=0;o<e.length;o++)t[o]=e[o]*32767;!this.connection||this.connection.isClosed?(this.connection?.close(),this.connection=void 0,Y.debug(`Opening connection. sampleRate: ${this.sampleRate} format=${this.format}`),this.connection=Qe(this.apiKey,"pcm_"+this.sampleRate,this.sampleRate,"manual"),this.startReading(this.connection),this.connection.sendAudio(t.buffer)):this.connection.sendAudio(t.buffer);let n=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{Y.debug("Shutting down WebSocket connection"),this.connection?.close(),this.connection=void 0},n)}async startReading(e){let t=e.stream.getReader();try{for(;;){let{value:n,done:o}=await t.read();if(o){Y.debug("Stream closed");break}if(!n?.trim()){Y.warn("Empty transcription received");continue}this.isTranscribing=!1,Y.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}}catch(n){Y.error(`Failed to read transcription stream: ${n.message}`),this.connection==e&&(this.connection=void 0);return}}async onVoiceEnd(e){this.connection?.commit()}onVoiceTranscription(e){}};var De=new m("SpeechRecognition"),me=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e}get isSupported(){if(!E.lib||!this.ai?.vadModel||!A().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey)){if(!(this.ai?.config?.transcription?.providerID=="elevenlabs"&&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),O.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new ce(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):this.ai?.config?.transcription?.providerID=="elevenlabs"?(this.voiceDetection=new he(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new ue(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=De.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),w(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 n=this.recordingStartTime?Date.now()-this.recordingStartTime:0;w(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:n}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),w(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){De.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 n of this.analyserBuffer)e+=n*n;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;De.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 ge=new m("AudioSystem"),D=class a{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 me(this.ai),this.speechOutput=new se(this.ai)}static get isSupported(){return!(!E.lib||!A().AudioWorkletNode)}static async registerModules(i){await Promise.all([z.registerModule(i),_.registerModule(i)])}async beginAccess(i){ge.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(ge.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await a.registerModules(this.context))}endAccess(i){ge.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(ge.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var tt=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 n=e.length-t,o=this.partialBuffers[0],s=o.length-this.partialBufferOffset;s<n?(e.set(o.subarray(this.partialBufferOffset),t),t+=s,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+n),t),t+=n,this.partialBufferOffset+=n)}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 it=class{constructor(i,e,t,n){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=n,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,n,o,s,r,l,d,c,u,p;if(e%t!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(n=this.outputBufferSize,o=this.ratioWeight,s=this.lastWeight,r=0,l=0,d=0,c=0,u=this.outputBuffer;s<1;s+=o)for(l=s%1,r=1-l,this.lastWeight=s%1,p=0;p<this.channels;++p)u[c++]=this.lastOutput[p]*r+i[p]*l;for(s-=1,e-=t,d=Math.floor(s)*t;c<n&&d<e;){for(l=s%1,r=1-l,p=0;p<this.channels;++p)u[c++]=i[d+(p>0?p:0)]*r+i[d+(t+p)]*l;s+=o,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,n,o=this.channels,s,r,l,d,c,u,p,h,f;if(e%o!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(t=this.outputBufferSize,n=[],s=this.ratioWeight,r=0,d=0,c=0,u=!this.tailExists,this.tailExists=!1,p=this.outputBuffer,h=0,f=0,l=0;l<o;++l)n[l]=0;do{if(u)for(r=s,l=0;l<o;++l)n[l]=0;else{for(r=this.lastWeight,l=0;l<o;++l)n[l]=this.lastOutput[l];u=!0}for(;r>0&&d<e;)if(c=1+d-f,r>=c){for(l=0;l<o;++l)n[l]+=i[d++]*c;f=d,r-=c}else{for(l=0;l<o;++l)n[l]+=i[d+(l>0?l:0)]*r;f+=r,r=0;break}if(r===0)for(l=0;l<o;++l)p[h++]=n[l]/s;else{for(this.lastWeight=r,l=0;l<o;++l)this.lastOutput[l]=n[l];this.tailExists=!0;break}}while(d<e&&h<t);return this.bufferSlice(h)}}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 En(a){let i=a.length,e=new Int16Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,a[i]));e[i]=t<0?t*32768:t*32767}return e}function Nn(a){let i=a.length,e=new BigInt64Array(i);for(;i--;){let t=Math.max(-1,Math.min(1,a[i]));e[i]=BigInt(Math.floor(t<0?t*32768:t*32767))*0x100000000000n}return e}function An(a){let i=a.length,e=new Float32Array(i);for(;i--;){let t=a[i];e[i]=t>=32768?-(65536-t)/32768:t/32767}return e}import Rt from"openai";import{v4 as Dt}from"uuid";var nt=new m("ChatBase"),K=class{constructor(i){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let i=new L;return i.createGroup("context").setSeparator(`
|
|
12
|
+
`)||"";let t=this.items.find(n=>n.id===e.id);return t?(this.tokenCount-=t.tokenCount,Object.assign(t,e),e=t):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:G.countTokensInText(typeof i.data=="string"?i.data:JSON.stringify(i.data))+G.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}remove(i){let e=this.items.findIndex(t=>t.id===i);return e===-1?!1:(this.tokenCount-=this.items[e].tokenCount||0,this.items.splice(e,1),!0)}getAllAsString(){return this.getAll().map(i=>i.text).join(this.separator)}getAll(){return this.items.filter(i=>!i.disabled)}empty(){this.items=[],this.tokenCount=0}},Z=(o=>(o.Text="text",o.ToolCall="tool_call",o.ToolResult="tool_result",o.Thinking="thinking",o.Other="other",o))(Z||{});var E=new g("ElevenLabs");function je(l,i,e="pcm_24000"){let t=[],n=Date.now(),o=!1,s,r;return{stream:new ReadableStream({start:c=>{s=c,r=new WebSocket(`wss://api.elevenlabs.io/v1/text-to-speech/${i}/stream-input?inactivity_timeout=120&output_format=${e}`),r.addEventListener("open",()=>{E.debug(`[at ${Date.now()-n}ms] WebSocket connected`),r.send(JSON.stringify({text:" ","xi-api-key":l}));for(let p of t)r.send(JSON.stringify({text:p}));t.length=0}),r.addEventListener("close",()=>{E.debug(`[at ${Date.now()-n}ms] WebSocket closed`),s?.close(),o=!0}),r.addEventListener("message",p=>{let h=JSON.parse(p.data);if(h.final){r.close(),s?.close();return}if(E.debug(`[at ${Date.now()-n}ms] Message received: ${h.audio?.length||0} bytes of audio data`),!h.audio)return;let m=Uint8Array.from(atob(h.audio),b=>b.charCodeAt(0));s?.enqueue(m)})},cancel:()=>{E.debug(`[at ${Date.now()-n}ms] Stream cancelled`),r?.close(),o=!0}}),sendText:c=>{c&&(E.debug(`[at ${Date.now()-n}ms] Sending text: "${c}"`),r?.readyState===WebSocket.OPEN?r.send(JSON.stringify({text:c})):t.push(c))},endText:()=>{r?.readyState===WebSocket.OPEN?r.send(JSON.stringify({text:""})):t.push("")},get isClosed(){return o}}}function nt(l,i="pcm_16000",e=16e3,t="vad"){let n=[],o=Date.now(),s=!1,r,a;return{stream:new ReadableStream({start:async h=>{r=h;let m=await fetch("https://api.elevenlabs.io/v1/single-use-token/realtime_scribe",{method:"POST",headers:{"xi-api-key":l}});if(!m.ok)throw new Error(`Failed to generate single-use token: ${m.status} ${m.statusText}`);let b=await m.json(),y=b.token;if(!y)throw new Error(`No token found in response: ${JSON.stringify(b)}`);a=new WebSocket(`wss://api.elevenlabs.io/v1/speech-to-text/realtime?token=${encodeURIComponent(y)}&audio_format=${i}&commit_strategy=${t}`),a.addEventListener("open",()=>{E.debug(`[at ${Date.now()-o}ms] WebSocket connected`);for(let v of n)a.send(v);n.length=0}),a.addEventListener("close",()=>{E.debug(`[at ${Date.now()-o}ms] WebSocket closed`),r?.close(),s=!0}),a.addEventListener("message",v=>{let A=JSON.parse(v.data);A.message_type=="committed_transcript"?(E.debug(`[at ${Date.now()-o}ms] Committed transcript received: "${A.text}"`),r?.enqueue(A.text)):A.error&&(E.warn(`[at ${Date.now()-o}ms] Error received: ${A.error}`),r?.error(new Error(A.error)),a?.close(),s=!0)})},cancel:()=>{E.debug(`[at ${Date.now()-o}ms] Stream cancelled`),a?.close(),s=!0}}),sendAudio:h=>{let m=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:btoa(String.fromCharCode(...new Uint8Array(h))),commit:!1,sample_rate:e});E.debug(`[at ${Date.now()-o}ms] Sending audio: ${h.byteLength} bytes`),a?.readyState===WebSocket.OPEN?a.send(m):n.push(m)},commit:()=>{let h=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:e});a?.readyState===WebSocket.OPEN?a.send(h):n.push(h)},close:()=>{E.debug("Closing connection"),a?.close(),s=!0,setTimeout(()=>{r?.close()},1e3)},get isClosed(){return s}}}var de=new g("SpeechOutput"),ot=.5,Gt=.8,ue=class extends EventTarget{constructor(e){super();this.autoSpeak=!0;this.preemptiveConnection=!0;this.processedMessages=new Set;this.maxVolumeHeard=0;this._queuedText=[];this._queueActive=!1;this.ai=e,this.ai.addEventListener("output",t=>this.onOutputFromAI(t)),this.ai.audio?.speechRecognition.addEventListener("speechstart",t=>this.interrupt())}onOutputFromAI(e){let t=e.detail.messages,n=e.detail.isPartial;if(!(!this.ai?.audio?.speechRecognition.isRunning||!this.autoSpeak)){for(let o of t)if(!o.streamingInProgress&&!(!o.id||this.processedMessages.has(o.id))){this.processedMessages.add(o.id);for(let s of o.sections||[])s.type=="text"&&s.text&&this.speak(s.text)}n||this.processedMessages.clear()}}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let n of this.analyserBuffer)e+=n*n;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 de.warn("No voice provider configured");this.ai._voiceTracker?.(`Added text to queue: ${e}`),this._queuedText.push(e),this._runQueue()}async _runQueue(){if(this._queueActive)return;let e=this._queuedText.shift();if(!e)return;this._queueActive=!0;let t=`speech-${Zt++}`;try{await this.ai.audio.beginAccess(t),await this._speakWithLock(e)}finally{this._queueActive=!1,this.ai.audio.endAccess(t)}this._queuedText.length?await this._runQueue():this.onSpeechEnd()}_getElevenLabsConnection(){let e=this._elevenLabsPrecachedConnection;return(!e||e.isClosed)&&(e=je(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),this.preemptiveConnection&&(this._elevenLabsPrecachedConnection=je(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),e}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.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Gt);let n=this.ai?._voiceTracker||de.timer(`${this.ai.config.voice.providerID} voice`);n(`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 o=new V(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",a=>{let u=a;n(`PCM stream ${u.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!u.detail.interrupted&&(this.currentPlayer=void 0)});let s=Date.now(),r=null;if(this.ai.config.voice.providerID=="openai"){let a=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"})});if(!a.ok){de.warn(`Failed to generate voice sample: ${a.status} ${a.statusText}`);return}r=a.body}else if(this.ai.config.voice.providerID=="elevenlabs"){let a=this._getElevenLabsConnection();a.sendText(e),a.endText(),r=a.stream}else{de.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}n(`Received response in ${Date.now()-s}ms`),this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),n("Playing PCM stream"),await o.play(r),n("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(this._queuedText=[],!this.currentPlayerVolume)return;this.ai._voiceTracker?.("Interrupted");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=ot);let n=400;e.gain.linearRampToValueAtTime(0,n/1e3),await new Promise(o=>setTimeout(o,n+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=ot)}},Zt=1;function pe(l,i){let e=i.reduce((a,u)=>a+u.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 n=1,o=32,s=n*o/8,r=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,n,!0),t.setUint32(24,l,!0),t.setUint32(28,r,!0),t.setUint16(32,s,!0),t.setUint16(34,o,!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 st="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoZSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGUpfWNhdGNoe3RyeXt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b3IobGV0IGE9MDthPGkubGVuZ3RoO2ErKyl7bGV0IHM9TWF0aC5taW4oaVthXS5sZW5ndGgsdFswXS5sZW5ndGgpO2ZvcihsZXQgcj0wO3I8cztyKyspaVthXVtyXS5zZXQodFswXVtyXSl9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Y=class extends AudioWorkletNode{constructor(e,t,n,o){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=n;let s=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!s.includes(n))throw new Error(`Invalid format ${n}, must be one of: ${s.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=r=>this.onWorkletMessage(r),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:n,bufferSize:o})}static async registerModule(e){await e.audioWorklet.addModule(st)}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 _e=16e3,he=256,F=8,ee=new g("VoiceDetectionNode"),te=class te extends Y{constructor(e){super(e,_e,"float32",he*F);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(!te.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 _e}get numberOfSamples(){return he}get numberOfSampleChunks(){return F}get outputBufferSize(){return he*F}get isModelLoaded(){return!!this.vad}async loadModel(){ee.debug("Loading VAD model"),this.vad=await D.load(te.vadModelURL),this.vad.ignoreIfBusy=!0,ee.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],_e),this.vad.makeState("h","hn","float32",[2,F,64]),this.vad.makeState("c","cn","float32",[2,F,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new D.onnx.Tensor(e,[F,he])});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 n=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>n;if(!o&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=o,o&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),ee.debug("Started speaking")):o?this.lastVoiceActiveDate=Date.now():!o&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!o&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),ee.debug("Stopped speaking after timeout")),!o){let s=Date.now();s>this.nextVadReset&&(this.nextVadReset=s+5e3,this.vad.resetState())}}catch(t){ee.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};te.vadModelURL="";var U=te;var rt=new g("VoiceChunkOutputNode"),P=class extends U{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){rt.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((n,o)=>n+o.length,0);rt.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 me=new g("OpenAITranscriptionNode"),ge=class extends P{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=me.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let n=pe(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let s=new FormData;s.append("file",n),s.append("model","whisper-1"),s.append("response_format","text");let r=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s,signal:this.lastRequestAbortController.signal});if(!r.ok)throw new Error(`Failed to generate voice sample: ${r.status} ${r.statusText}`);t("Response received"),o=await r.text(),t("Content received: "+o),this.lastRequestAbortController=void 0}catch(s){me.error(`Failed to transcribe speech: ${s.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return me.debug("Transcription complete, but no text was found");me.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(e){}};var fe=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 L=new g("IntelliWeaveTranscriptionNode"),Xt="wss://speech.intelliweave.ai/api/v1/transcribe",ye=class ye extends P{constructor(e,t){super(e);this.apiAddress=Xt;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(L.debug("Opening WebSocket connection"),this.ws=new fe(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=()=>{L.debug("WebSocket connection opened")},this.ws.addEventListener("message",n=>{let o=JSON.parse(n.data);if(o.error)return L.warn("Error: "+o.error);if(o.type!="transcription")return L.warn("Invalid response type",o);if(o.streaming&&!o.final)return L.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return L.warn(`Empty transcription (${o.processingTime}ms)`);L.debug(`Transcription: ${o.text} (${o.processingTime}ms)`),this.onVoiceTranscription(o.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",n=>L.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{L.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),ye.debugExportWav){let t=pe(this.sampleRate,e),n=document.createElement("a");n.href=URL.createObjectURL(t),n.download="recording.wav",n.click()}}onVoiceTranscription(e){}onSocketClose(){L.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};ye.debugExportWav=!1;var be=ye;var X={name:"@intelliweave/embedded",version:"2.2.80",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{v4 as Bt}from"uuid";var jt=new g("Statistics"),ie=[];async function I(l,i){let e={...i,event_id:Bt(),event_date:new Date().toISOString(),sdk_version:X.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(ie.push(e),!l||(await new Promise(n=>setTimeout(n,5e3)),ie.length===0))return;let t=ie.slice();ie.length=0;try{let n=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){jt.warn("Failed to submit analytics event:",n),ie.push(...t);return}}var K=new g("ElevenLabsTranscriptionNode"),we=class extends P{constructor(e,t){super(e);this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0;let t=new Int16Array(e.length);for(let o=0;o<e.length;o++)t[o]=e[o]*32767;!this.connection||this.connection.isClosed?(this.connection?.close(),this.connection=void 0,K.debug(`Opening connection. sampleRate: ${this.sampleRate} format=${this.format}`),this.connection=nt(this.apiKey,"pcm_"+this.sampleRate,this.sampleRate,"manual"),this.startReading(this.connection),this.connection.sendAudio(t.buffer)):this.connection.sendAudio(t.buffer);let n=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{K.debug("Shutting down WebSocket connection"),this.connection?.close(),this.connection=void 0},n)}async startReading(e){let t=e.stream.getReader();try{for(;;){let{value:n,done:o}=await t.read();if(o){K.debug("Stream closed");break}if(!n?.trim()){K.warn("Empty transcription received");continue}this.isTranscribing=!1,K.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}}catch(n){K.error(`Failed to read transcription stream: ${n.message}`),this.connection==e&&(this.connection=void 0);return}}async onVoiceEnd(e){this.connection?.commit()}onVoiceTranscription(e){}};var ze=new g("SpeechRecognition"),ve=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e}get isSupported(){if(!D.lib||!this.ai?.vadModel||!W().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey)){if(!(this.ai?.config?.transcription?.providerID=="elevenlabs"&&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),U.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new ge(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):this.ai?.config?.transcription?.providerID=="elevenlabs"?(this.voiceDetection=new we(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new be(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=ze.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),I(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 n=this.recordingStartTime?Date.now()-this.recordingStartTime:0;I(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:n}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),I(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){ze.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 n of this.analyserBuffer)e+=n*n;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;ze.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 xe=new g("AudioSystem"),R=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 ve(this.ai),this.speechOutput=new ue(this.ai)}static get isSupported(){return!(!D.lib||!W().AudioWorkletNode)}static async registerModules(i){await Promise.all([V.registerModule(i),Y.registerModule(i)])}async beginAccess(i){xe.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(xe.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await l.registerModules(this.context))}endAccess(i){xe.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(xe.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var at=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 n=e.length-t,o=this.partialBuffers[0],s=o.length-this.partialBufferOffset;s<n?(e.set(o.subarray(this.partialBufferOffset),t),t+=s,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+n),t),t+=n,this.partialBufferOffset+=n)}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 lt=class{constructor(i,e,t,n){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=n,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,n,o,s,r,a,u,d,c,p;if(e%t!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(n=this.outputBufferSize,o=this.ratioWeight,s=this.lastWeight,r=0,a=0,u=0,d=0,c=this.outputBuffer;s<1;s+=o)for(a=s%1,r=1-a,this.lastWeight=s%1,p=0;p<this.channels;++p)c[d++]=this.lastOutput[p]*r+i[p]*a;for(s-=1,e-=t,u=Math.floor(s)*t;d<n&&u<e;){for(a=s%1,r=1-a,p=0;p<this.channels;++p)c[d++]=i[u+(p>0?p:0)]*r+i[u+(t+p)]*a;s+=o,u=Math.floor(s)*t}for(p=0;p<t;++p)this.lastOutput[p]=i[u++];return this.bufferSlice(d)}}multiTap(){this.resampler=i=>{let e=i.length,t,n,o=this.channels,s,r,a,u,d,c,p,h,m;if(e%o!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(t=this.outputBufferSize,n=[],s=this.ratioWeight,r=0,u=0,d=0,c=!this.tailExists,this.tailExists=!1,p=this.outputBuffer,h=0,m=0,a=0;a<o;++a)n[a]=0;do{if(c)for(r=s,a=0;a<o;++a)n[a]=0;else{for(r=this.lastWeight,a=0;a<o;++a)n[a]=this.lastOutput[a];c=!0}for(;r>0&&u<e;)if(d=1+u-m,r>=d){for(a=0;a<o;++a)n[a]+=i[u++]*d;m=u,r-=d}else{for(a=0;a<o;++a)n[a]+=i[u+(a>0?a:0)]*r;m+=r,r=0;break}if(r===0)for(a=0;a<o;++a)p[h++]=n[a]/s;else{for(this.lastWeight=r,a=0;a<o;++a)this.lastOutput[a]=n[a];this.tailExists=!0;break}}while(u<e&&h<t);return this.bufferSlice(h)}}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 Zn(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 Pn(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 Xn(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 zt from"openai";import{v4 as _t}from"uuid";var ct=new g("ChatBase"),H=class{constructor(i){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let i=new G;return i.createGroup("context").setSeparator(`
|
|
13
13
|
|
|
14
|
-
`),i.createGroup("actions").setItemPadding(25),i.createGroup("messages").setItemPadding(10),i})();this.config=i,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}getBaseURL(){if(!this.config.endpoint)return;let i=this.config.endpoint;return i.endsWith("/chat/completions")&&(i=i.substring(0,i.length-17)),i}async sendMessage(i,e){throw new Error("Not implemented")}addUserMessage(i){throw new Error("Not implemented")}addAssistantMessage(i){throw new Error("Not implemented")}addTextMessage(i,e,t){this.messageGroup.add({id:"msg-"+
|
|
14
|
+
`),i.createGroup("actions").setItemPadding(25),i.createGroup("messages").setItemPadding(10),i})();this.config=i,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}getBaseURL(){if(!this.config.endpoint)return;let i=this.config.endpoint;return i.endsWith("/chat/completions")&&(i=i.substring(0,i.length-17)),i}async sendMessage(i,e){throw new Error("Not implemented")}addUserMessage(i){throw new Error("Not implemented")}addAssistantMessage(i){throw new Error("Not implemented")}addTextMessage(i,e,t){this.messageGroup.add({id:"msg-"+_t(),source:e,data:t,sections:[{type:"text",text:i}]})}onBeforeIncomingMessage(i){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(i){return this.toolGroup.add({id:i.name,data:i,cannotRemove:!i.canRemove,sortOrder:101,disabled:!!i.kbItem?.disabled})}findToolBySafeName(i){return this.toolGroup.getAll().find(e=>e.id==i||e.data?.kbItem?.name==i)?.data}async executeTool(i,e){if(!i)throw new Error("Tool not found");ct.debug(`Executing tool '${i.name}'`,e,i),this.config.onAIToolStart?.(i.kbItem?.name||i.name,e);let t;try{t=await i.callback(e)}catch(n){throw ct.error(`Error executing tool '${i.name}'`,n),n}return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),t}};import{v4 as Ot}from"uuid";var Oe=new g("ChatGPT"),Me=class extends H{addUserMessage(i){this.addTextMessage(i,"user",{role:"user",content:i||""})}addAssistantMessage(i){this.addTextMessage(i,"assistant",{role:"assistant",content:i||""})}createOpenAIClient(){return new zt({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(i,e){this.addUserMessage(i);let t=this.createOpenAIClient(),n=!0,o=[];for(;n;){let s="msg-"+Ot();n=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),Oe.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 r=this.toolGroup.getAll().filter(c=>!!c?.data).map(c=>({type:"function",function:{name:c.data.name,description:c.data.description||"",parameters:{type:"object",...c.data?.params}}})),a,u;if(this.config.stream){let c=t.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:r,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let p of c){let h=c.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!h)continue;let m=this.parseMessageBlock(s,h,void 0,!0);this.config.onAIMessage?.([...o,m],!0),e?.([...o,m])}a=await c.finalMessage(),u=await c.totalUsage()}else{let c=await t.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:r,parallel_tool_calls:!0});a=c.choices[0].message,u=c.usage}a.role=="assistant"&&!a.content&&!a.tool_calls?.length&&(a.content=""),Oe.debug("Message received",a);let d=this.messageGroup.add(this.parseMessageBlock(s,a,u,!1));o.push(d),await Promise.all((a.tool_calls||[]).map(async c=>{if(c.type!="function")return;let p=this.findToolBySafeName(c.function.name);try{let h=null;try{h=c.function.arguments?JSON.parse(c.function.arguments):null}catch(y){throw new Error(`The AI provided invalid JSON arguments for tool call ${c.function.name}: ${y.message}`)}let m=await this.executeTool(p,h),b=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:c.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolSuccessResponse:m,toolCallInstanceID:c.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:c.id,content:m}});o.push(b)}catch(h){let m=h?.message||"An unknown error occurred",b=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:c.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolErrorResponse:m,toolCallInstanceID:c.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:c.id,content:`Error performing tool call ${c.function.name}: ${m}`}});o.push(b)}n=!0,this.config.onAIMessage?.(o,!0),e?.(o)})),this.stats.tokensUsed+=u?.total_tokens||0}return this.config.onAIMessage?.(o,!1),e?.(o),o}parseMessageBlock(i,e,t,n){let o=[];e.reasoning&&o.push({type:"thinking",text:e.reasoning});for(let s of e.tool_calls||[]){if(s.type!="function")continue;let r=this.findToolBySafeName(s.function.name),a=null;if(s.function.arguments)try{a=JSON.parse(s.function.arguments)}catch(u){n||Oe.error(`Failed to parse tool parameters for tool call ${s.function.name}:`,u)}o.push({type:"tool_call",toolName:s.function.name,toolKbID:r?.kbItem?.id,toolKbName:r?.kbItem?.name,toolCallInstanceID:s.id,toolCallHiddenInUI:r?.kbItem?.hideActionInUI,toolParameters:a})}return typeof e.content=="string"&&o.push({type:"text",text:e.content||""}),{id:i,data:e,sections:o,source:"assistant",streamingInProgress:n,usage:{inputTokens:t?.prompt_tokens||0,outputTokens:t?.completion_tokens||0,cachedInputTokens:0,totalTokens:(t?.prompt_tokens||0)+(t?.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 Vt from"@anthropic-ai/sdk";import{v4 as Yt}from"uuid";var dt=new g("AnthropicChat"),Ie=class extends H{addUserMessage(i){this.addTextMessage(i,"user",{role:"user",content:i||""})}addAssistantMessage(i){this.addTextMessage(i,"assistant",{role:"assistant",content:i||""})}async sendMessage(i,e){this.addUserMessage(i);let t=new Vt({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),n=!0,o=[];for(;n;){n=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),dt.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.data),tools:this.toolGroup.getAll().map(d=>d.data),context:this.contextGroup.getAll().map(d=>d.text)});let s=this.toolGroup.getAll().map(d=>({name:d.data?.name||"",description:d.data?.description||"",input_schema:{...d.data?.params,type:"object"}})),r;if(this.config.stream){let d=t.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(c=>c.data),tools:s,stream:!0});d.on("streamEvent",(c,p)=>{let h=this.parseMessageBlock(p,!0);this.config.onAIMessage?.([...o,h],!0),e?.([...o,h])});try{r=await d.finalMessage()}catch(c){throw c?.error?.error?.message?c.error.error:c}}else try{r=await t.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(d=>d.data),tools:s})}catch(d){throw d?.error?.error?.message?d.error.error:d}if(dt.debug("Message received",r),r.content?.length){let d=this.messageGroup.add(this.parseMessageBlock(r,!1));o.push(d)}let a=[],u=[];if(await Promise.all(r.content.map(async d=>{if(d.type!="tool_use")return;let c=this.findToolBySafeName(d.name);try{let p=await this.executeTool(c,d.input);u.push({type:"tool_result",tool_use_id:d.id,content:p}),a.push({type:"tool_result",toolKbID:c?.kbItem?.id,toolKbName:c?.kbItem?.name,toolName:d.name,toolSuccessResponse:p,toolCallInstanceID:d.id,toolCallHiddenInUI:c?.kbItem?.hideActionInUI})}catch(p){let h=p?.message||"An unknown error occurred";u.push({type:"tool_result",tool_use_id:d.id,content:`Error performing tool call ${d.name}: ${h}`}),a.push({type:"tool_result",toolKbID:c?.kbItem?.id,toolKbName:c?.kbItem?.name,toolName:d.name,toolErrorResponse:h,toolCallInstanceID:d.id,toolCallHiddenInUI:c?.kbItem?.hideActionInUI})}})),u.length>0){let d=this.messageGroup.add({id:"msg-"+Yt(),sections:a,data:{role:"user",content:u}});o.push(d),n=!0,this.config.onAIMessage?.(o,!0),e?.(o)}this.stats.tokensUsed+=r.usage.input_tokens+r.usage.output_tokens}return this.config.onAIMessage?.(o,!1),e?.(o),o}parseMessageBlock(i,e){let t=[];for(let n of i.content)if(n.type=="thinking")t.push({type:"thinking",text:n.thinking||""});else if(n.type=="text")t.push({type:"text",text:n.text||""});else if(n.type=="tool_use"){let o=this.findToolBySafeName(n.name);t.push({type:"tool_call",toolName:n.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:n.input,toolCallInstanceID:n.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:i.id,data:{role:i.role,content:i.content},sections:t,source:"assistant",streamingInProgress:e,usage:{inputTokens:i.usage?.input_tokens||0,outputTokens:i.usage?.output_tokens||0,cachedInputTokens:i.usage?.cache_read_input_tokens||0,totalTokens:(i.usage?.input_tokens||0)+(i.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import Qt from"minisearch";var ut=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",disabled:!l?.knowledgeBase?.allowRagSearch,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(i,e)=>{let t=await e.knowledgeBase.search(i.query),n=e;n._lastKBsearch=i.query,n._nextRequestUseKBitems=t;let o=t.filter(r=>r.type!="action").map(r=>"- "+r.name).join(`
|
|
15
15
|
`)||"- (none)",s=t.filter(r=>r.type=="action").map(r=>"- "+r._functionID).join(`
|
|
16
16
|
`)||"- (none)";return`Search complete, context has been updated.
|
|
17
17
|
New information found:
|
|
18
18
|
${o}
|
|
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"||!a?.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"||!a?.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"||!a?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),n=encodeURIComponent(i.subject),o=encodeURIComponent(i.body),s=`mailto:${t}?subject=${n}&body=${o}`;try{window.location.href=s}catch(r){throw new Error(`Failed to open email client: ${r instanceof Error?r.message:String(r)}`)}return`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as Vt}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as zt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{LoggingMessageNotificationSchema as _t,ToolListChangedNotificationSchema as jt}from"@modelcontextprotocol/sdk/types.js";var b=new m("MCPKnowledgeClient"),Ot="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",be=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(){b.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new URL(this.config.baseURL),t={};this.config.headers&&(t={...t,...this.config.headers}),this.config.proxy?.enabled&&(t["Mcp-Target-Url"]=e.toString(),t["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",e=new URL(this.config.proxy.url||Ot));let n=new Vt({name:Z.name,version:Z.version}),o=new zt(e,{requestInit:{headers:t}});return await n.connect(o),b.debug("Connected with HTTP streaming mode"),n});return await this.disconnect(),this.client=i,i.onerror=e=>{b.error(`MCP client error: ${e.message}`)},i.onclose=()=>{b.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(_t,e=>{e.params.level=="critical"?b.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?b.error(`[Server] ${e.params.data}`):e.params.level=="error"?b.error(`[Server] ${e.params.data}`):e.params.level=="warning"?b.warn(`[Server] ${e.params.data}`):e.params.level=="info"?b.info(`[Server] ${e.params.data}`):e.params.level=="debug"?b.debug(`[Server] ${e.params.data}`):b.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(jt,e=>{b.debug("Tool list changed",e),this.fetchTools()}),b.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let o of n.tools||[])i.push(o);if(!n?.tools?.length||!e)break}let t=[];for(let n of i){let o=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:s=>this.performToolCall(n.name,s),disabled:o})}b.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,b.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(o=>o.name==this.config.searchToolName);if(!t)return b.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(t.inputSchema.required?.length==1){let o=t.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let o=Object.keys(t.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let o=0;o<n.length;o++){let s=n[o];e.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(i,e){await this.connect(),b.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let n=t.content?.[0]?.text||"Unknown error";throw b.error(`Error calling tool ${i}: ${n}`),new Error(`Error calling tool ${i}: ${n}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};var X=new m("KnowledgeBase"),Xe=1,we=class a{constructor(i){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=i,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(i=>i.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>st(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${Xe++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return this.allowGlobalConfigSources&&g().knowledgeBaseSources&&(i=i.concat(g().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(i=i.concat(this._windowSources)),i=i.filter(e=>!e.disabled),i}async search(i){X.debug(`Searching knowledge base for: ${i}`);let e=Date.now(),t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(t),this._windowSources=t.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async d=>{try{let c=Date.now(),u=await d.query(i);return X.debug(`Source '${d.id}' took ${Date.now()-c}ms`),u||[]}catch(c){return X.warn(`Knowledge source '${d.id}' failed:`,c),[]}}))).flat();o=o.concat(t.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&g().knowledgeBase&&(o=o.concat(g().knowledgeBase)),o=o.filter(d=>d&&!d.disabled);for(let d=0;d<o.length;d++){let c=o[d];c.id=c.id||`temp.${d}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new Yt({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(i).map(d=>o.find(c=>c.id==d.id));for(let d of o)d.isContext&&(l.find(c=>c.id===d.id)||l.push(d));return this.lastResults=l,w(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),X.debug("Found results:",l),l}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${Xe++}`),X.debug(`Registering remote knowledge base source: ${i}`);let t=[],n=[],o=!0,s=async(l,d)=>{X.debug(`Calling remote knowledge base action: ${l.id}`);let c={type:"action",userID:this.ai.userID,actionID:l.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 r(p.updateItems||[]),p.response},r=l=>{for(let d of l){if(!d.id){X.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 l=>{if(o&&n.includes(l))return t;let d={type:"search",userID:this.ai?.userID||"",query:l},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 o=!u.noCache,n.includes(l)||n.push(l),r(u.items),t})}clone(i){let e=new a(i);return e._sources=this._sources.slice(),e._windowSources=this._windowSources.slice(),e.manualEntries=this.manualEntries.slice(),e.allowGlobalConfigSources=this.allowGlobalConfigSources,e.allowWindowSources=this.allowWindowSources,e.allowRagSearch=this.allowRagSearch,e.ensureInternalKnowledge(),e}registerMCPSource(i){i.id||(i.id=`external.${Xe++}`);let e=new be(i);return this.registerSource(i.id,t=>e.search(t)),e}};var U=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:(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),n=encodeURIComponent(i.subject),o=encodeURIComponent(i.body),s=`mailto:${t}?subject=${n}&body=${o}`;try{window.location.href=s}catch(r){throw new Error(`Failed to open email client: ${r instanceof Error?r.message:String(r)}`)}return`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as Ft}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Ut}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{LoggingMessageNotificationSchema as Kt,ToolListChangedNotificationSchema as Ht}from"@modelcontextprotocol/sdk/types.js";var x=new g("MCPKnowledgeClient"),Jt="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",ke=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(){x.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new URL(this.config.baseURL),t={};this.config.headers&&(t={...t,...this.config.headers}),this.config.proxy?.enabled&&(t["Mcp-Target-Url"]=e.toString(),t["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",e=new URL(this.config.proxy.url||Jt));let n=new Ft({name:X.name,version:X.version}),o=new Ut(e,{requestInit:{headers:t}});return await n.connect(o),x.debug("Connected with HTTP streaming mode"),n});return await this.disconnect(),this.client=i,i.onerror=e=>{x.error(`MCP client error: ${e.message}`)},i.onclose=()=>{x.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(Kt,e=>{e.params.level=="critical"?x.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?x.error(`[Server] ${e.params.data}`):e.params.level=="error"?x.error(`[Server] ${e.params.data}`):e.params.level=="warning"?x.warn(`[Server] ${e.params.data}`):e.params.level=="info"?x.info(`[Server] ${e.params.data}`):e.params.level=="debug"?x.debug(`[Server] ${e.params.data}`):x.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(Ht,e=>{x.debug("Tool list changed",e),this.fetchTools()}),x.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 s of o.tools||[])i.push(s);if(!o?.tools?.length||!e)break}let t=[],n=this.config.id||"mcp";for(let o of i){let s=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),r=`${n}_${o.name}`;t.push({id:r,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:a=>this.performToolCall(o.name,a),disabled:s})}x.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,x.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(o=>o.name==this.config.searchToolName);if(!t)return x.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(t.inputSchema.required?.length==1){let o=t.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let o=Object.keys(t.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[o]:i})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let o=0;o<n.length;o++){let s=n[o];e.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(i,e){await this.connect(),x.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let n=t.content?.[0]?.text||"Unknown error";throw x.error(`Error calling tool ${i}: ${n}`),new Error(`Error calling tool ${i}: ${n}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};var B=new g("KnowledgeBase"),$t=8*1024,Ve=1,Se=class l{constructor(i){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=i,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(i=>i.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>ut(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${Ve++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return this.allowGlobalConfigSources&&f().knowledgeBaseSources&&(i=i.concat(f().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(i=i.concat(this._windowSources)),i=i.filter(e=>!e.disabled),i}async search(i){B.debug(`Searching knowledge base for: ${i}`);let e=Date.now(),t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(t),this._windowSources=t.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async c=>{try{let p=Date.now(),h=await c.query(i);return B.debug(`Source '${c.id}' took ${Date.now()-p}ms`),h||[]}catch(p){return B.warn(`Knowledge source '${c.id}' failed:`,p),[]}}))).flat();o=o.concat(t.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&f().knowledgeBase&&(o=o.concat(f().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);let s=new Map;for(let c of o)c.id&&s.set(c.id,(s.get(c.id)||0)+1);for(let[c,p]of s)if(p>1){B.warn(`Duplicate knowledge base item ID detected: '${c}' appears ${p} times. Adding suffixes to make them unique.`);let h=1,m=!0;for(let b of o)if(b.id===c){if(m){m=!1;continue}b.id=`${c}(${h})`,h++}}for(let c=0;c<o.length;c++){let p=o[c];p.id=p.id||`temp.${c}`,p._functionID=p.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let r=new Qt({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});r.addAll(o);let u=r.search(i).map(c=>o.find(p=>p.id==c.id)).filter(Boolean),d=0;u=u.filter(c=>{if(c.isContext)return!0;let p=(c.content||"").length;return d+p>$t?!1:(d+=p,!0)});for(let c of o)c.isContext&&(u.find(p=>p.id===c.id)||u.push(c));return this.lastResults=u,I(this.ai,{event_type:"kb_search",value:u.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),B.debug("Found results:",u),u}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${Ve++}`),B.debug(`Registering remote knowledge base source: ${i}`);let t=[],n=[],o=!0,s=async(a,u)=>{B.debug(`Calling remote knowledge base action: ${a.id}`);let d={type:"action",userID:this.ai.userID,actionID:a.id,parameters:u},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 p=await c.json();return r(p.updateItems||[]),p.response},r=a=>{for(let u of a){if(!u.id){B.warn("KB item skipped since it has no ID.",u);continue}let d=t.find(c=>c.id==u.id);if(d){d.name=u.name||d.name||"",d.content=u.content||d.content||"",d.disabled=u.disabled??d.disabled,d.isContext=u.isContext??d.isContext,d.parameters=u.parameters||d.parameters||[],d.tags=u.tags||d.tags,d.type=u.type||d.type;continue}t.push({...u,action:c=>s(u,c)})}};this.registerSource(e,async a=>{if(o&&n.includes(a))return t;let u={type:"search",userID:this.ai?.userID||"",query:a},d=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let c=await d.json();return o=!c.noCache,n.includes(a)||n.push(a),r(c.items),t})}clone(i){let e=new l(i);return e._sources=this._sources.slice(),e._windowSources=this._windowSources.slice(),e.manualEntries=this.manualEntries.slice(),e.allowGlobalConfigSources=this.allowGlobalConfigSources,e.allowWindowSources=this.allowWindowSources,e.allowRagSearch=this.allowRagSearch,e.ensureInternalKnowledge(),e}registerMCPSource(i){i.id||(i.id=`external.${Ve++}`);let e=new ke(i);return this.registerSource(i.id,t=>e.search(t)),e}};function Ye(l){let i="",e=[],t=0;for(;t<l.length;){let n=l.indexOf("<[[",t);if(n===-1){i+=l.slice(t);break}i+=l.slice(t,n);let o=l.indexOf("]]>",n+3);if(o===-1)break;let s=l.slice(n,o+3),r=l.slice(n+3,o).trim(),a={raw:s,content:r};try{let u=JSON.parse(r);u&&typeof u=="object"&&!Array.isArray(u)&&(a.action=u)}catch{}e.push(a),t=o+3}return{visibleText:i,actions:e.flatMap(n=>n.action?[n.action]:[]),blocks:e}}function pt(l){return Ye(l).visibleText}var J=class{constructor(i){this.messages=i}text(){return this.messages?.flatMap(i=>i.sections)?.filter(i=>i?.type=="text")?.map(i=>pt(i?.text||""))?.filter(i=>!!i)?.join(`
|
|
22
22
|
|
|
23
|
-
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((i,e)=>i+(e.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(i=>i.sections||[])||[]}toolCalls(){return this.messages?.flatMap(i=>i.sections?.filter(e=>e.type=="tool_call")||[])||[]}toolResult(i){return this.messages?.map(e=>e.sections?.find(t=>t.type=="tool_result"&&t.toolCallInstanceID==i)).filter(e=>!!e)[0]||null}};import{v4 as
|
|
23
|
+
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((i,e)=>i+(e.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((i,e)=>i+(e.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(i=>i.sections||[])||[]}toolCalls(){return this.messages?.flatMap(i=>i.sections?.filter(e=>e.type=="tool_call")||[])||[]}toolResult(i){return this.messages?.map(e=>e.sections?.find(t=>t.type=="tool_result"&&t.toolCallInstanceID==i)).filter(e=>!!e)[0]||null}};import{v4 as ht}from"uuid";var Te=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
24
24
|
|
|
25
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(i){let e=await this.instruct({...i,instruction:`${i.instruction}
|
|
26
26
|
|
|
@@ -37,7 +37,7 @@ Objects should have the following keys:
|
|
|
37
37
|
${i.extractions.map(n=>`- ${n.name} (${n.type}): ${n.description||"No description provided."}`).join(`
|
|
38
38
|
`)}
|
|
39
39
|
`,t=await this.instruct({...i,instruction:e});if(t=t.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),i.allowMultiple){let n=t.split(`
|
|
40
|
-
`).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of n)try{o.push(JSON.parse(s))}catch(r){console.error("Failed to parse line as JSON:",s,r.message)}return o}else return[JSON.parse(t.trim())]}async generateMarkdown(i){return this.instruct({...i,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(i){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>i.instruction,i.callback&&e.addEventListener("output",t=>{i.callback(t.detail.message)}),i.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof i.data=="string"?i.data:JSON.stringify(i.data)).then(t=>t.text())}};var
|
|
40
|
+
`).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of n)try{o.push(JSON.parse(s))}catch(r){console.error("Failed to parse line as JSON:",s,r.message)}return o}else return[JSON.parse(t.trim())]}async generateMarkdown(i){return this.instruct({...i,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(i){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>i.instruction,i.callback&&e.addEventListener("output",t=>{i.callback(t.detail.message)}),i.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof i.data=="string"?i.data:JSON.stringify(i.data)).then(t=>t.text())}};var Ce=class{constructor(i){this.subagents=[];this.cachedSubagents={};this.ai=i}register(i){if(this.subagents.find(e=>e.id==i.id))throw new Error(`Sub-agent with ID ${i.id} already exists`);this.subagents.push(i),this.ai.knowledgeBase.registerSource("subagent:"+i.id,e=>[{type:"action",id:"ask:"+i.id,name:`Ask ${i.name||"subagent"}`,content:i.usageInstructions||`Use this tool to ask ${i.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(t,n)=>await this.runQuery(i,t.query)}])}remove(i){this.subagents=this.subagents.filter(e=>e.id!=i),this.ai.knowledgeBase.removeSource("subagent:"+i)}async runQuery(i,e){let t=i.apiKey||this.ai.apiKey,n=this.cachedSubagents[t];return n||(n=new j,n.userID=this.ai.userID,await n.load(t,i.config),this.cachedSubagents[t]=n),n=n.clone(),n.knowledgeBase.allowGlobalConfigSources=!1,n.knowledgeBase.allowWindowSources=!1,i.clearExistingKnowledge&&n.knowledgeBase.reset(),n.knowledgeBase.allowRagSearch=!i.disableRagSearch,i.knowledge&&n.knowledgeBase.registerSource(i.knowledge),i.onAgentLoaded&&await i.onAgentLoaded(n),(await n.sendMessage(e)).text()}};var T=new g("Main"),mt=new Set,_=class _ extends EventTarget{constructor(){super(...arguments);this.conversationID=ht();this.knowledgeBase=new Se(this);this.subAgents=new Ce(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new Te(this);this.userID=et();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:_.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","embedded.suggestion - Add hidden follow-up suggestion buttons in the built-in UI","embedded.emoji - Trigger hidden emoji effects in the built-in UI","search - Search knowledge base"],enabledFlags:this.flags}}async load(e,t){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");t?.userID&&(this.userID=t.userID),t?.hubAPI&&(this.hubAPI=t.hubAPI);try{await Promise.all([(async()=>{T.debug("Loading configuration...");let n=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,userID:this.userID})});if(!n.ok){let o=`${n.status} ${n.statusText}`;try{let s=await n.json();s.error?o=s.error:s.message&&(o=s.message)}catch(s){T.debug("Could not parse error response body:",s)}throw new Error(`Failed to load configuration: ${o}`)}try{this.config=await n.json(),T.debug("Config loaded successfully:",this.config),t&&(this.config={...this.config,...t}),this.config&&T.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){T.error("Failed to parse JSON response:",o);try{let s=await n.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: ${o}`)}})(),(async()=>{try{let n=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!n.ok)throw new Error(`Failed to load VAD model: ${n.status} ${n.statusText}`);this.vadModel=await n.blob()}catch(n){T.warn(`Failed to load VAD model, some features will be unavailable. ${n.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let n of this.config.knowledge||[])n.url&&n.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:n.id,searchToolName:n.mcpSearchToolName,baseURL:n.url}):n.url&&this.knowledgeBase.registerSourceFromURL(n.url);for(let n of this.config.knowledge||[])n.entries?.length&&this.knowledgeBase.registerSource(n.id,()=>n.entries||[]);if(this.config.mcpServers)for(let n of this.config.mcpServers)this.knowledgeBase.registerMCPSource(n);for(let n of this.config.subagents||[])this.subAgents.register(n);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(n){throw T.warn("Failed to load:",n),this.error=n,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:n}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:n}})),n}}setModel(e){let t=this.models.find(o=>o.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let n={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let r=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(r?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(n):t.config.providerID==="anthropic"?this.currentModel=new Ie(n):this.currentModel=new Me(n),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=f().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let t=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:t}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:le(`
|
|
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.
|
|
@@ -45,7 +45,7 @@ ${i.extractions.map(n=>`- ${n.name} (${n.type}): ${n.description||"No descriptio
|
|
|
45
45
|
If you're about to say "I don't have access..." or "I can't..." use the \`search\` tool first.
|
|
46
46
|
`)}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,data:`# Knowledge Database${e.length==0?`
|
|
47
47
|
|
|
48
|
-
(no items found)`:""}`});for(let n of e)if(n.type=="info"||n.type=="tour"||n.type=="input-event"){let o=
|
|
48
|
+
(no items found)`:""}`});for(let n of e)if(n.type=="info"||n.type=="tour"||n.type=="input-event"){let o=le(n.content),s=!0;if(n.attachments?.length)for(let r of n.attachments)r.url&&(s&&(o+=`
|
|
49
49
|
|
|
50
50
|
\`\`\`yaml
|
|
51
51
|
attachments:
|
|
@@ -53,12 +53,12 @@ attachments:
|
|
|
53
53
|
mimetype: "${r.mimeType||""}"
|
|
54
54
|
url: "${r.url}"
|
|
55
55
|
`);s||(o+="```\n"),this.currentModel.contextGroup.add({id:n.id,data:`## ${n.type}: ${n.name}
|
|
56
|
-
${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="function"?n.disabled(this):n.disabled})}else if(n.type=="action"){let o={name:n._functionID,description:
|
|
56
|
+
${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="function"?n.disabled(this):n.disabled})}else if(n.type=="action"){let o={name:n._functionID,description:le(n.content),params:tt(n.parameters||[{name:"value",type:"string",description:"Input"}]),callback:s=>this.toolRunKBAction(n,s),canRemove:!n.isContext,kbItem:n};this.currentModel.registerTool(o)}else continue;for(let n of this.lastKBItems)!n.isContext||!n.id||e.find(s=>s.id==n.id)||(this.currentModel.contextGroup.remove(n.id),n._functionID&&this.currentModel.toolGroup.remove(n._functionID));this.lastKBItems=e}processIncomingMessage(e,t){if(!t){let n=this.currentModel?.stats?.tokensUsed||0,o=e.reduce((s,r)=>s+(r.usage?.totalTokens||0),0);I(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:n}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:t,messages:e}})),this.onAIMessage?.(e,!!t)}async sendMessage(e,t){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(),mt.has(this.conversationID)||(mt.add(this.conversationID),I(this,{event_type:"session_start"})),I(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 n=Date.now(),o=await this.currentModel.sendMessage(e),s=new J(o);(this._voiceTracker||T.debug.bind(T))(`LLM response took ${Date.now()-n}ms`);let a=this.currentModel.contextGroup.getAllAsString();a+=`
|
|
57
57
|
|
|
58
58
|
=== TOOLS ===
|
|
59
59
|
|
|
60
|
-
`+this.currentModel.toolGroup.getAll().map(
|
|
61
|
-
`),this._lastSystemMsg!=l&&(this._lastSystemMsg=l,this.submitAnalyticsEvent({type:"system-msg",txt:l}));for(let d of o)for(let c of d.sections||[])if(c.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:c.text||""});else if(c.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:c.text||""});else if(c.type=="tool_call"){let u=s.toolResult(c.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:c.toolKbID||"",actionName:c.toolKbName||"",value:c.toolParameters,result:u?.toolErrorResponse||u?.toolSuccessResponse,isError:!!u?.toolErrorResponse})}else c.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let n=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:t,ai:this}}));let o=await e.action(t,this),s=Date.now()-n;return w(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:o}})),o}catch(o){let s=Date.now()-n;throw w(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:s,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,error:o}})),o}}submitAnalyticsEvent(e){if(g().analytics===!1||this.config?.analytics===!1)return;let t=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(n=>{x.debug("Failed to submit analytics event:",n)});this.activeAnalyticsPromises.push(t),t.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(n=>n!==t)})}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=rt(),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 P;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),e}get messages(){return this.currentModel?.messageGroup.items||[]}};P.version=Z.version,P.builtInActionsVersion="1.0.0",x.debug(`Loaded: version=${Z.version} builtInActionsVersion=${P.builtInActionsVersion}`);var R=P;var I=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 n=document.createElement(this.tagName);for(let o in e)n.setAttribute(o,e[o]);return n.onBeforeCreate(),n.innerHTML=t,n}static add(e={},t=""){this.register();let n=o=>o.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">");return`<${this.tagName} ${Object.keys(e).map(o=>`${o}="${n(e[o]+"")}"`).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,n){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,n)=>(this.getAttribute(t.toString())===n||(n?this.setAttribute(t.toString(),n):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,n)=>(this._state[t]=n,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}};I.observedAttributes=[],I.tagName="",I._isRegistered=!1;var lt='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 ct='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 dt='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var $=class extends I{constructor(){super(...arguments);this.html=()=>`
|
|
60
|
+
`+this.currentModel.toolGroup.getAll().map(u=>"- "+u.data?.name).join(`
|
|
61
|
+
`),this._lastSystemMsg!=a&&(this._lastSystemMsg=a,this.submitAnalyticsEvent({type:"system-msg",txt:a}));for(let u of o)for(let d of u.sections||[])if(d.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:d.text||""});else if(d.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:d.text||""});else if(d.type=="tool_call"){let c=s.toolResult(d.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:d.toolKbID||"",actionName:d.toolKbName||"",value:d.toolParameters,result:c?.toolErrorResponse||c?.toolSuccessResponse,isError:!!c?.toolErrorResponse})}else d.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let n=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:t,ai:this}}));let o=await e.action(t,this),s=Date.now()-n;return I(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:o}})),o}catch(o){let s=Date.now()-n;throw I(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:s,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,error:o}})),o}}submitAnalyticsEvent(e){if(f().analytics===!1||this.config?.analytics===!1)return;let t=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(n=>{T.debug("Failed to submit analytics event:",n)});this.activeAnalyticsPromises.push(t),t.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(n=>n!==t)})}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=ht(),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 _;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),e}get messages(){return this.currentModel?.messageGroup.items||[]}};_.version=X.version,_.builtInActionsVersion="1.2.0",T.debug(`Loaded: version=${X.version} builtInActionsVersion=${_.builtInActionsVersion}`);var j=_;var C=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 n=document.createElement(this.tagName);for(let o in e)n.setAttribute(o,e[o]);return n.onBeforeCreate(),n.innerHTML=t,n}static add(e={},t=""){this.register();let n=o=>o.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">");return`<${this.tagName} ${Object.keys(e).map(o=>`${o}="${n(e[o]+"")}"`).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,n){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,n)=>(this.getAttribute(t.toString())===n||(n?this.setAttribute(t.toString(),n):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,n)=>(this._state[t]=n,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}};C.observedAttributes=[],C.tagName="",C._isRegistered=!1;var gt='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 ft='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 bt='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 ne=class extends C{constructor(){super(...arguments);this.html=()=>`
|
|
62
62
|
|
|
63
63
|
<!-- Styling -->
|
|
64
64
|
<style>
|
|
@@ -139,7 +139,7 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
139
139
|
}
|
|
140
140
|
|
|
141
141
|
:host #loader {
|
|
142
|
-
background-image: url('${
|
|
142
|
+
background-image: url('${gt}');
|
|
143
143
|
background-size: 64px 64px;
|
|
144
144
|
background-position: center;
|
|
145
145
|
background-repeat: no-repeat;
|
|
@@ -162,7 +162,7 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
162
162
|
}
|
|
163
163
|
|
|
164
164
|
:host #microphone-button {
|
|
165
|
-
background-image: url('${
|
|
165
|
+
background-image: url('${ft}');
|
|
166
166
|
z-index: 2;
|
|
167
167
|
margin-right: -10px;
|
|
168
168
|
}
|
|
@@ -186,10 +186,117 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
186
186
|
}
|
|
187
187
|
|
|
188
188
|
:host #cancel-speech-button {
|
|
189
|
-
background-image: url('${
|
|
189
|
+
background-image: url('${bt}');
|
|
190
190
|
z-index: 2;
|
|
191
191
|
}
|
|
192
192
|
|
|
193
|
+
/** Dock UI input treatment */
|
|
194
|
+
:host {
|
|
195
|
+
--iw-mic-active-fill-width: 58px;
|
|
196
|
+
height: auto;
|
|
197
|
+
min-height: 62px;
|
|
198
|
+
display: grid;
|
|
199
|
+
grid-template-columns: auto auto minmax(0, 1fr) auto auto;
|
|
200
|
+
gap: 8px;
|
|
201
|
+
align-items: center;
|
|
202
|
+
padding: 10px;
|
|
203
|
+
box-sizing: border-box;
|
|
204
|
+
background: rgba(7, 11, 13, 0.58);
|
|
205
|
+
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
|
206
|
+
overflow: hidden;
|
|
207
|
+
}
|
|
208
|
+
:host([layout="fullscreen"]) {
|
|
209
|
+
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
|
210
|
+
border-radius: 0;
|
|
211
|
+
width: 100%;
|
|
212
|
+
max-width: none;
|
|
213
|
+
margin: 0;
|
|
214
|
+
background: rgba(7, 11, 13, 0.58);
|
|
215
|
+
}
|
|
216
|
+
:host input {
|
|
217
|
+
min-width: 0;
|
|
218
|
+
min-height: 42px;
|
|
219
|
+
border: 1px solid rgba(255, 255, 255, 0.12);
|
|
220
|
+
border-radius: 14px;
|
|
221
|
+
background: rgba(255, 255, 255, 0.06);
|
|
222
|
+
color: var(--intelliweave-text-color, #E6F1F5);
|
|
223
|
+
padding: 0 12px;
|
|
224
|
+
/* Keep text inputs at 16px to prevent iOS Safari from zooming the page on focus. */
|
|
225
|
+
font-size: 16px;
|
|
226
|
+
font-weight: 750;
|
|
227
|
+
}
|
|
228
|
+
:host input::placeholder {
|
|
229
|
+
color: var(--intelliweave-text-color, #E6F1F5);
|
|
230
|
+
opacity: 0.48;
|
|
231
|
+
font-size: 16px;
|
|
232
|
+
font-weight: 650;
|
|
233
|
+
}
|
|
234
|
+
:host input:focus {
|
|
235
|
+
border-color: rgba(34, 211, 238, 0.42);
|
|
236
|
+
box-shadow: 0 0 0 2px rgba(34, 211, 238, 0.12);
|
|
237
|
+
}
|
|
238
|
+
:host #send-button {
|
|
239
|
+
width: auto;
|
|
240
|
+
min-width: 42px;
|
|
241
|
+
height: 42px;
|
|
242
|
+
margin: 0;
|
|
243
|
+
border-radius: 14px;
|
|
244
|
+
background: var(--iw-send-btn-gradient, linear-gradient(135deg, #0b7aa1, 55%, #a34b0d));
|
|
245
|
+
color: #061017;
|
|
246
|
+
opacity: 1;
|
|
247
|
+
}
|
|
248
|
+
:host([layout="widget"]) #send-button {
|
|
249
|
+
background: var(--iw-send-btn-gradient, linear-gradient(135deg, #0b7aa1, 55%, #a34b0d));
|
|
250
|
+
opacity: 1;
|
|
251
|
+
}
|
|
252
|
+
:host #send-button svg {
|
|
253
|
+
fill: currentColor;
|
|
254
|
+
}
|
|
255
|
+
:host #llm-button {
|
|
256
|
+
height: 34px;
|
|
257
|
+
display: flex;
|
|
258
|
+
align-items: center;
|
|
259
|
+
padding: 0 9px;
|
|
260
|
+
margin: 0;
|
|
261
|
+
border-radius: 999px;
|
|
262
|
+
background: rgba(255, 255, 255, 0.07);
|
|
263
|
+
border: 1px solid rgba(255, 255, 255, 0.12);
|
|
264
|
+
font-size: 10px;
|
|
265
|
+
font-weight: 850;
|
|
266
|
+
white-space: nowrap;
|
|
267
|
+
}
|
|
268
|
+
:host .button {
|
|
269
|
+
width: 34px;
|
|
270
|
+
height: 34px;
|
|
271
|
+
border-radius: 999px;
|
|
272
|
+
background-color: rgba(255, 255, 255, 0.06);
|
|
273
|
+
align-self: center;
|
|
274
|
+
}
|
|
275
|
+
:host #microphone-button {
|
|
276
|
+
margin-right: 0;
|
|
277
|
+
}
|
|
278
|
+
:host #microphone-button-bg {
|
|
279
|
+
top: 0;
|
|
280
|
+
left: 0;
|
|
281
|
+
width: var(--iw-mic-active-fill-width);
|
|
282
|
+
height: 100%;
|
|
283
|
+
border-radius: 0 999px 999px 0;
|
|
284
|
+
transform: scaleX(0.0001);
|
|
285
|
+
transform-origin: left center;
|
|
286
|
+
}
|
|
287
|
+
:host #microphone-button-bg.active {
|
|
288
|
+
transform: scaleX(1);
|
|
289
|
+
}
|
|
290
|
+
:host #microphone-button-bg.active + #microphone-button {
|
|
291
|
+
background-color: transparent;
|
|
292
|
+
}
|
|
293
|
+
:host #loader {
|
|
294
|
+
min-height: 42px;
|
|
295
|
+
height: 42px;
|
|
296
|
+
border-radius: 14px;
|
|
297
|
+
background-color: rgba(255, 255, 255, 0.06);
|
|
298
|
+
}
|
|
299
|
+
|
|
193
300
|
</style>
|
|
194
301
|
|
|
195
302
|
<!-- Microphone button bg -->
|
|
@@ -217,7 +324,7 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
217
324
|
<!-- Loader bar -->
|
|
218
325
|
<div id='loader'></div>
|
|
219
326
|
|
|
220
|
-
`;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("send-button").addEventListener("click",e=>this.onSendButtonClick(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",t=>this.onSpeechEvent(t)),this.ai.audio?.speechRecognition.addEventListener("start",t=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",t=>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("send-button").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",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(t=>t.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(e){if(e.stopPropagation(),e.key!="Enter")return;let t=this.child("input-field"),n=t.value?.trim();t.value="",n&&this.dispatchEvent(new CustomEvent("input-message",{detail:n}))}onLLMButtonClick(e){e.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onSendButtonClick(e){e.preventDefault();let t=this.child("input-field"),n=t.value?.trim();t.value="",n&&this.dispatchEvent(new CustomEvent("input-message",{detail:n}))}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 t=this.ai?.audio?.speechRecognition.volumeLevel||0,n=30,o=6,s=Math.round(t*(n-o)+o),r=document.createElement("div");r.posX=
|
|
327
|
+
`;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("send-button").addEventListener("click",e=>this.onSendButtonClick(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",t=>this.onSpeechEvent(t)),this.ai.audio?.speechRecognition.addEventListener("start",t=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",t=>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("send-button").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",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(t=>t.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(e){if(e.stopPropagation(),e.key!="Enter")return;let t=this.child("input-field"),n=t.value?.trim();t.value="",n&&this.dispatchEvent(new CustomEvent("input-message",{detail:n}))}onLLMButtonClick(e){e.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onSendButtonClick(e){e.preventDefault();let t=this.child("input-field"),n=t.value?.trim();t.value="",n&&this.dispatchEvent(new CustomEvent("input-message",{detail:n}))}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 t=this.ai?.audio?.speechRecognition.volumeLevel||0,n=30,o=6,s=Math.round(t*(n-o)+o),r=document.createElement("div"),a=this.child("microphone-button"),u=a?a.offsetLeft+a.offsetWidth+8:62;r.posX=u,r.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(r),this.voiceAnimationPieces.push(r)}for(let e=0;e<this.voiceAnimationPieces.length;e++){let t=this.voiceAnimationPieces[e];t.posX+=2,t.style.transform=`translate(${t.posX}px, 0px)`;let n=this.offsetWidth||600;t.posX<n||(this.voiceAnimationPieces.splice(e--,1),t.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()}};ne.observedAttributes=["loading","llmName","llmButtonVisible","textColor","layout"];var Ee='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 oe=class extends C{constructor(){super(...arguments);this.html=()=>`
|
|
221
328
|
|
|
222
329
|
<!-- Styling -->
|
|
223
330
|
<style>
|
|
@@ -270,7 +377,7 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
270
377
|
<!-- Logo -->
|
|
271
378
|
<img id='root' />
|
|
272
379
|
|
|
273
|
-
`;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let t=this.attr.logo||
|
|
380
|
+
`;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let t=this.attr.logo||Ee;this._lastLogoSrc!=t&&(this._lastLogoSrc=t,e.src=t);let n=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(n){let o=window.visualViewport?.offsetTop||0,s=window.visualViewport?.offsetLeft||0,r=n.getBoundingClientRect();if(!r)return;e.classList.add("focused-mode"),e.style.width="128px",e.style.height="128px",e.style.left=Math.round(r.x+r.width/2-128/2+s)+"px",e.style.top=Math.round(r.y+r.height/2-128/2+o)+"px"}else e.classList.remove("focused-mode"),e.style.width="",e.style.height="",e.style.left="",e.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};oe.observedAttributes=["logo","focusID"];import wt from"rehype-external-links";import vt from"rehype-format";import xt from"rehype-stringify";import Mt from"remark-gfm";import It from"remark-parse";import kt from"remark-rehype";var Ae=(function(l){if(l==null)return ri;if(typeof l=="function")return Le(l);if(typeof l=="object")return Array.isArray(l)?ni(l):oi(l);if(typeof l=="string")return si(l);throw new Error("Expected function, string, or object as test")});function ni(l){let i=[],e=-1;for(;++e<l.length;)i[e]=Ae(l[e]);return Le(t);function t(...n){let o=-1;for(;++o<i.length;)if(i[o].apply(this,n))return!0;return!1}}function oi(l){let i=l;return Le(e);function e(t){let n=t,o;for(o in l)if(n[o]!==i[o])return!1;return!0}}function si(l){return Le(i);function i(e){return e&&e.type===l}}function Le(l){return i;function i(e,t,n){return!!(ai(e)&&l.call(this,e,typeof t=="number"?t:void 0,n||void 0))}}function ri(){return!0}function ai(l){return l!==null&&typeof l=="object"&&"type"in l}var yt=[],Fe=!0,Ne=!1,Ue="skip";function Ke(l,i,e,t){let n;typeof i=="function"&&typeof e!="function"?(t=e,e=i):n=i;let o=Ae(n),s=t?-1:1;r(l,void 0,[])();function r(a,u,d){let c=a&&typeof a=="object"?a:{};if(typeof c.type=="string"){let h=typeof c.tagName=="string"?c.tagName:typeof c.name=="string"?c.name:void 0;Object.defineProperty(p,"name",{value:"node ("+(a.type+(h?"<"+h+">":""))+")"})}return p;function p(){let h=yt,m,b,y;if((!i||o(a,u,d[d.length-1]||void 0))&&(h=li(e(a,d)),h[0]===Ne))return h;if("children"in a&&a.children){let v=a;if(v.children&&h[0]!==Ue)for(b=(t?v.children.length:-1)+s,y=d.concat(v);b>-1&&b<v.children.length;){let A=v.children[b];if(m=r(A,b,y)(),m[0]===Ne)return m;b=typeof m[1]=="number"?m[1]:b+s}}return h}}}function li(l){return Array.isArray(l)?l:typeof l=="number"?[Fe,l]:l==null?yt:[l]}function He(l,i,e,t){let n,o,s;typeof i=="function"&&typeof e!="function"?(o=void 0,s=i,n=e):(o=i,s=e,n=t),Ke(l,o,r,n);function r(a,u){let d=u[u.length-1],c=d?d.children.indexOf(a):void 0;return s(a,c,d)}}import{unified as St}from"unified";var se=class extends C{constructor(){super(...arguments);this.html=()=>`
|
|
274
381
|
|
|
275
382
|
<!-- Styling -->
|
|
276
383
|
<style>
|
|
@@ -357,7 +464,7 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
357
464
|
<div class='llm-selector-item-icon' style="background-image: url('${t.icon}'); "></div>
|
|
358
465
|
<div class='llm-selector-item-name'>${t.name}</div>
|
|
359
466
|
<div class='llm-selector-item-provider'>${t.provider}</div>
|
|
360
|
-
`,n.addEventListener("click",o=>{this.dispatchEvent(new CustomEvent("select",{detail:t.id}))}),e.appendChild(n)}}};
|
|
467
|
+
`,n.addEventListener("click",o=>{this.dispatchEvent(new CustomEvent("select",{detail:t.id}))}),e.appendChild(n)}}};se.observedAttributes=["open"];var k=new g("Embed"),Q=class extends C{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this._handledEmbeddedActionBlocks=new Map;this._returnToCollapsedOnSwipeClose=!1;this._suppressNextContainerClick=!1;this._previousFullscreenState=!1;this.html=()=>`
|
|
361
468
|
|
|
362
469
|
<!-- Styling -->
|
|
363
470
|
<style>
|
|
@@ -414,7 +521,6 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
414
521
|
max-height: none;
|
|
415
522
|
border-radius: 0;
|
|
416
523
|
box-shadow: none;
|
|
417
|
-
background: transparent !important;
|
|
418
524
|
overflow: hidden;
|
|
419
525
|
box-sizing: border-box;
|
|
420
526
|
padding-bottom: calc(12px + env(safe-area-inset-bottom));
|
|
@@ -444,7 +550,6 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
444
550
|
left: 50%;
|
|
445
551
|
transform: translateX(-50%);
|
|
446
552
|
z-index: 10;
|
|
447
|
-
transition: opacity 0.2s ease;
|
|
448
553
|
}
|
|
449
554
|
#root.layout-fullscreen #fullscreen-header {
|
|
450
555
|
display: flex;
|
|
@@ -460,9 +565,9 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
460
565
|
color: #333;
|
|
461
566
|
}
|
|
462
567
|
#root.layout-fullscreen #fullscreen-logo {
|
|
463
|
-
width:
|
|
464
|
-
height:
|
|
465
|
-
border-radius:
|
|
568
|
+
width: 60px;
|
|
569
|
+
height: 60px;
|
|
570
|
+
border-radius: 14px;
|
|
466
571
|
object-fit: contain;
|
|
467
572
|
}
|
|
468
573
|
#root.layout-fullscreen #fullscreen-branding {
|
|
@@ -507,13 +612,12 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
507
612
|
position: relative;
|
|
508
613
|
}
|
|
509
614
|
#root.layout-fullscreen #poweredby {
|
|
510
|
-
background
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
border-top: none;
|
|
615
|
+
background: rgba(7, 11, 13, 0.38);
|
|
616
|
+
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
|
617
|
+
color: rgba(230, 241, 245, 0.62);
|
|
514
618
|
width: 100%;
|
|
515
|
-
max-width:
|
|
516
|
-
margin: 0
|
|
619
|
+
max-width: none;
|
|
620
|
+
margin: 0;
|
|
517
621
|
border-radius: 0;
|
|
518
622
|
}
|
|
519
623
|
|
|
@@ -544,6 +648,11 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
544
648
|
right: 0px;
|
|
545
649
|
overflow-x: hidden;
|
|
546
650
|
overflow-y: auto;
|
|
651
|
+
-webkit-overflow-scrolling: touch;
|
|
652
|
+
overscroll-behavior: contain;
|
|
653
|
+
touch-action: pan-y;
|
|
654
|
+
scrollbar-width: none;
|
|
655
|
+
-ms-overflow-style: none;
|
|
547
656
|
opacity: 1;
|
|
548
657
|
transition: opacity 0.25s;
|
|
549
658
|
color: var(--intelliweave-text-color, white);
|
|
@@ -562,6 +671,8 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
562
671
|
}
|
|
563
672
|
#web-weaver-embed-inner::-webkit-scrollbar {
|
|
564
673
|
width: 0;
|
|
674
|
+
height: 0;
|
|
675
|
+
display: none;
|
|
565
676
|
background: transparent;
|
|
566
677
|
}
|
|
567
678
|
|
|
@@ -699,6 +810,46 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
699
810
|
border-bottom-color: rgba(0, 0, 0, 0.15);
|
|
700
811
|
}
|
|
701
812
|
|
|
813
|
+
#emoji-action-overlay {
|
|
814
|
+
position: absolute;
|
|
815
|
+
inset: 0;
|
|
816
|
+
pointer-events: none;
|
|
817
|
+
overflow: visible;
|
|
818
|
+
z-index: 40;
|
|
819
|
+
}
|
|
820
|
+
#root.layout-fullscreen #emoji-action-overlay,
|
|
821
|
+
#root.container-mode #emoji-action-overlay {
|
|
822
|
+
overflow: hidden;
|
|
823
|
+
}
|
|
824
|
+
.emoji-action-particle {
|
|
825
|
+
position: absolute;
|
|
826
|
+
left: var(--emoji-x, 50%);
|
|
827
|
+
bottom: var(--emoji-bottom, 72px);
|
|
828
|
+
font-size: var(--emoji-size, 34px);
|
|
829
|
+
line-height: 1;
|
|
830
|
+
opacity: 0;
|
|
831
|
+
transform: translate(-50%, 18px) scale(0.7) rotate(var(--emoji-rotate-start, 0deg));
|
|
832
|
+
text-shadow: 0 6px 18px rgba(0, 0, 0, 0.22);
|
|
833
|
+
animation: emoji-action-burst var(--emoji-duration, 1200ms) cubic-bezier(0.16, 1, 0.3, 1) forwards;
|
|
834
|
+
will-change: transform, opacity;
|
|
835
|
+
}
|
|
836
|
+
@keyframes emoji-action-burst {
|
|
837
|
+
0% {
|
|
838
|
+
opacity: 0;
|
|
839
|
+
transform: translate(-50%, 18px) scale(0.7) rotate(var(--emoji-rotate-start, 0deg));
|
|
840
|
+
}
|
|
841
|
+
12% {
|
|
842
|
+
opacity: 1;
|
|
843
|
+
}
|
|
844
|
+
72% {
|
|
845
|
+
opacity: 1;
|
|
846
|
+
}
|
|
847
|
+
100% {
|
|
848
|
+
opacity: 0;
|
|
849
|
+
transform: translate(calc(-50% + var(--emoji-drift, 0px)), var(--emoji-rise, -180px)) scale(var(--emoji-scale, 1.2)) rotate(var(--emoji-rotate-end, 20deg));
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
702
853
|
/** Info block */
|
|
703
854
|
#web-weaver-embed-inner .info-block {
|
|
704
855
|
display: flex;
|
|
@@ -783,55 +934,632 @@ ${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="functi
|
|
|
783
934
|
}
|
|
784
935
|
}
|
|
785
936
|
|
|
937
|
+
/** IntelliWeave dock UI */
|
|
938
|
+
#root {
|
|
939
|
+
width: auto;
|
|
940
|
+
height: auto;
|
|
941
|
+
min-width: 0;
|
|
942
|
+
min-height: 0;
|
|
943
|
+
display: flex;
|
|
944
|
+
align-items: center;
|
|
945
|
+
gap: 6px;
|
|
946
|
+
padding: 6px;
|
|
947
|
+
border: 1px solid rgba(34, 211, 238, 0.30);
|
|
948
|
+
border-radius: 999px;
|
|
949
|
+
background: var(--intelliweave-dock-bg, linear-gradient(135deg, rgba(7, 11, 13, 0.92), rgba(18, 26, 31, 0.88)));
|
|
950
|
+
box-shadow: 0 16px 44px rgba(0, 0, 0, 0.38), 0 0 32px rgba(34, 211, 238, 0.12);
|
|
951
|
+
color: var(--intelliweave-text-color, #E6F1F5);
|
|
952
|
+
font-family: var(--intelliweave-font-family, "Karla", sans-serif);
|
|
953
|
+
overflow: visible;
|
|
954
|
+
backdrop-filter: blur(16px);
|
|
955
|
+
-webkit-backdrop-filter: blur(16px);
|
|
956
|
+
}
|
|
957
|
+
#root.hidden {
|
|
958
|
+
display: none;
|
|
959
|
+
}
|
|
960
|
+
#root.open {
|
|
961
|
+
width: min(390px, calc(100vw - 28px));
|
|
962
|
+
height: auto;
|
|
963
|
+
max-width: none;
|
|
964
|
+
max-height: none;
|
|
965
|
+
min-height: 0;
|
|
966
|
+
display: flex;
|
|
967
|
+
flex-direction: column;
|
|
968
|
+
align-items: stretch;
|
|
969
|
+
gap: 0;
|
|
970
|
+
padding: 0;
|
|
971
|
+
border-color: rgba(34, 211, 238, 0.26);
|
|
972
|
+
border-radius: 24px;
|
|
973
|
+
background: var(--intelliweave-panel-bg, linear-gradient(145deg, rgba(7, 11, 13, 0.98), rgba(18, 26, 31, 0.94)), radial-gradient(circle at 100% 0, rgba(34, 211, 238, 0.18), transparent 38%));
|
|
974
|
+
box-shadow: 0 26px 86px rgba(0, 0, 0, 0.52), inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
|
975
|
+
overflow: hidden;
|
|
976
|
+
transform-origin: bottom right;
|
|
977
|
+
animation: iw-panel-enter 190ms cubic-bezier(0.2, 0.85, 0.25, 1);
|
|
978
|
+
backdrop-filter: blur(18px);
|
|
979
|
+
-webkit-backdrop-filter: blur(18px);
|
|
980
|
+
}
|
|
981
|
+
@media (min-width: 900px) {
|
|
982
|
+
#root.open:not(.layout-fullscreen):not(.container-mode) {
|
|
983
|
+
width: min(624px, calc(100vw - 36px));
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
@keyframes iw-panel-enter {
|
|
987
|
+
from { opacity: 0; transform: translateY(14px) scale(0.97); }
|
|
988
|
+
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
989
|
+
}
|
|
990
|
+
#root.layout-fullscreen:not(.container-mode) {
|
|
991
|
+
position: fixed;
|
|
992
|
+
top: max(0px, env(safe-area-inset-top)) !important;
|
|
993
|
+
right: max(0px, env(safe-area-inset-right)) !important;
|
|
994
|
+
bottom: max(0px, env(safe-area-inset-bottom)) !important;
|
|
995
|
+
left: max(0px, env(safe-area-inset-left)) !important;
|
|
996
|
+
width: auto;
|
|
997
|
+
height: auto;
|
|
998
|
+
display: flex;
|
|
999
|
+
flex-direction: column;
|
|
1000
|
+
border-radius: 0;
|
|
1001
|
+
background: var(--intelliweave-panel-bg, linear-gradient(145deg, rgba(7, 11, 13, 0.98), rgba(18, 26, 31, 0.94)), radial-gradient(circle at 100% 0, rgba(34, 211, 238, 0.18), transparent 38%)) !important;
|
|
1002
|
+
box-shadow: none;
|
|
1003
|
+
padding: 0;
|
|
1004
|
+
}
|
|
1005
|
+
#root.container-mode {
|
|
1006
|
+
position: absolute;
|
|
1007
|
+
inset: 0;
|
|
1008
|
+
width: 100%;
|
|
1009
|
+
height: 100%;
|
|
1010
|
+
border-radius: 0;
|
|
1011
|
+
}
|
|
1012
|
+
#root.is-collapsed {
|
|
1013
|
+
padding: 5px 4px 5px 5px;
|
|
1014
|
+
border-radius: 16px 0 0 16px;
|
|
1015
|
+
}
|
|
1016
|
+
#root.is-collapsed.position-left {
|
|
1017
|
+
border-radius: 0 16px 16px 0;
|
|
1018
|
+
}
|
|
1019
|
+
#root button {
|
|
1020
|
+
border: none;
|
|
1021
|
+
color: inherit;
|
|
1022
|
+
cursor: pointer;
|
|
1023
|
+
font: inherit;
|
|
1024
|
+
}
|
|
1025
|
+
#dock-launcher {
|
|
1026
|
+
display: flex;
|
|
1027
|
+
align-items: center;
|
|
1028
|
+
gap: 6px;
|
|
1029
|
+
overflow: hidden;
|
|
1030
|
+
max-width: 220px;
|
|
1031
|
+
max-height: 58px;
|
|
1032
|
+
opacity: 1;
|
|
1033
|
+
transform: translateY(0) scale(1);
|
|
1034
|
+
transition: opacity 180ms ease, transform 180ms ease, max-width 180ms ease, max-height 180ms ease, margin 180ms ease;
|
|
1035
|
+
}
|
|
1036
|
+
#root.open #dock-launcher,
|
|
1037
|
+
#root.is-collapsed #dock-launcher {
|
|
1038
|
+
max-width: 0;
|
|
1039
|
+
max-height: 0;
|
|
1040
|
+
margin: 0;
|
|
1041
|
+
opacity: 0;
|
|
1042
|
+
pointer-events: none;
|
|
1043
|
+
transform: translateY(12px) scale(0.92);
|
|
1044
|
+
}
|
|
1045
|
+
#dock-main {
|
|
1046
|
+
display: inline-flex;
|
|
1047
|
+
align-items: center;
|
|
1048
|
+
justify-content: center;
|
|
1049
|
+
gap: 8px;
|
|
1050
|
+
min-height: 40px;
|
|
1051
|
+
padding: 0 12px;
|
|
1052
|
+
border-radius: 999px;
|
|
1053
|
+
background: linear-gradient(135deg, rgba(34, 211, 238, 0.24), rgba(236, 72, 153, 0.16));
|
|
1054
|
+
font-size: 11px;
|
|
1055
|
+
font-weight: 900;
|
|
1056
|
+
letter-spacing: 0.01em;
|
|
1057
|
+
touch-action: pan-y;
|
|
1058
|
+
}
|
|
1059
|
+
#dock-main:hover {
|
|
1060
|
+
background: linear-gradient(135deg, rgba(34, 211, 238, 0.34), rgba(236, 72, 153, 0.24));
|
|
1061
|
+
}
|
|
1062
|
+
#dock-main .dock-title {
|
|
1063
|
+
white-space: nowrap;
|
|
1064
|
+
font-weight: 900;
|
|
1065
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
1066
|
+
}
|
|
1067
|
+
#dock-collapse,
|
|
1068
|
+
#collapsed-tab,
|
|
1069
|
+
.iw-panel-action,
|
|
1070
|
+
.iw-panel-close {
|
|
1071
|
+
display: inline-flex;
|
|
1072
|
+
align-items: center;
|
|
1073
|
+
justify-content: center;
|
|
1074
|
+
width: 40px;
|
|
1075
|
+
height: 40px;
|
|
1076
|
+
border-radius: 999px;
|
|
1077
|
+
background: rgba(255, 255, 255, 0.06);
|
|
1078
|
+
touch-action: manipulation;
|
|
1079
|
+
}
|
|
1080
|
+
#collapsed-tab {
|
|
1081
|
+
touch-action: pan-y;
|
|
1082
|
+
}
|
|
1083
|
+
#dock-collapse:hover,
|
|
1084
|
+
#collapsed-tab:hover,
|
|
1085
|
+
.iw-panel-action:hover,
|
|
1086
|
+
.iw-panel-close:hover {
|
|
1087
|
+
background: rgba(255, 255, 255, 0.14);
|
|
1088
|
+
}
|
|
1089
|
+
#collapsed-tab {
|
|
1090
|
+
display: none;
|
|
1091
|
+
width: 38px;
|
|
1092
|
+
height: 42px;
|
|
1093
|
+
border-radius: 12px 0 0 12px;
|
|
1094
|
+
background: linear-gradient(135deg, rgba(34, 211, 238, 0.24), rgba(236, 72, 153, 0.18));
|
|
1095
|
+
}
|
|
1096
|
+
#root.position-left #collapsed-tab {
|
|
1097
|
+
border-radius: 0 12px 12px 0;
|
|
1098
|
+
}
|
|
1099
|
+
#root.is-collapsed #collapsed-tab {
|
|
1100
|
+
display: inline-flex;
|
|
1101
|
+
}
|
|
1102
|
+
.iw-logo-icon,
|
|
1103
|
+
#dock-logo,
|
|
1104
|
+
#collapsed-logo {
|
|
1105
|
+
width: 28px;
|
|
1106
|
+
height: 28px;
|
|
1107
|
+
display: inline-block;
|
|
1108
|
+
flex: 0 0 auto;
|
|
1109
|
+
border-radius: 999px;
|
|
1110
|
+
object-fit: contain;
|
|
1111
|
+
}
|
|
1112
|
+
#collapsed-logo {
|
|
1113
|
+
width: 30px;
|
|
1114
|
+
height: 30px;
|
|
1115
|
+
}
|
|
1116
|
+
#fullscreen-logo {
|
|
1117
|
+
width: 48px;
|
|
1118
|
+
height: 48px;
|
|
1119
|
+
display: inline-block;
|
|
1120
|
+
flex: 0 0 auto;
|
|
1121
|
+
border-radius: 12px;
|
|
1122
|
+
object-fit: contain;
|
|
1123
|
+
}
|
|
1124
|
+
#root #fullscreen-header {
|
|
1125
|
+
position: relative;
|
|
1126
|
+
top: auto;
|
|
1127
|
+
left: auto;
|
|
1128
|
+
transform: none;
|
|
1129
|
+
max-width: none;
|
|
1130
|
+
z-index: 1;
|
|
1131
|
+
display: none;
|
|
1132
|
+
width: 100%;
|
|
1133
|
+
align-items: flex-start;
|
|
1134
|
+
justify-content: space-between;
|
|
1135
|
+
gap: 12px;
|
|
1136
|
+
padding: 14px 14px 12px;
|
|
1137
|
+
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
|
1138
|
+
background: var(--intelliweave-panel-bg, linear-gradient(90deg, rgba(34, 211, 238, 0.12), rgba(236, 72, 153, 0.055)));
|
|
1139
|
+
flex-shrink: 0;
|
|
1140
|
+
box-sizing: border-box;
|
|
1141
|
+
}
|
|
1142
|
+
#root.open #fullscreen-header {
|
|
1143
|
+
display: flex;
|
|
1144
|
+
}
|
|
1145
|
+
#root.header-hidden #fullscreen-header {
|
|
1146
|
+
display: none;
|
|
1147
|
+
}
|
|
1148
|
+
#fullscreen-persona {
|
|
1149
|
+
display: flex;
|
|
1150
|
+
align-items: center;
|
|
1151
|
+
gap: 10px;
|
|
1152
|
+
min-width: 0;
|
|
1153
|
+
}
|
|
1154
|
+
#fullscreen-persona-copy {
|
|
1155
|
+
min-width: 0;
|
|
1156
|
+
}
|
|
1157
|
+
.iw-panel-kicker {
|
|
1158
|
+
color: var(--intelliweave-kicker-color, #22D3EE);
|
|
1159
|
+
font-size: 10px;
|
|
1160
|
+
font-weight: 950;
|
|
1161
|
+
letter-spacing: 0.13em;
|
|
1162
|
+
text-transform: uppercase;
|
|
1163
|
+
}
|
|
1164
|
+
#fullscreen-name {
|
|
1165
|
+
display: block;
|
|
1166
|
+
margin-top: 3px;
|
|
1167
|
+
overflow: hidden;
|
|
1168
|
+
font-size: 15px;
|
|
1169
|
+
font-weight: 850;
|
|
1170
|
+
letter-spacing: -0.025em;
|
|
1171
|
+
text-overflow: ellipsis;
|
|
1172
|
+
white-space: nowrap;
|
|
1173
|
+
color: white;
|
|
1174
|
+
}
|
|
1175
|
+
#fullscreen-branding {
|
|
1176
|
+
margin-top: 3px;
|
|
1177
|
+
color: rgba(230, 241, 245, 0.54);
|
|
1178
|
+
font-size: 10px;
|
|
1179
|
+
font-weight: 800;
|
|
1180
|
+
letter-spacing: 0.08em;
|
|
1181
|
+
text-transform: uppercase;
|
|
1182
|
+
}
|
|
1183
|
+
#fullscreen-branding:not(.visible) {
|
|
1184
|
+
display: none;
|
|
1185
|
+
}
|
|
1186
|
+
#panel-actions {
|
|
1187
|
+
display: flex;
|
|
1188
|
+
align-items: center;
|
|
1189
|
+
gap: 8px;
|
|
1190
|
+
flex: 0 0 auto;
|
|
1191
|
+
}
|
|
1192
|
+
.iw-panel-action,
|
|
1193
|
+
.iw-panel-close {
|
|
1194
|
+
border: 1px solid rgba(255, 255, 255, 0.12);
|
|
1195
|
+
border-radius: 12px;
|
|
1196
|
+
background: rgba(255, 255, 255, 0.055);
|
|
1197
|
+
}
|
|
1198
|
+
#root.layout-fullscreen #panel-fullscreen svg {
|
|
1199
|
+
transform: rotate(180deg);
|
|
1200
|
+
}
|
|
1201
|
+
#web-weaver-logo,
|
|
1202
|
+
#pulseanim {
|
|
1203
|
+
display: none !important;
|
|
1204
|
+
}
|
|
1205
|
+
#web-weaver-embed-inner {
|
|
1206
|
+
width: 100%;
|
|
1207
|
+
min-height: 0;
|
|
1208
|
+
max-height: min(440px, 58vh);
|
|
1209
|
+
overflow-x: hidden;
|
|
1210
|
+
overflow-y: auto;
|
|
1211
|
+
-webkit-overflow-scrolling: touch;
|
|
1212
|
+
overscroll-behavior: contain;
|
|
1213
|
+
touch-action: pan-y;
|
|
1214
|
+
display: none;
|
|
1215
|
+
align-content: start;
|
|
1216
|
+
gap: 10px;
|
|
1217
|
+
padding: 12px;
|
|
1218
|
+
box-sizing: border-box;
|
|
1219
|
+
color: inherit;
|
|
1220
|
+
scrollbar-width: none;
|
|
1221
|
+
-ms-overflow-style: none;
|
|
1222
|
+
}
|
|
1223
|
+
#web-weaver-embed-inner::-webkit-scrollbar {
|
|
1224
|
+
width: 0;
|
|
1225
|
+
height: 0;
|
|
1226
|
+
display: none;
|
|
1227
|
+
background: transparent;
|
|
1228
|
+
}
|
|
1229
|
+
#root.open #web-weaver-embed-inner {
|
|
1230
|
+
display: grid;
|
|
1231
|
+
}
|
|
1232
|
+
#root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner {
|
|
1233
|
+
flex: 1 1 auto;
|
|
1234
|
+
min-height: 0;
|
|
1235
|
+
max-height: none;
|
|
1236
|
+
height: auto;
|
|
1237
|
+
overflow-x: hidden;
|
|
1238
|
+
overflow-y: auto;
|
|
1239
|
+
width: 70%;
|
|
1240
|
+
max-width: none;
|
|
1241
|
+
margin: 0 15%;
|
|
1242
|
+
padding: 12px;
|
|
1243
|
+
align-content: start;
|
|
1244
|
+
flex-direction: unset;
|
|
1245
|
+
gap: 10px;
|
|
1246
|
+
}
|
|
1247
|
+
#root.container-mode #web-weaver-embed-inner {
|
|
1248
|
+
flex: 1 1 auto;
|
|
1249
|
+
min-height: 0;
|
|
1250
|
+
max-height: none;
|
|
1251
|
+
height: auto;
|
|
1252
|
+
overflow-x: hidden;
|
|
1253
|
+
overflow-y: auto;
|
|
1254
|
+
padding: 12px;
|
|
1255
|
+
max-width: none;
|
|
1256
|
+
margin: 0;
|
|
1257
|
+
flex-direction: unset;
|
|
1258
|
+
gap: 10px;
|
|
1259
|
+
}
|
|
1260
|
+
#web-weaver-embed-inner .introduction-message,
|
|
1261
|
+
#web-weaver-embed-inner .input,
|
|
1262
|
+
#web-weaver-embed-inner .output,
|
|
1263
|
+
#web-weaver-embed-inner .info-block {
|
|
1264
|
+
max-width: 88%;
|
|
1265
|
+
margin: 0;
|
|
1266
|
+
padding: 10px 11px;
|
|
1267
|
+
border: 1px solid rgba(255, 255, 255, 0.08);
|
|
1268
|
+
border-radius: 16px;
|
|
1269
|
+
background: rgba(255, 255, 255, 0.045);
|
|
1270
|
+
color: inherit;
|
|
1271
|
+
font-size: 13px;
|
|
1272
|
+
line-height: 1.55;
|
|
1273
|
+
opacity: 1;
|
|
1274
|
+
overflow-wrap: anywhere;
|
|
1275
|
+
text-align: left;
|
|
1276
|
+
}
|
|
1277
|
+
#web-weaver-embed-inner .introduction-message,
|
|
1278
|
+
#web-weaver-embed-inner .output,
|
|
1279
|
+
#web-weaver-embed-inner .info-block {
|
|
1280
|
+
justify-self: start;
|
|
1281
|
+
border-color: rgba(255, 255, 255, 0.12);
|
|
1282
|
+
background: linear-gradient(135deg, rgba(255, 255, 255, 0.075), rgba(255, 255, 255, 0.035));
|
|
1283
|
+
}
|
|
1284
|
+
#web-weaver-embed-inner .input {
|
|
1285
|
+
justify-self: end;
|
|
1286
|
+
border-color: rgba(34, 211, 238, 0.25);
|
|
1287
|
+
background: linear-gradient(135deg, rgba(34, 211, 238, 0.18), rgba(34, 211, 238, 0.07));
|
|
1288
|
+
}
|
|
1289
|
+
#root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner .introduction-message {
|
|
1290
|
+
justify-self: start;
|
|
1291
|
+
width: auto;
|
|
1292
|
+
max-width: 88%;
|
|
1293
|
+
margin: 0;
|
|
1294
|
+
padding: 10px 11px;
|
|
1295
|
+
border: 1px solid rgba(255, 255, 255, 0.12);
|
|
1296
|
+
border-radius: 16px;
|
|
1297
|
+
background: linear-gradient(135deg, rgba(255, 255, 255, 0.075), rgba(255, 255, 255, 0.035));
|
|
1298
|
+
text-align: left;
|
|
1299
|
+
}
|
|
1300
|
+
#root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner > .input {
|
|
1301
|
+
align-self: auto;
|
|
1302
|
+
justify-self: end;
|
|
1303
|
+
width: auto;
|
|
1304
|
+
max-width: 50%;
|
|
1305
|
+
margin: 0;
|
|
1306
|
+
padding: 10px 11px;
|
|
1307
|
+
box-sizing: border-box;
|
|
1308
|
+
border-radius: 16px;
|
|
1309
|
+
border-color: rgba(34, 211, 238, 0.25);
|
|
1310
|
+
background: linear-gradient(135deg, rgba(34, 211, 238, 0.18), rgba(34, 211, 238, 0.07));
|
|
1311
|
+
color: inherit;
|
|
1312
|
+
font-size: 13px;
|
|
1313
|
+
line-height: 1.55;
|
|
1314
|
+
opacity: 1;
|
|
1315
|
+
}
|
|
1316
|
+
#root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner > .output,
|
|
1317
|
+
#root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner > .info-block,
|
|
1318
|
+
#root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner > .output-container {
|
|
1319
|
+
justify-self: stretch;
|
|
1320
|
+
width: auto;
|
|
1321
|
+
max-width: none;
|
|
1322
|
+
margin: 0;
|
|
1323
|
+
}
|
|
1324
|
+
#root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner > .output,
|
|
1325
|
+
#root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner > .info-block {
|
|
1326
|
+
align-self: auto;
|
|
1327
|
+
justify-self: start;
|
|
1328
|
+
max-width: 88%;
|
|
1329
|
+
margin: 0;
|
|
1330
|
+
padding: 10px 11px;
|
|
1331
|
+
border-radius: 16px;
|
|
1332
|
+
border-color: rgba(255, 255, 255, 0.12);
|
|
1333
|
+
background: linear-gradient(135deg, rgba(255, 255, 255, 0.075), rgba(255, 255, 255, 0.035));
|
|
1334
|
+
color: inherit;
|
|
1335
|
+
font-size: 13px;
|
|
1336
|
+
line-height: 1.55;
|
|
1337
|
+
opacity: 1;
|
|
1338
|
+
}
|
|
1339
|
+
#root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner > .output-container {
|
|
1340
|
+
display: grid;
|
|
1341
|
+
align-content: start;
|
|
1342
|
+
justify-items: normal;
|
|
1343
|
+
gap: 10px;
|
|
1344
|
+
min-width: 0;
|
|
1345
|
+
}
|
|
1346
|
+
#root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner > .output-container .output,
|
|
1347
|
+
#root.layout-fullscreen:not(.container-mode) #web-weaver-embed-inner > .output-container .info-block {
|
|
1348
|
+
align-self: auto;
|
|
1349
|
+
justify-self: start;
|
|
1350
|
+
max-width: 88%;
|
|
1351
|
+
margin: 0;
|
|
1352
|
+
padding: 10px 11px;
|
|
1353
|
+
border-radius: 16px;
|
|
1354
|
+
border-color: rgba(255, 255, 255, 0.12);
|
|
1355
|
+
background: linear-gradient(135deg, rgba(255, 255, 255, 0.075), rgba(255, 255, 255, 0.035));
|
|
1356
|
+
color: inherit;
|
|
1357
|
+
font-size: 13px;
|
|
1358
|
+
line-height: 1.55;
|
|
1359
|
+
opacity: 1;
|
|
1360
|
+
}
|
|
1361
|
+
#web-weaver-embed-inner .output-container {
|
|
1362
|
+
display: grid;
|
|
1363
|
+
align-content: start;
|
|
1364
|
+
gap: 10px;
|
|
1365
|
+
min-width: 0;
|
|
1366
|
+
}
|
|
1367
|
+
#web-weaver-embed-inner .output > *:first-child,
|
|
1368
|
+
#web-weaver-embed-inner .info-block-text > *:first-child {
|
|
1369
|
+
margin-top: 0;
|
|
1370
|
+
}
|
|
1371
|
+
#web-weaver-embed-inner .output > *:last-child,
|
|
1372
|
+
#web-weaver-embed-inner .info-block-text > *:last-child {
|
|
1373
|
+
margin-bottom: 0;
|
|
1374
|
+
}
|
|
1375
|
+
#web-weaver-embed-inner .output p,
|
|
1376
|
+
#web-weaver-embed-inner .info-block-text p {
|
|
1377
|
+
margin: 0 0 0.75rem;
|
|
1378
|
+
}
|
|
1379
|
+
#web-weaver-embed-inner .output strong,
|
|
1380
|
+
#web-weaver-embed-inner .info-block-text strong {
|
|
1381
|
+
color: #EAF8FF;
|
|
1382
|
+
font-weight: 950;
|
|
1383
|
+
}
|
|
1384
|
+
#web-weaver-embed-inner .output code,
|
|
1385
|
+
#web-weaver-embed-inner .info-block-text code {
|
|
1386
|
+
padding: 0.08rem 0.28rem;
|
|
1387
|
+
border-radius: 6px;
|
|
1388
|
+
background: rgba(255, 255, 255, 0.08);
|
|
1389
|
+
color: #67E8F9;
|
|
1390
|
+
font-size: 0.78em;
|
|
1391
|
+
}
|
|
1392
|
+
#web-weaver-embed-inner .suggestion-button {
|
|
1393
|
+
width: 100%;
|
|
1394
|
+
min-height: 38px;
|
|
1395
|
+
margin: 0;
|
|
1396
|
+
border: 1px solid rgba(236, 72, 153, 0.22);
|
|
1397
|
+
border-radius: 12px;
|
|
1398
|
+
background: linear-gradient(135deg, rgba(236, 72, 153, 0.11), rgba(34, 211, 238, 0.07));
|
|
1399
|
+
color: inherit;
|
|
1400
|
+
padding: 8px 10px;
|
|
1401
|
+
box-sizing: border-box;
|
|
1402
|
+
cursor: pointer;
|
|
1403
|
+
font-size: 12px;
|
|
1404
|
+
font-weight: 820;
|
|
1405
|
+
line-height: 1.2;
|
|
1406
|
+
text-align: left;
|
|
1407
|
+
transition: transform 140ms ease, border-color 140ms ease, background 140ms ease;
|
|
1408
|
+
}
|
|
1409
|
+
#web-weaver-embed-inner .suggestion-button:hover {
|
|
1410
|
+
transform: translateY(-1px);
|
|
1411
|
+
border-color: rgba(236, 72, 153, 0.42);
|
|
1412
|
+
background: linear-gradient(135deg, rgba(236, 72, 153, 0.17), rgba(34, 211, 238, 0.12));
|
|
1413
|
+
}
|
|
1414
|
+
#web-weaver-embed-inner .info-block {
|
|
1415
|
+
display: flex;
|
|
1416
|
+
gap: 8px;
|
|
1417
|
+
color: rgba(230, 241, 245, 0.72);
|
|
1418
|
+
font-size: 11px;
|
|
1419
|
+
}
|
|
1420
|
+
#emoji-action-overlay {
|
|
1421
|
+
z-index: 40;
|
|
1422
|
+
}
|
|
1423
|
+
#interaction-bar {
|
|
1424
|
+
display: none;
|
|
1425
|
+
width: 100%;
|
|
1426
|
+
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
|
1427
|
+
}
|
|
1428
|
+
#root.open #interaction-bar {
|
|
1429
|
+
display: flex;
|
|
1430
|
+
}
|
|
1431
|
+
#poweredby {
|
|
1432
|
+
display: none;
|
|
1433
|
+
width: 100%;
|
|
1434
|
+
height: 21px;
|
|
1435
|
+
align-items: center;
|
|
1436
|
+
justify-content: center;
|
|
1437
|
+
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
|
1438
|
+
background: rgba(7, 11, 13, 0.38);
|
|
1439
|
+
color: rgba(230, 241, 245, 0.62);
|
|
1440
|
+
font-size: 9px;
|
|
1441
|
+
}
|
|
1442
|
+
#root.open #poweredby {
|
|
1443
|
+
display: flex;
|
|
1444
|
+
}
|
|
1445
|
+
:host([data-theme="light"]) #root,
|
|
1446
|
+
#root.theme-light {
|
|
1447
|
+
--intelliweave-dock-bg: linear-gradient(135deg, rgba(255, 255, 255, 0.96), rgba(232, 241, 247, 0.90));
|
|
1448
|
+
--intelliweave-panel-bg: linear-gradient(145deg, rgba(255, 255, 255, 0.98), rgba(232, 241, 247, 0.94)), radial-gradient(circle at 100% 0, rgba(34, 211, 238, 0.12), transparent 38%);
|
|
1449
|
+
color: var(--intelliweave-text-color, #07111D);
|
|
1450
|
+
box-shadow: 0 14px 38px rgba(15, 35, 50, 0.18), 0 0 28px rgba(34, 211, 238, 0.10);
|
|
1451
|
+
}
|
|
1452
|
+
@media (max-width: 768px) {
|
|
1453
|
+
#root.open:not(.layout-fullscreen):not(.container-mode) {
|
|
1454
|
+
right: 8px !important;
|
|
1455
|
+
bottom: calc(8px + env(safe-area-inset-bottom)) !important;
|
|
1456
|
+
left: auto !important;
|
|
1457
|
+
top: auto !important;
|
|
1458
|
+
width: min(390px, calc(100vw - 16px));
|
|
1459
|
+
max-height: min(78vh, 680px);
|
|
1460
|
+
}
|
|
1461
|
+
#web-weaver-embed-inner {
|
|
1462
|
+
max-height: min(54vh, 440px);
|
|
1463
|
+
}
|
|
1464
|
+
#root.layout-fullscreen:not(.container-mode) {
|
|
1465
|
+
top: max(0px, env(safe-area-inset-top)) !important;
|
|
1466
|
+
right: max(0px, env(safe-area-inset-right)) !important;
|
|
1467
|
+
bottom: max(0px, env(safe-area-inset-bottom)) !important;
|
|
1468
|
+
left: max(0px, env(safe-area-inset-left)) !important;
|
|
1469
|
+
border-radius: 0;
|
|
1470
|
+
}
|
|
1471
|
+
#dock-main .dock-title {
|
|
1472
|
+
max-width: 112px;
|
|
1473
|
+
overflow: hidden;
|
|
1474
|
+
text-overflow: ellipsis;
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
|
|
786
1478
|
</style>
|
|
787
1479
|
|
|
788
1480
|
<!-- Embed font (default: Karla; updated dynamically when a different font is configured) -->
|
|
789
1481
|
<link id='google-font-link' href="https://fonts.googleapis.com/css2?family=Karla:ital,wght@0,200..800;1,200..800&display=swap" rel="stylesheet">
|
|
1482
|
+
<!-- Inter font for dock title -->
|
|
1483
|
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@700;800;900&display=swap" rel="stylesheet">
|
|
790
1484
|
|
|
791
1485
|
<!-- Root element -->
|
|
792
1486
|
<div id='root' class='hidden'>
|
|
793
1487
|
|
|
1488
|
+
<!-- Collapsed dock tab -->
|
|
1489
|
+
<button id='collapsed-tab' type='button' aria-label='Open IntelliWeave assistant'>
|
|
1490
|
+
<img id='collapsed-logo' class='iw-logo-icon' alt='' />
|
|
1491
|
+
</button>
|
|
1492
|
+
|
|
1493
|
+
<!-- Floating dock launcher -->
|
|
1494
|
+
<div id='dock-launcher'>
|
|
1495
|
+
<button id='dock-main' type='button' aria-label='Open IntelliWeave assistant'>
|
|
1496
|
+
<img id='dock-logo' class='iw-logo-icon' alt='' />
|
|
1497
|
+
<span id='dock-brand-name' class='dock-title'>Ask</span>
|
|
1498
|
+
</button>
|
|
1499
|
+
<button id='dock-collapse' type='button' aria-label='Collapse IntelliWeave assistant'>
|
|
1500
|
+
<svg width='18' height='18' viewBox='0 0 24 24' aria-hidden='true'><path d='M9 6l6 6-6 6' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/></svg>
|
|
1501
|
+
</button>
|
|
1502
|
+
</div>
|
|
1503
|
+
|
|
794
1504
|
<!-- Logo -->
|
|
795
|
-
${
|
|
1505
|
+
${oe.add({id:"web-weaver-logo",logo:this.attr.logo})}
|
|
796
1506
|
<div id='pulseanim' class="circle pulse"></div>
|
|
797
1507
|
|
|
798
1508
|
|
|
799
1509
|
|
|
800
|
-
<!--
|
|
1510
|
+
<!-- Panel header -->
|
|
801
1511
|
<div id='fullscreen-header'>
|
|
802
1512
|
<div id='fullscreen-persona'>
|
|
803
1513
|
<img id='fullscreen-logo' src='' alt='' />
|
|
804
|
-
<
|
|
1514
|
+
<div id='fullscreen-persona-copy'>
|
|
1515
|
+
<div id='brand-name' class='iw-panel-kicker'>IntelliWeave</div>
|
|
1516
|
+
<span id='fullscreen-name'></span>
|
|
1517
|
+
</div>
|
|
805
1518
|
</div>
|
|
806
|
-
<div id='
|
|
807
|
-
<
|
|
808
|
-
|
|
1519
|
+
<div id='panel-actions'>
|
|
1520
|
+
<button id='panel-fullscreen' class='iw-panel-action' type='button' aria-label='Toggle fullscreen'>
|
|
1521
|
+
<svg width='19' height='19' viewBox='0 0 24 24' aria-hidden='true'><path d='M8 3H3v5M16 3h5v5M21 16v5h-5M3 16v5h5' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/></svg>
|
|
1522
|
+
</button>
|
|
1523
|
+
<button id='panel-close' class='iw-panel-close' type='button' aria-label='Close IntelliWeave assistant'>
|
|
1524
|
+
<svg width='19' height='19' viewBox='0 0 24 24' aria-hidden='true'><path d='M6 6l12 12M18 6L6 18' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round'/></svg>
|
|
1525
|
+
</button>
|
|
809
1526
|
</div>
|
|
810
1527
|
</div>
|
|
811
1528
|
|
|
1529
|
+
<!-- Visual effects overlay -->
|
|
1530
|
+
<div id='emoji-action-overlay' aria-hidden='true'></div>
|
|
1531
|
+
|
|
812
1532
|
<!-- Inner container contains all the UI when the panel is open -->
|
|
813
1533
|
<div id='web-weaver-embed-inner'>
|
|
814
1534
|
</div>
|
|
815
1535
|
|
|
816
1536
|
<!-- LLM selector panel -->
|
|
817
|
-
${
|
|
1537
|
+
${se.add({id:"llm-selector-panel"})}
|
|
818
1538
|
|
|
819
1539
|
<!-- Interaction panel -->
|
|
820
|
-
${
|
|
1540
|
+
${ne.add({id:"interaction-bar"})}
|
|
821
1541
|
|
|
822
1542
|
|
|
823
1543
|
<!-- Powered by IW banner -->
|
|
824
|
-
<div id='poweredby'>
|
|
825
|
-
<span>powered by <strong>IntelliWeave <i class='green-accent'>AI</i></strong></span>
|
|
826
|
-
</div>
|
|
1544
|
+
<div id='poweredby'></div>
|
|
827
1545
|
|
|
828
1546
|
</div>
|
|
829
1547
|
|
|
830
|
-
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastFontFamily="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new R
|
|
1548
|
+
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastFontFamily="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._lastBrandName="";this._isProcessing=!1;this.ai=new j,R.isSupported&&(this.ai.audio=new R(this.ai))}onCreate(){f().embed&&k.warn("Only one <web-weaver-embed> element should be on the page."),f().embed=this;let e=f();k.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(k.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.layout&&!this.attr.layout&&(k.debug("[WebWeaverEmbed] Setting layout from client config:",e.layout),this.attr.layout=e.layout),e.positioningMode&&!this.attr.positioningMode&&(k.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(k.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(k.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(k.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(k.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),k.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",o=>this.onContainerClick(o)),this.child("web-weaver-logo").addEventListener("click",o=>this.onLogoClick(o)),this.child("dock-main").addEventListener("click",o=>this.onDockOpenClick(o)),this.child("dock-collapse").addEventListener("click",o=>this.onDockCollapseClick(o)),this.child("collapsed-tab").addEventListener("click",o=>this.onCollapsedOpenClick(o)),this.child("panel-fullscreen").addEventListener("click",o=>this.onPanelFullscreenClick(o)),this.child("panel-close").addEventListener("click",o=>this.onPanelCloseClick(o)),this.child("collapsed-tab").addEventListener("pointerdown",o=>this.onSwipePointerDown(o)),this.child("collapsed-tab").addEventListener("pointerup",o=>this.onCollapsedSwipePointerUp(o)),this.child("dock-main").addEventListener("pointerdown",o=>this.onSwipePointerDown(o)),this.child("dock-main").addEventListener("pointerup",o=>this.onDockSwipePointerUp(o)),this.child("root").addEventListener("pointerdown",o=>this.onSwipePointerDown(o)),this.child("root").addEventListener("pointerup",o=>this.onPanelSwipePointerUp(o)),this.child("root").addEventListener("pointercancel",o=>this.onSwipePointerCancel()),this.child("interaction-bar").addEventListener("input-message",o=>this.processInput(o.detail)),this.child("interaction-bar").addEventListener("llm-button-click",o=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",o=>this.onLLMModelSelect(o)),this.child("web-weaver-embed-inner").addEventListener("scroll",o=>this.onContentScroll(o)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"_iw_image_instructions",type:"info",name:"Using Images",content:`
|
|
831
1549
|
You can display images in Markdown format, example: 
|
|
832
|
-
Image URLs must be absolute. When using an image URL from the knowledge base, include all parameters.`,isContext:!0});let n=this.attr.apiKey||g().apiKey;if(!n)return v.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(n).then(o=>{this.config=o.config,g().introductionMessage||(g().introductionMessage=this.config.introductionMessage),g().analytics=this.config.analytics!==void 0?!!this.config.analytics:g().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.config.managedBy&&this.updateBrandingFor(this.config.managedBy),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",disabled:!this.ai.flags.allowSuggestionButtons,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:s=>(this.suggestions.push(s.text),"Suggestion button added")}),this.resetConversation()}).catch(o=>{v.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");if(s){let r=o?.message||o?.toString()||"Unknown error";s.innerHTML=`<div class="output" style="color: red; padding: 20px;">${r}</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 n=this.parseColorToRGB(t);if(!n){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.setProperty("--intelliweave-interaction-bg",t);return}let{r:o,g:s,b:r}=n;e.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${r}, 0.65)`),e.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(r*.85)}, 0.85)`),e.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${r}, 0.9)`)}parseColorToRGB(e){if(!e)return null;let t=e.trim();if(t.startsWith("#")){let n=t.slice(1);if(n.length===3){let o=parseInt(n[0]+n[0],16),s=parseInt(n[1]+n[1],16),r=parseInt(n[2]+n[2],16);return{r:o,g:s,b:r}}if(n.length===6){let o=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),r=parseInt(n.slice(4,6),16);return{r:o,g:s,b:r}}return null}if(t.startsWith("rgb")){let n=t.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return n?{r:Math.max(0,Math.min(255,Math.round(Number(n[1])))),g:Math.max(0,Math.min(255,Math.round(Number(n[2])))),b:Math.max(0,Math.min(255,Math.round(Number(n[3]))))}:null}return null}adjustLogoPadding(e){let t=new Image;t.onload=()=>{let l=t.naturalWidth/t.naturalHeight,d=l>1?96/l:96,c=l<=1?10:0,p=(96+d)/2-48,h=Math.max(p+15+c,40+c);this.style.setProperty("--logo-top-margin",`${Math.round(c)}px`);let f=this.child("web-weaver-embed-inner");f&&f.style.setProperty("--logo-bottom-padding",`${Math.round(h)}px`)},t.src=e}applyConfigStylesAndAttributes(){let e=this.config,t=this.child("root");if(!t)return;let n=!1,s=this.attr.logo||e.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,n=!0;let N=this.child("web-weaver-logo");N&&(N.setAttribute("logo",s),this.adjustLogoPadding(s))}let r=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),d=e.name||"";d!==this._lastPersonaName&&(this._lastPersonaName=d,l&&(l.textContent=d),n=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",r&&(s?(r.src=s,r.style.display=""):r.style.display="none"),n=!0);let c=this.root?.getElementById("fullscreen-header"),u=(this.attr.header||"").toLowerCase();if(c){let N=u==="hidden"||u==="none"||u==="false";c.style.display=!N&&(s||d)?"":"none"}let h=this.attr.background||e.background;h!==this._lastBackground&&(this._lastBackground=h,n=!0,h?(t.style.background=h,t.style.setProperty("--intelliweave-persona-bg",h),this.applyPersonaColorVariants(t,h)):(t.style.background="",t.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(t,void 0)));let y=this.attr.textColor||e.textColor,M=this.child("interaction-bar");y!==this._lastTextColor&&(this._lastTextColor=y,n=!0,y?(t.style.color=y,t.style.setProperty("--intelliweave-user-bubble-text",y),t.style.setProperty("--intelliweave-assistant-bubble-text",y),M&&M.setAttribute("textColor",y)):(t.style.color="",t.style.removeProperty("--intelliweave-user-bubble-text"),t.style.removeProperty("--intelliweave-assistant-bubble-text"),M&&M.removeAttribute("textColor")));let T={Inter:"Inter:wght@300;400;500;600;700",Roboto:"Roboto:wght@300;400;500;700","Open Sans":"Open+Sans:wght@300;400;500;600;700",Poppins:"Poppins:wght@300;400;500;600;700",Lato:"Lato:wght@300;400;700","DM Sans":"DM+Sans:wght@300;400;500;600;700",Nunito:"Nunito:wght@300;400;500;600;700","Plus Jakarta Sans":"Plus+Jakarta+Sans:wght@300;400;500;600;700",Montserrat:"Montserrat:wght@300;400;500;600;700"},B=this.attr.fontFamily||e.fontFamily;if(B!==this._lastFontFamily){this._lastFontFamily=B,n=!0,B?t.style.setProperty("--intelliweave-font-family",B):t.style.removeProperty("--intelliweave-font-family");let N=this.root?.getElementById("google-font-link");if(N){let Ye=(B||"Karla").replace(/['"]/g,"").split(",")[0].trim(),Ke=T[Ye];Ke?N.href=`https://fonts.googleapis.com/css2?family=${Ke}&display=swap`:(!B||Ye==="Karla")&&(N.href="https://fonts.googleapis.com/css2?family=Karla:ital,wght@0,200..800;1,200..800&display=swap")}}let te=this.attr.displayMode||e.displayMode||"closed";te!==this._lastDisplayMode&&(this._lastDisplayMode=te,n=!0,te==="open"&&!this.attr.open&&(this.attr.open=!0));let ke=this.attr.layout||e.layout||"widget";ke!==this._lastLayout&&(this._lastLayout=ke,n=!0);let Ce=this.attr.positioningMode||e.positioningMode||"fixed";Ce!==this._lastPositioningMode&&(this._lastPositioningMode=Ce,n=!0);let Ee=this.attr.positionX||e.positionX||"right";Ee!==this._lastPositionX&&(this._lastPositionX=Ee,n=!0);let Ne=this.attr.positionY||e.positionY||"bottom";Ne!==this._lastPositionY&&(this._lastPositionY=Ne,n=!0);let je=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,Ae=je!==void 0?je:e.offsetX!==void 0?e.offsetX:20;Ae!==this._lastOffsetX&&(this._lastOffsetX=Ae,n=!0);let Oe=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,Le=Oe!==void 0?Oe:e.offsetY!==void 0?e.offsetY:20;Le!==this._lastOffsetY&&(this._lastOffsetY=Le,n=!0),n&&v.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:t.style.background,finalTextColor:t.style.color,finalDisplayMode:te,finalLayout:ke,finalPositioningMode:Ce,finalPositionX:Ee,finalPositionY:Ne,finalOffsetX:Ae,finalOffsetY:Le})}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.child("interaction-bar").attr.layout=this._lastLayout||"widget",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),w(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;w(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 n=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",r=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;n==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),n!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",o==="left"?e.style.left=r+"px":e.style.right=r+"px",s==="top"?e.style.top=l+"px":e.style.bottom=l+"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(){g().embed==this&&(g().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=g().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let n of g().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=n,o.addEventListener("click",s=>this.onSuggestionClick(s,n)),e.appendChild(o)}}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 r of Array.from(t.querySelectorAll(".suggestion-button")))r.remove();this.attr.focusID="";let n=document.createElement("div");n.className="input",n.innerText=e,t.appendChild(n);let o=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),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"}),await this.ai.sendMessage(e);for(let r of this.suggestions){let l=document.createElement("div");l.className="suggestion-button",l.innerText=r,l.addEventListener("click",d=>this.onSuggestionClick(d,r)),this.currentOutputElement.appendChild(l)}}catch(n){v.error("Failed to process input:",n);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+n.message,t.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",r=>this.resetConversation()),t.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e,t){let n=[];for(let o of e)for(let s=0;s<(o.sections?.length||0);s++){let r=o.sections[s],l=`msgelem-${o.id||""}_${s}_${r.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),r.type=="thinking"){if(!r.text)continue;let d=r.text||"";d.includes(`
|
|
833
|
-
|
|
834
|
-
|
|
1550
|
+
Image URLs must be absolute. When using an image URL from the knowledge base, include all parameters.`,isContext:!0});let n=this.attr.apiKey||f().apiKey;if(!n)return k.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(n).then(o=>{this.config=o.config,f().introductionMessage||(f().introductionMessage=this.config.introductionMessage),f().analytics=this.config.analytics!==void 0?!!this.config.analytics:f().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.updateBrandingFor(this.config.managedBy),this.ai.knowledgeBase.addEntry({id:"_iw_suggestion_action_instructions",type:"info",name:"Suggestion buttons",content:`
|
|
1551
|
+
Suggest follow-up responses by embedding standalone action blocks: <[[ {"action":"suggestion","text":"Show me pricing"} ]]>
|
|
1552
|
+
The block is hidden from the user and will be displayed as clickable buttons.
|
|
1553
|
+
Use concise text that can be sent as the user's next message.
|
|
1554
|
+
Use multiple blocks when multiple suggestions are useful.
|
|
1555
|
+
Continue writing normal visible text outside the block.`,isContext:!0,disabled:!this.ai.flags.allowSuggestionButtons}),this.ai.knowledgeBase.addEntry({id:"_iw_emoji_action_instructions",type:"info",name:"Emoji visual effects",content:`
|
|
1556
|
+
You may trigger a visual emoji effect by embedding a standalone action block: <[[ {"action":"emoji","emoji":"\u{1F44D}"} ]]>
|
|
1557
|
+
The block is hidden from the user.
|
|
1558
|
+
Use this sparingly for celebration, confirmation, delight, or matching user emotion.
|
|
1559
|
+
Only use one emoji character or a short emoji sequence.
|
|
1560
|
+
Continue writing normal visible text outside the block.`,isContext:!0,disabled:!this.ai.flags.allowEmojiActions}),this.resetConversation()}).catch(o=>{k.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");if(s){let r=o?.message||o?.toString()||"Unknown error";s.innerHTML=`<div class="output" style="padding: 20px;"><span style="display: inline-block; background-color: #fee; color: #c00; padding: 8px 12px; border-radius: 6px; border: 1px solid #fcc;">${r}</span></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 n=this.parseColorToRGB(t);if(!n){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.setProperty("--intelliweave-interaction-bg",t);return}let{r:o,g:s,b:r}=n;e.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${r}, 0.65)`),e.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(r*.85)}, 0.85)`),e.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${r}, 0.9)`)}parseColorToRGB(e){if(!e)return null;let t=e.trim();if(t.startsWith("#")){let n=t.slice(1);if(n.length===3){let o=parseInt(n[0]+n[0],16),s=parseInt(n[1]+n[1],16),r=parseInt(n[2]+n[2],16);return{r:o,g:s,b:r}}if(n.length===6){let o=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),r=parseInt(n.slice(4,6),16);return{r:o,g:s,b:r}}return null}if(t.startsWith("rgb")){let n=t.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return n?{r:Math.max(0,Math.min(255,Math.round(Number(n[1])))),g:Math.max(0,Math.min(255,Math.round(Number(n[2])))),b:Math.max(0,Math.min(255,Math.round(Number(n[3]))))}:null}return null}computeKickerColor(e){let t=this.parseColorToRGB(e);if(!t)return null;let n=t.r/255,o=t.g/255,s=t.b/255,r=Math.max(n,o,s),a=Math.min(n,o,s),u=(r+a)/2,d=0,c=0;if(r!==a){let S=r-a;switch(c=u>.5?S/(2-r-a):S/(r+a),r){case n:d=((o-s)/S+(o<s?6:0))/6;break;case o:d=((s-n)/S+2)/6;break;case s:d=((n-o)/S+4)/6;break}}let p=(d+1/3)%1,h=Math.min(1,Math.max(.5,c+.3)),m=u<.5?Math.min(.85,u+.45):Math.max(.55,u-.1),b=(S,re,M)=>(M<0&&(M+=1),M>1&&(M-=1),M<1/6?S+(re-S)*6*M:M<1/2?re:M<2/3?S+(re-S)*(2/3-M)*6:S),y=m<.5?m*(1+h):m+h-m*h,v=2*m-y,A=Math.round(b(v,y,p+1/3)*255),N=Math.round(b(v,y,p)*255),z=Math.round(b(v,y,p-1/3)*255);return`rgb(${A}, ${N}, ${z})`}adjustLogoPadding(e){let t=new Image;t.onload=()=>{let a=t.naturalWidth/t.naturalHeight,u=a>1?96/a:96,d=a<=1?10:0,p=(96+u)/2-48,h=Math.max(p+15+d,40+d);this.style.setProperty("--logo-top-margin",`${Math.round(d)}px`);let m=this.child("web-weaver-embed-inner");m&&m.style.setProperty("--logo-bottom-padding",`${Math.round(h)}px`)},t.src=e}applyConfigStylesAndAttributes(){let e=this.config,t=this.child("root");if(!t)return;let n=!1,s=this.attr.logo||e.logo||Ee;if(s&&s!==this._lastLogo){this._lastLogo=s,n=!0;let w=this.child("web-weaver-logo");w&&(w.setAttribute("logo",s),this.adjustLogoPadding(s));let $=this.root?.getElementById("dock-logo"),q=this.root?.getElementById("collapsed-logo");$&&($.src=s),q&&(q.src=s)}let r=this.root?.getElementById("fullscreen-logo"),a=this.root?.getElementById("fullscreen-name"),u=e.name||"IntelliWeave";u!==this._lastPersonaName&&(this._lastPersonaName=u,a&&(a.textContent=u),n=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",r&&(s?(r.src=s,r.style.display=""):r.style.display="none"),n=!0);let d=this.root?.getElementById("fullscreen-header"),c=(this.attr.header||"").toLowerCase();if(d){let w=c==="hidden"||c==="none"||c==="false";d.style.display=!w&&(s||u)?"":"none"}let h=this.attr.background||e.background;if(h!==this._lastBackground)if(this._lastBackground=h,n=!0,h){t.style.background=h,t.style.setProperty("--intelliweave-persona-bg",h),t.style.setProperty("--intelliweave-panel-bg",h),this.applyPersonaColorVariants(t,h);let w=this.computeKickerColor(h);w?t.style.setProperty("--intelliweave-kicker-color",w):t.style.removeProperty("--intelliweave-kicker-color")}else t.style.background="",t.style.removeProperty("--intelliweave-persona-bg"),t.style.removeProperty("--intelliweave-panel-bg"),t.style.removeProperty("--intelliweave-kicker-color"),this.applyPersonaColorVariants(t,void 0);let m=this.attr.brandName,b=e.managedBy?.toLowerCase()==="chatterly"?"Chatterly":"IntelliWeave",y=m||e.brandName||b;if(y!==this._lastBrandName){this._lastBrandName=y,n=!0;let w=this.root?.getElementById("brand-name");w&&(w.textContent=y)}let v=this.child("interaction-bar");if(v){let w;e.managedBy?.toLowerCase()==="chatterly"?w=`linear-gradient(135deg, ${h||"#425570"}, 55%, #f3f1ee)`:h?w=`linear-gradient(135deg, ${h}, 55%, #f3f1ee)`:w="linear-gradient(135deg, #0b7aa1, 55%, #a34b0d)",v.style.setProperty("--iw-send-btn-gradient",w)}let N=this.attr.textColor||e.textColor,z=this.child("interaction-bar");N!==this._lastTextColor&&(this._lastTextColor=N,n=!0,N?(t.style.color=N,t.style.setProperty("--intelliweave-user-bubble-text",N),t.style.setProperty("--intelliweave-assistant-bubble-text",N),z&&z.setAttribute("textColor",N)):(t.style.color="",t.style.removeProperty("--intelliweave-user-bubble-text"),t.style.removeProperty("--intelliweave-assistant-bubble-text"),z&&z.removeAttribute("textColor")));let S={Inter:"Inter:wght@300;400;500;600;700",Roboto:"Roboto:wght@300;400;500;700","Open Sans":"Open+Sans:wght@300;400;500;600;700",Poppins:"Poppins:wght@300;400;500;600;700",Lato:"Lato:wght@300;400;700","DM Sans":"DM+Sans:wght@300;400;500;600;700",Nunito:"Nunito:wght@300;400;500;600;700","Plus Jakarta Sans":"Plus+Jakarta+Sans:wght@300;400;500;600;700",Montserrat:"Montserrat:wght@300;400;500;600;700"},M=this.attr.fontFamily||e.fontFamily;if(M!==this._lastFontFamily){this._lastFontFamily=M,n=!0,M?t.style.setProperty("--intelliweave-font-family",M):t.style.removeProperty("--intelliweave-font-family");let w=this.root?.getElementById("google-font-link");if(w){let $=(M||"Karla").replace(/['"]/g,"").split(",")[0].trim(),q=S[$];q?w.href=`https://fonts.googleapis.com/css2?family=${q}&display=swap`:(!M||$==="Karla")&&(w.href="https://fonts.googleapis.com/css2?family=Karla:ital,wght@0,200..800;1,200..800&display=swap")}}let ae=this.attr.displayMode||e.displayMode||"closed";ae!==this._lastDisplayMode&&(this._lastDisplayMode=ae,n=!0,ae==="open"&&!this.attr.open&&(this.attr.open=!0));let We=this.attr.layout||e.layout||"widget";We!==this._lastLayout&&(this._lastLayout=We,n=!0);let Ge=this.attr.positioningMode||e.positioningMode||"fixed";Ge!==this._lastPositioningMode&&(this._lastPositioningMode=Ge,n=!0);let Ze=this.attr.positionX||e.positionX||"right";Ze!==this._lastPositionX&&(this._lastPositionX=Ze,n=!0);let Pe=this.attr.positionY||e.positionY||"bottom";Pe!==this._lastPositionY&&(this._lastPositionY=Pe,n=!0);let Qe=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,Xe=Qe!==void 0?Qe:e.offsetX!==void 0?e.offsetX:20;Xe!==this._lastOffsetX&&(this._lastOffsetX=Xe,n=!0);let $e=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,Re=$e!==void 0?$e:e.offsetY!==void 0?e.offsetY:20;Re!==this._lastOffsetY&&(this._lastOffsetY=Re,n=!0),n&&k.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:t.style.background,finalTextColor:t.style.color,finalDisplayMode:ae,finalLayout:We,finalPositioningMode:Ge,finalPositionX:Ze,finalPositionY:Pe,finalOffsetX:Xe,finalOffsetY:Re})}onUpdate(){this.applyConfigStylesAndAttributes();let e=this.child("root"),t=this._lastLayout||"widget",n=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",r=this._lastOffsetX!==void 0?this._lastOffsetX:20,a=this._lastOffsetY!==void 0?this._lastOffsetY:20,d=(this._lastDisplayMode||"closed")==="open"||t==="fullscreen"||n==="container",c=t==="fullscreen"||n==="container";d&&!this.attr.open&&(this.attr.open=!0);let p=!!this.attr.open,h=!!this.attr.collapsed&&!p&&!d,m=p&&(c||!!this.state.panelFullscreen);if(this.child("web-weaver-embed-inner").style.display=p?"":"none",this.child("interaction-bar").style.display=p?"":"none",this.child("fullscreen-header").style.display=p?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display="none",this.child("poweredby").style.display=p?"flex":"none",this.child("interaction-bar").attr.layout=m?"fullscreen":"widget",this.child("panel-close").style.display=d?"none":"",this.child("panel-fullscreen").style.display=c?"none":"",p&&m!==this._previousFullscreenState&&this.refreshContentScrollability(),this._previousFullscreenState=m,p&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),I(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!p&&this._previousOpenState){let y=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;I(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:y}})}this._previousOpenState=p,e.classList.toggle("open",p),e.classList.toggle("is-collapsed",h),e.classList.toggle("layout-fullscreen",m),e.classList.toggle("position-left",o==="left"),e.classList.toggle("position-top",s==="top");let b=(this.attr.header||"").toLowerCase();if(e.classList.toggle("header-hidden",b==="hidden"||b==="none"||b==="false"),n==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),n!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",!m)){let y=h?a+56:a;h?o==="left"?e.style.left="0px":e.style.right="0px":o==="left"?e.style.left=r+"px":e.style.right=r+"px",s==="top"?e.style.top=y+"px":e.style.bottom=y+"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((y,v)=>(v.priority||0)-(y.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){f().embed==this&&(f().embed=void 0)}onContainerClick(e){if(this._suppressNextContainerClick){this._suppressNextContainerClick=!1,e.preventDefault(),e.stopPropagation();return}let t=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&t!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.collapsed="",this.attr.open=!0))}onDockOpenClick(e){e.preventDefault(),e.stopPropagation(),this.openFromDock()}onDockCollapseClick(e){e.preventDefault(),e.stopPropagation(),this.collapseDock()}onCollapsedOpenClick(e){e.preventDefault(),e.stopPropagation(),this.showDockFromCollapsed()}onPanelCollapseClick(e){e.preventDefault(),e.stopPropagation(),this.collapseDock()}onPanelFullscreenClick(e){e.preventDefault(),e.stopPropagation();let t=this._lastLayout||"widget",n=this._lastPositioningMode||"fixed";t==="fullscreen"||n==="container"||(this.state.panelFullscreen=!this.state.panelFullscreen)}onPanelCloseClick(e){e.preventDefault(),e.stopPropagation(),this.closePanel()}isForcedOpen(){let e=this._lastDisplayMode||"closed",t=this._lastLayout||"widget",n=this._lastPositioningMode||"fixed";return e==="open"||t==="fullscreen"||n==="container"}openFromDock(){this._returnToCollapsedOnSwipeClose=!1,this.attr.collapsed="",this.attr.open=!0}refreshContentScrollability(){let e=this.child("web-weaver-embed-inner");if(!e||typeof window>"u")return;let t=e.scrollTop;e.style.setProperty("-webkit-overflow-scrolling","auto"),e.style.overflowY="hidden",window.requestAnimationFrame(()=>{e.style.overflowY="auto",e.style.setProperty("-webkit-overflow-scrolling","touch"),e.scrollTop=Math.min(t,Math.max(0,e.scrollHeight-e.clientHeight))})}showDockFromCollapsed(){this._returnToCollapsedOnSwipeClose=!0,this.state.panelFullscreen=!1,this.attr.collapsed=""}openFromCollapsed(){this._returnToCollapsedOnSwipeClose=!0,this.state.panelFullscreen=!1,this.attr.collapsed="",this.attr.open=!0}closePanel(){if(this.isForcedOpen())return;let e=this._returnToCollapsedOnSwipeClose;this._returnToCollapsedOnSwipeClose=!1,this.state.panelFullscreen=!1,this.attr.open="",e&&(this.attr.collapsed=!0)}collapseDock(){this.isForcedOpen()||(this._returnToCollapsedOnSwipeClose=!1,this.state.panelFullscreen=!1,this.attr.open="",this.attr.collapsed=!0)}onSwipePointerDown(e){if(typeof window>"u"||window.innerWidth>768||e.pointerType==="mouse"&&e.button!==0)return;let t=e.currentTarget,n=e.target;if(!(!(t?.id==="collapsed-tab"||t?.id==="dock-main")&&n?.closest?.('input, textarea, select, [contenteditable="true"], button'))){this._swipeStart={x:e.clientX,y:e.clientY};try{t?.setPointerCapture?.(e.pointerId)}catch{}}}onSwipePointerCancel(){this._swipeStart=void 0}inwardSwipeDirection(){return(this._lastPositionX||"right")==="left"?"right":"left"}outwardSwipeDirection(){return this.inwardSwipeDirection()==="left"?"right":"left"}didSwipe(e,t){let n=this._swipeStart;if(this._swipeStart=void 0,!n||typeof window>"u"||window.innerWidth>768)return!1;let o=e.clientX-n.x,s=e.clientY-n.y;if(Math.abs(o)<48||Math.abs(s)>72||Math.abs(o)<Math.abs(s)*1.2||t==="left"&&o>=0||t==="right"&&o<=0)return!1;e.preventDefault();try{e.currentTarget.releasePointerCapture?.(e.pointerId)}catch{}return!0}onCollapsedSwipePointerUp(e){this.didSwipe(e,this.inwardSwipeDirection())&&this.openFromCollapsed()}onDockSwipePointerUp(e){this.didSwipe(e,this.inwardSwipeDirection())&&this.openFromDock()}onPanelSwipePointerUp(e){this.attr.open&&this.didSwipe(e,this.outwardSwipeDirection())&&(this._suppressNextContainerClick=!0,this.closePanel())}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.closePanel():this.openFromDock()}}open(){this.attr.collapsed="",this.attr.open=!0}close(){this.closePanel()}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=[],this._handledEmbeddedActionBlocks.clear();let t=document.createElement("div");t.className="introduction-message",t.innerHTML=f().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let n of f().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=n,o.addEventListener("click",s=>this.onSuggestionClick(s,n)),e.appendChild(o)}}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 r of Array.from(t.querySelectorAll(".suggestion-button")))r.remove();this.attr.focusID="";let n=document.createElement("div");n.className="input",n.innerText=e,t.appendChild(n);let o=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),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"}),await this.ai.sendMessage(e);for(let r of this.suggestions){let a=document.createElement("div");a.className="suggestion-button",a.innerText=r,a.addEventListener("click",u=>this.onSuggestionClick(u,r)),this.currentOutputElement.appendChild(a)}}catch(n){k.error("Failed to process input:",n);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+n.message,t.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",r=>this.resetConversation()),t.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e,t){let n=[];for(let o of e)for(let s=0;s<(o.sections?.length||0);s++){let r=o.sections[s],a=`msgelem-${o.id||""}_${s}_${r.type||"unknown"}`;if(a=a.replace(/[^a-zA-Z0-9-_]/g,"_"),r.type=="thinking"){if(!r.text)continue;let u=r.text||"";u.includes(`
|
|
1561
|
+
`)&&(u=u.split(`
|
|
1562
|
+
`)[0]),this.updateInfoElement(a,u,"thinking-icon"),n.push(a)}else if(r.type=="tool_call"){let d=new J(e).toolResult(r.toolCallInstanceID||"");if(r.toolCallHiddenInUI!="always"){if(d?.toolErrorResponse)this.updateInfoElement(a,"**Error:** "+d.toolErrorResponse||"","tool-icon"),n.push(a);else if(!(r.toolCallHiddenInUI=="after-complete"&&d))if(r.toolKbID=="search"){let c=r.toolParameters?.query?`**Search:** ${r.toolParameters.query}`:"**Search**";this.updateInfoElement(a,c,"tool-icon"),n.push(a)}else if(r.toolKbID?.startsWith("ask:")&&r.toolParameters?.query){let c=r.toolKbID.substring(4),h=`**Ask ${this.ai.subAgents.subagents.find(m=>m.id===c)?.name||"agent"}:** ${r.toolParameters.query}`;this.updateInfoElement(a,h,"tool-icon"),n.push(a)}else this.updateInfoElement(a,r.toolKbName||"","tool-icon"),n.push(a)}}else if(r.type!="tool_result"){if(!r.text)continue;this.updateTextElement(a,r.text||"")&&n.push(a)}}for(let o of Array.from(this.currentOutputElement.children))n.includes(o.id)||o.remove()}updateTextElement(e,t){let n=Ye(t||""),o=this._handledEmbeddedActionBlocks.get(e)||new Set;this._handledEmbeddedActionBlocks.set(e,o);for(let a of n.blocks)o.has(a.raw)||(o.add(a.raw),a.action&&this.runEmbeddedAction(a.action));let s=this.currentOutputElement.querySelector(`#${e}`);if(!n.visibleText.trim())return s?.remove(),!1;s||(s=document.createElement("div"),s.id=e,s.className="output",this.currentOutputElement.appendChild(s));let r=St().use(It).use(Mt).use(kt).use(Tt).use(wt,{target:"_blank",rel:["noopener","noreferrer"]}).use(vt).use(xt).processSync(n.visibleText||"");return s.innerHTML=r.toString("utf-8"),!0}runEmbeddedAction(e){if(e.action==="suggestion"){if(!this.ai.flags.allowSuggestionButtons)return;let s=this.normalizeSuggestionActionValue(e.text);if(!s)return;this.suggestions.includes(s)||this.suggestions.push(s);return}if(e.action!=="emoji"||!this.ai.flags.allowEmojiActions)return;let t=this.normalizeEmojiActionValue(e.emoji);if(!t)return;let n=this.clampNumber(e.count,1,24,14),o=this.clampNumber(e.duration,800,2200,1300);this.showEmojiBurst(t,n,o)}clampNumber(e,t,n,o){let s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?Math.max(t,Math.min(n,Math.round(s))):o}normalizeEmojiActionValue(e){return typeof e!="string"?"":Array.from(e.trim()).slice(0,8).join("")}normalizeSuggestionActionValue(e){return typeof e!="string"?"":Array.from(e.trim().replace(/\s+/g," ")).slice(0,160).join("")}showEmojiBurst(e,t,n){let o=this.child("emoji-action-overlay");if(o)for(let s=0;s<t;s++){let r=document.createElement("span");r.className="emoji-action-particle",r.textContent=e;let a=Math.floor(Math.random()*220),u=n+Math.floor(Math.random()*360);r.style.setProperty("--emoji-x",`${12+Math.random()*76}%`),r.style.setProperty("--emoji-bottom",`${54+Math.random()*52}px`),r.style.setProperty("--emoji-size",`${26+Math.random()*20}px`),r.style.setProperty("--emoji-drift",`${Math.round((Math.random()-.5)*180)}px`),r.style.setProperty("--emoji-rise",`${Math.round(-130-Math.random()*170)}px`),r.style.setProperty("--emoji-scale",`${(.9+Math.random()*.7).toFixed(2)}`),r.style.setProperty("--emoji-rotate-start",`${Math.round((Math.random()-.5)*28)}deg`),r.style.setProperty("--emoji-rotate-end",`${Math.round((Math.random()-.5)*120)}deg`),r.style.setProperty("--emoji-duration",`${u}ms`),r.style.animationDelay=`${a}ms`,o.appendChild(r),window.setTimeout(()=>r.remove(),u+a+250)}}updateInfoElement(e,t,n){let o=this.currentOutputElement.querySelector(`#${e}`);o||(o=document.createElement("div"),o.id=e,o.className="info-block",o.innerHTML=`
|
|
835
1563
|
<div class='info-block-icon'></div>
|
|
836
1564
|
<div class='info-block-text'></div>
|
|
837
|
-
`,this.currentOutputElement.appendChild(o));let s=
|
|
1565
|
+
`,this.currentOutputElement.appendChild(o));let s=St().use(It).use(Mt).use(kt).use(Tt).use(wt,{target:"_blank",rel:["noopener","noreferrer"]}).use(vt).use(xt).processSync(t||"");o.querySelector(".info-block-icon").className="info-block-icon "+n,o.querySelector(".info-block-text").innerHTML=s.toString("utf-8")}onSuggestionClick(e,t){this.processInput(t)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}onContentScroll(e){}updateBrandingFor(e){this.updateBrandingText(e)}updateBrandingText(e){let t=this.root?.querySelector("#poweredby");if(!t){console.warn("Powered by element not found for branding update.");return}e?.toLowerCase()==="chatterly"?t.innerHTML="<span>powered by <strong><i class='green-accent'>Chatterly</i></strong></span>":t.innerHTML="<span>powered by <strong>IntelliWeave <i class='green-accent'>AI</i></strong></span>"}};Q.tagName="intelliweave-embed",Q.observedAttributes=["logo","focusID","open","collapsed","background","textColor","fontFamily","displayMode","layout","header","positioningMode","positionX","positionY","offsetX","offsetY","brandName"];function Tt(){return l=>{He(l,"element",(i,e,t)=>{!t||e==null||i.tagName==="table"&&(t.children[e]={type:"element",tagName:"div",properties:{className:["table-scroll-wrapper"]},children:[i]})})}}import Ct,{createContext as ci,useContext as di,useEffect as De,useMemo as ui,useState as Je}from"react";var Et=new g("React"),$s=l=>typeof window>"u"?null:(Q.register(),f().analytics=l.analytics??f().analytics,f().debug=l.debug??f().debug,l.context&&(f().pageSummary=l.context),l.introductionMessage&&(f().introductionMessage=l.introductionMessage),l.introductionSuggestions&&(f().introductionSuggestions=l.introductionSuggestions),l.userID&&(f().userID=l.userID),De(()=>{let i=e=>{for(let t of l.knowledgeBase||[])e.entries.push(t);for(let t of l.sources||[])e.sources.push(t)};return document.addEventListener("webweaver_kb_search",i),()=>document.removeEventListener("webweaver_kb_search",i)},[l.knowledgeBase]),Ct.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})),At=ci(void 0);function qs(l){function i(){Et.debug("Creating new IntelliWeave instance for <IntelliWeaveProvider />");let t=new j;return R.isSupported&&(t.audio=new R(t)),t.load(l.apiKey),t}f().analytics=l.analytics??f().analytics,f().debug=l.debug??f().debug;let e=ui(()=>l.ai||i(),[l.ai,l.apiKey]);return De(()=>{let t=n=>{let o=n;o.detail.isFinal&&e.sendMessage(o.detail.transcript)};return e.audio?.speechRecognition.addEventListener("speech",t),()=>{e.audio?.speechRecognition.removeEventListener("speech",t)}}),Ct.createElement(At.Provider,{value:e},l.children)}function er(){let[l,i]=Je(0),e=di(At)||f().embed?.ai;e||Et.warn("Couldn't find IntelliWeave instance. Make sure you have <IntelliWeaveProvider /> somewhere in your scene graph, or use the <WebWeaverUI /> component.");let[,t]=Je(!!e?.loaded),[,n]=Je(e?.error);return De(()=>{let o=a=>t(a.detail.ai.loaded),s=a=>n(a.detail.ai.error),r=()=>i(a=>a+1);return e?.addEventListener("load",o),e?.addEventListener("error",s),e?.addEventListener("input",r),e?.addEventListener("output",r),e?.addEventListener("toolstart",r),e?.addEventListener("tool",r),()=>{e?.removeEventListener("load",o),e?.removeEventListener("error",s),e?.removeEventListener("input",r),e?.removeEventListener("output",r),e?.removeEventListener("toolstart",r),e?.removeEventListener("tool",r)}},[e]),e}function tr(l,i=[]){De(()=>{let e=t=>t.sources.push({query:l});return document.addEventListener("webweaver_kb_search",e),()=>document.removeEventListener("webweaver_kb_search",e)},i)}export{Ie as AnthropicChat,R as AudioSystem,fe as BufferedWebSocket,H as ChatBase,Me as ChatGPT,we as ElevenLabsTranscriptionNode,at as FixedBufferStream,j as IntelliWeave,J as IntelliWeaveMessageParser,qs as IntelliWeaveProvider,be as IntelliWeaveTranscriptionNode,Se as KnowledgeBase,g as Logging,ke as MCPKnowledgeClient,D as ONNXModel,ge as OpenAITranscriptionNode,V as PCMPlayerNode,Y as PCMReceiverNode,lt as Resampler,G as TokenWindow,Be as TokenWindowGroup,Z as TokenWindowGroupItemSectionType,P as VoiceChunkOutputNode,U as VoiceDetectionNode,Q as WebWeaverEmbed,$s as WebWeaverUI,pe as audioToWav,tt as convertParamsToJSONSchema,nt as createElevenLabsSpeechToTextStream,je as createElevenLabsTextToSpeechStream,Zn as floatTo16BitPCM,Pn as floatTo64BitPCM,et as getDefaultUserID,Xn as int16ToFloat32BitPCM,f as intelliweaveConfig,W as intelliweaveGlobalThis,yi as sseEvents,le as trimWhitespaceInText,er as useIntelliWeave,tr as useIntelliWeaveKnowledge};
|