@intelliweave/embedded 2.0.71 → 2.0.72-beta.1

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.
Binary file
@@ -1206,6 +1206,8 @@ interface WebWeaverGPTConfig {
1206
1206
  textColor?: string;
1207
1207
  /** Display mode: 'closed' (default - starts minimized) or 'open' (always open) */
1208
1208
  displayMode?: 'closed' | 'open';
1209
+ /** Layout preset: 'widget' (default) or 'fullscreen' */
1210
+ layout?: 'widget' | 'fullscreen';
1209
1211
  /** Positioning mode: 'fixed' (default - floats on page) or 'container' (fills parent container) */
1210
1212
  positioningMode?: 'fixed' | 'container';
1211
1213
  /** Horizontal position: 'left' or 'right' (default: 'right') - only used when positioningMode is 'fixed' */
@@ -1430,7 +1432,7 @@ interface KnowledgeBaseItem {
1430
1432
  /** If true, this item will always be returned from all search results. */
1431
1433
  isContext?: boolean;
1432
1434
  /** If true, this item will not be visible to the AI. */
1433
- disabled?: boolean;
1435
+ disabled?: boolean | ((ai: IntelliWeave) => boolean);
1434
1436
  /** List of parameters for an action function. Can either use IW's format, or a JSON Schema object. */
1435
1437
  parameters?: KnowledgeBaseActionParameterSchema;
1436
1438
  /**
@@ -1572,11 +1574,18 @@ declare class WebWeaverEmbed extends BaseComponent {
1572
1574
  private _lastBackground?;
1573
1575
  private _lastTextColor?;
1574
1576
  private _lastDisplayMode?;
1577
+ private _lastLayout?;
1578
+ private _lastPersonaName?;
1579
+ private _lastHeaderLogo?;
1575
1580
  private _lastPositioningMode?;
1576
1581
  private _lastPositionX?;
1577
1582
  private _lastPositionY?;
1578
1583
  private _lastOffsetX?;
1579
1584
  private _lastOffsetY?;
1585
+ /** Apply persona-based color variants as CSS variables */
1586
+ private applyPersonaColorVariants;
1587
+ /** Parse a color string to RGB (supports hex and rgb/rgba) */
1588
+ private parseColorToRGB;
1580
1589
  /** Apply UI styles from config and attributes, prioritizing attributes */
1581
1590
  private applyConfigStylesAndAttributes;
1582
1591
  /** Called on update */
@@ -1632,6 +1641,8 @@ interface IntelliWeaveGlobalConfig {
1632
1641
  backgroundColor?: string;
1633
1642
  /** Display mode: 'closed' (default - starts minimized) or 'open' (always open) */
1634
1643
  displayMode?: 'closed' | 'open';
1644
+ /** Layout preset: 'widget' (default) or 'fullscreen' */
1645
+ layout?: 'widget' | 'fullscreen';
1635
1646
  /** Positioning mode: 'fixed' (default - floats on page) or 'container' (fills parent container) */
1636
1647
  positioningMode?: 'fixed' | 'container';
1637
1648
  /** Horizontal position: 'left' or 'right' (default: 'right') - only used when positioningMode is 'fixed' */
package/dist/node/node.js CHANGED
@@ -6,12 +6,12 @@ import{v4 as J}from"uuid";function G(u){let t=(u||"").split(`
6
6
  `);for(let c of r){i=c.indexOf(": ");let l=c.slice(0,i),m=c.slice(i+2);i==-1&&(l=c,m=""),l&&(a[l]!==void 0?a[l]+=`
7
7
  `+m:a[l]=m)}yield a}},s=new TextDecoder,n=u.getReader();for(;;){let{done:i,value:o}=await n.read();if(i)break;t+=s.decode(o,{stream:!0}),yield*e()}t+=s.decode()+`
8
8
 
9
- `,yield*e()}function z(){if(p().userID)return p().userID||"";if(typeof localStorage<"u"){let u=localStorage.getItem("intelliweave.uid")||"";return u||(u=J(),localStorage.setItem("intelliweave.uid",u),u)}else return J()}function V(u){let t=u;if(t?.type=="object"&&t.properties)return u;let e={type:"object",properties:{},required:[]};if(u&&Array.isArray(u)){let s=u;for(let n of s)e.properties[n.name]={type:n.type||"string",description:n.description||""}}return e}var B=class B{constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return B.debug?!0:typeof window<"u"&&p().debug}log(...t){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...t)}debug(...t){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...t)}info(...t){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...t)}warn(...t){console.warn(`[IntelliWeave > ${this.module}]`,...t)}error(...t){console.error(`[IntelliWeave > ${this.module}]`,...t)}timer(t,...e){let s=Date.now();return this.debug(`[${t} 0ms] Started`,...e),(...n)=>this.debug(`[${t} ${Math.floor(Date.now()-s)}ms]`,...n)}};B.debug=!1;var g=B;var k=new g("ONNXModel"),H=class u{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,k.debug(`Model input parameters: ${t.inputNames.join(", ")}`),k.debug(`Model output parameters: ${t.outputNames.join(", ")}`)}static isSupported(){return!!u.lib}static async load(t){if(!u.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(k.debug("Loading ONNX runtime"),this.onnx=await u.lib()),k.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new u(e)}makeTensor(t,e,s=0){let n=1;for(let o of e)n*=o;let i;if(t=="float32")i=new u.onnx.Tensor(new Float32Array(n),e);else if(t=="int8")i=new u.onnx.Tensor(new Int8Array(n),e);else if(t=="int16")i=new u.onnx.Tensor(new Int16Array(n),e);else if(t=="int32")i=new u.onnx.Tensor(new Int32Array(n),e);else if(t=="int64")i=new u.onnx.Tensor(new BigInt64Array(n),e);else if(t=="uint8")i=new u.onnx.Tensor(new Uint8Array(n),e);else if(t=="uint16")i=new u.onnx.Tensor(new Uint16Array(n),e);else if(t=="uint32")i=new u.onnx.Tensor(new Uint32Array(n),e);else if(t=="uint64")i=new u.onnx.Tensor(new BigUint64Array(n),e);else throw new Error(`Invalid type: ${t}`);return s!==0&&(t=="int64"||t=="uint64")?i.data.fill(BigInt(s)):s!==0&&i.data.fill(s),i}registerConstant(t,e){if(!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);return this.constantTensors[t]=e,e}makeConstant(t,e,s,n=0){return this.registerConstant(t,this.makeTensor(e,s,n))}registerState(t,e,s){if(e||(e=t),!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[t]={outputName:e,tensor:s},s}makeState(t,e,s,n,i=0){return this.registerState(t,e,this.makeTensor(s,n,i))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return k.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)t[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)t[e]=this.constantTensors[e];try{let e=await this.session.run(t);for(let s in this.stateTensors){let n=e[this.stateTensors[s].outputName];this.stateTensors[s].tensor=n}return e}finally{this._runActive=!1}}resetState(){k.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};function Se(u,t){let e=t.reduce((r,c)=>r+c.byteLength,0),s=new DataView(new ArrayBuffer(44));s.setUint8(0,82),s.setUint8(1,73),s.setUint8(2,70),s.setUint8(3,70),s.setUint32(4,44+e,!0),s.setUint8(8,87),s.setUint8(9,65),s.setUint8(10,86),s.setUint8(11,69);let n=1,i=32,o=n*i/8,a=u*o;return s.setUint8(12,102),s.setUint8(13,109),s.setUint8(14,116),s.setUint8(15,32),s.setUint32(16,16,!0),s.setUint16(20,3,!0),s.setUint16(22,n,!0),s.setUint32(24,u,!0),s.setUint32(28,a,!0),s.setUint16(32,o,!0),s.setUint16(34,i,!0),s.setUint8(36,100),s.setUint8(37,97),s.setUint8(38,116),s.setUint8(39,97),s.setUint32(40,e,!0),new File([s,...t],"audio.wav",{type:"audio/wav"})}var X=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var Y=class{constructor(t,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!t)throw new Error(`Invalid array class: ${t}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=t,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((t,e)=>t+e.length,0)}feed(t){this.partialBuffers.push(t)}get canDrain(){return this.partialBuffers.reduce((e,s)=>e+s.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let t=this.ArrayClass,e=new t(this.outputBufferSize),s=0;for(;s!=e.length;){if(s>e.length)throw new Error(`Buffer overflow: ${s} > ${e.length}`);let n=e.length-s,i=this.partialBuffers[0],o=i.length-this.partialBufferOffset;o<n?(e.set(i.subarray(this.partialBufferOffset),s),s+=o,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(i.subarray(this.partialBufferOffset,this.partialBufferOffset+n),s),s+=n,this.partialBufferOffset+=n)}return e}pad(){let t=this.queuedSize%this.outputBufferSize;if(t==0)return;let e=this.ArrayClass,s=new e(t);this.feed(s)}};var Z=class{constructor(t,e,s,n){if(!t||!e||!s)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=t,this.toSampleRate=e,this.channels=s||0,this.inputBufferSize=n,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=t=>t,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(t){try{return this.outputBuffer.subarray(0,t)}catch{try{return this.outputBuffer.length=t,this.outputBuffer}catch{return this.outputBuffer.slice(0,t)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=t=>{let e=t.length,s=this.channels,n,i,o,a,r,c,l,m,d;if(e%s!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(n=this.outputBufferSize,i=this.ratioWeight,o=this.lastWeight,a=0,r=0,c=0,l=0,m=this.outputBuffer;o<1;o+=i)for(r=o%1,a=1-r,this.lastWeight=o%1,d=0;d<this.channels;++d)m[l++]=this.lastOutput[d]*a+t[d]*r;for(o-=1,e-=s,c=Math.floor(o)*s;l<n&&c<e;){for(r=o%1,a=1-r,d=0;d<this.channels;++d)m[l++]=t[c+(d>0?d:0)]*a+t[c+(s+d)]*r;o+=i,c=Math.floor(o)*s}for(d=0;d<s;++d)this.lastOutput[d]=t[c++];return this.bufferSlice(l)}}multiTap(){this.resampler=t=>{let e=t.length,s,n,i=this.channels,o,a,r,c,l,m,d,v,E;if(e%i!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,n=[],o=this.ratioWeight,a=0,c=0,l=0,m=!this.tailExists,this.tailExists=!1,d=this.outputBuffer,v=0,E=0,r=0;r<i;++r)n[r]=0;do{if(m)for(a=o,r=0;r<i;++r)n[r]=0;else{for(a=this.lastWeight,r=0;r<i;++r)n[r]=this.lastOutput[r];m=!0}for(;a>0&&c<e;)if(l=1+c-E,a>=l){for(r=0;r<i;++r)n[r]+=t[c++]*l;E=c,a-=l}else{for(r=0;r<i;++r)n[r]+=t[c+(r>0?r:0)]*a;E+=a,a=0;break}if(a===0)for(r=0;r<i;++r)d[v++]=n[r]/o;else{for(this.lastWeight=a,r=0;r<i;++r)this.lastOutput[r]=n[r];this.tailExists=!0;break}}while(c<e&&v<s);return this.bufferSlice(v)}}resample(t){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(t)}};function Te(u){let t=u.length,e=new Int16Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,u[t]));e[t]=s<0?s*32768:s*32767}return e}function _e(u){let t=u.length,e=new BigInt64Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,u[t]));e[t]=BigInt(Math.floor(s<0?s*32768:s*32767))*0x100000000000n}return e}function Ee(u){let t=u.length,e=new Float32Array(t);for(;t--;){let s=u[t];e[t]=s>=32768?-(65536-s)/32768:s/32767}return e}import{countTokens as oe}from"gpt-tokenizer";import{countTokens as M}from"gpt-tokenizer";import{v4 as ie}from"uuid";var A=class{constructor(){this.size=4096;this.groups=[]}createGroup(t){let e=new U;return e.id=t,this.groups.push(e),e}group(t){return this.groups.find(e=>e.id===t)}countTokens(){return this.groups.reduce((t,e)=>t+e.tokenCount,0)}removeOverflow(){let t=this.countTokens(),e=this.groups.reduce((s,n)=>s+n.weight,0);for(;t>this.size;){let s=this.groups.slice().sort((i,o)=>{let a=Math.floor(i.weight/e*this.size),r=Math.floor(o.weight/e*this.size),c=i.tokenCount-a;return o.tokenCount-r-c}),n=this.removeOneItem(s);if(!n)throw new Error("Too many items in the token window that cannot be removed.");t-=n.tokenCount}}removeOneItem(t){for(let e of t){let s=e.items.findIndex(i=>!i.cannotRemove);if(s===-1)continue;let n=e.items[s];return e.items.splice(s,1),e.tokenCount-=n.tokenCount,n}return null}},U=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
9
+ `,yield*e()}function z(){if(p().userID)return p().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let u=localStorage.getItem("intelliweave.uid")||"";return u||(u=J(),localStorage.setItem("intelliweave.uid",u),u)}else return J()}function V(u){let t=u;if(t?.type=="object"&&t.properties)return u;let e={type:"object",properties:{},required:[]};if(u&&Array.isArray(u)){let s=u;for(let n of s)e.properties[n.name]={type:n.type||"string",description:n.description||""}}return e}var B=class B{constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return B.debug?!0:typeof window<"u"&&p().debug}log(...t){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...t)}debug(...t){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...t)}info(...t){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...t)}warn(...t){console.warn(`[IntelliWeave > ${this.module}]`,...t)}error(...t){console.error(`[IntelliWeave > ${this.module}]`,...t)}timer(t,...e){let s=Date.now();return this.debug(`[${t} 0ms] Started`,...e),(...n)=>this.debug(`[${t} ${Math.floor(Date.now()-s)}ms]`,...n)}};B.debug=!1;var h=B;var k=new h("ONNXModel"),H=class u{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,k.debug(`Model input parameters: ${t.inputNames.join(", ")}`),k.debug(`Model output parameters: ${t.outputNames.join(", ")}`)}static isSupported(){return!!u.lib}static async load(t){if(!u.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(k.debug("Loading ONNX runtime"),this.onnx=await u.lib()),k.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new u(e)}makeTensor(t,e,s=0){let n=1;for(let o of e)n*=o;let i;if(t=="float32")i=new u.onnx.Tensor(new Float32Array(n),e);else if(t=="int8")i=new u.onnx.Tensor(new Int8Array(n),e);else if(t=="int16")i=new u.onnx.Tensor(new Int16Array(n),e);else if(t=="int32")i=new u.onnx.Tensor(new Int32Array(n),e);else if(t=="int64")i=new u.onnx.Tensor(new BigInt64Array(n),e);else if(t=="uint8")i=new u.onnx.Tensor(new Uint8Array(n),e);else if(t=="uint16")i=new u.onnx.Tensor(new Uint16Array(n),e);else if(t=="uint32")i=new u.onnx.Tensor(new Uint32Array(n),e);else if(t=="uint64")i=new u.onnx.Tensor(new BigUint64Array(n),e);else throw new Error(`Invalid type: ${t}`);return s!==0&&(t=="int64"||t=="uint64")?i.data.fill(BigInt(s)):s!==0&&i.data.fill(s),i}registerConstant(t,e){if(!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);return this.constantTensors[t]=e,e}makeConstant(t,e,s,n=0){return this.registerConstant(t,this.makeTensor(e,s,n))}registerState(t,e,s){if(e||(e=t),!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[t]={outputName:e,tensor:s},s}makeState(t,e,s,n,i=0){return this.registerState(t,e,this.makeTensor(s,n,i))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return k.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)t[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)t[e]=this.constantTensors[e];try{let e=await this.session.run(t);for(let s in this.stateTensors){let n=e[this.stateTensors[s].outputName];this.stateTensors[s].tensor=n}return e}finally{this._runActive=!1}}resetState(){k.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};function Se(u,t){let e=t.reduce((r,c)=>r+c.byteLength,0),s=new DataView(new ArrayBuffer(44));s.setUint8(0,82),s.setUint8(1,73),s.setUint8(2,70),s.setUint8(3,70),s.setUint32(4,44+e,!0),s.setUint8(8,87),s.setUint8(9,65),s.setUint8(10,86),s.setUint8(11,69);let n=1,i=32,o=n*i/8,a=u*o;return s.setUint8(12,102),s.setUint8(13,109),s.setUint8(14,116),s.setUint8(15,32),s.setUint32(16,16,!0),s.setUint16(20,3,!0),s.setUint16(22,n,!0),s.setUint32(24,u,!0),s.setUint32(28,a,!0),s.setUint16(32,o,!0),s.setUint16(34,i,!0),s.setUint8(36,100),s.setUint8(37,97),s.setUint8(38,116),s.setUint8(39,97),s.setUint32(40,e,!0),new File([s,...t],"audio.wav",{type:"audio/wav"})}var X=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var Y=class{constructor(t,e){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!t)throw new Error(`Invalid array class: ${t}`);if(!e||e<=0)throw new Error(`Invalid output buffer size: ${e}`);this.ArrayClass=t,this.outputBufferSize=e}get queuedSize(){return this.partialBuffers.reduce((t,e)=>t+e.length,0)}feed(t){this.partialBuffers.push(t)}get canDrain(){return this.partialBuffers.reduce((e,s)=>e+s.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let t=this.ArrayClass,e=new t(this.outputBufferSize),s=0;for(;s!=e.length;){if(s>e.length)throw new Error(`Buffer overflow: ${s} > ${e.length}`);let n=e.length-s,i=this.partialBuffers[0],o=i.length-this.partialBufferOffset;o<n?(e.set(i.subarray(this.partialBufferOffset),s),s+=o,this.partialBuffers.shift(),this.partialBufferOffset=0):(e.set(i.subarray(this.partialBufferOffset,this.partialBufferOffset+n),s),s+=n,this.partialBufferOffset+=n)}return e}pad(){let t=this.queuedSize%this.outputBufferSize;if(t==0)return;let e=this.ArrayClass,s=new e(t);this.feed(s)}};var Z=class{constructor(t,e,s,n){if(!t||!e||!s)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=t,this.toSampleRate=e,this.channels=s||0,this.inputBufferSize=n,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=t=>t,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(t){try{return this.outputBuffer.subarray(0,t)}catch{try{return this.outputBuffer.length=t,this.outputBuffer}catch{return this.outputBuffer.slice(0,t)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=t=>{let e=t.length,s=this.channels,n,i,o,a,r,c,l,m,d;if(e%s!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(n=this.outputBufferSize,i=this.ratioWeight,o=this.lastWeight,a=0,r=0,c=0,l=0,m=this.outputBuffer;o<1;o+=i)for(r=o%1,a=1-r,this.lastWeight=o%1,d=0;d<this.channels;++d)m[l++]=this.lastOutput[d]*a+t[d]*r;for(o-=1,e-=s,c=Math.floor(o)*s;l<n&&c<e;){for(r=o%1,a=1-r,d=0;d<this.channels;++d)m[l++]=t[c+(d>0?d:0)]*a+t[c+(s+d)]*r;o+=i,c=Math.floor(o)*s}for(d=0;d<s;++d)this.lastOutput[d]=t[c++];return this.bufferSlice(l)}}multiTap(){this.resampler=t=>{let e=t.length,s,n,i=this.channels,o,a,r,c,l,m,d,v,E;if(e%i!==0)throw new Error("Buffer was of incorrect sample length.");if(e<=0)return[];for(s=this.outputBufferSize,n=[],o=this.ratioWeight,a=0,c=0,l=0,m=!this.tailExists,this.tailExists=!1,d=this.outputBuffer,v=0,E=0,r=0;r<i;++r)n[r]=0;do{if(m)for(a=o,r=0;r<i;++r)n[r]=0;else{for(a=this.lastWeight,r=0;r<i;++r)n[r]=this.lastOutput[r];m=!0}for(;a>0&&c<e;)if(l=1+c-E,a>=l){for(r=0;r<i;++r)n[r]+=t[c++]*l;E=c,a-=l}else{for(r=0;r<i;++r)n[r]+=t[c+(r>0?r:0)]*a;E+=a,a=0;break}if(a===0)for(r=0;r<i;++r)d[v++]=n[r]/o;else{for(this.lastWeight=a,r=0;r<i;++r)this.lastOutput[r]=n[r];this.tailExists=!0;break}}while(c<e&&v<s);return this.bufferSlice(v)}}resample(t){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(t)}};function Te(u){let t=u.length,e=new Int16Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,u[t]));e[t]=s<0?s*32768:s*32767}return e}function _e(u){let t=u.length,e=new BigInt64Array(t);for(;t--;){let s=Math.max(-1,Math.min(1,u[t]));e[t]=BigInt(Math.floor(s<0?s*32768:s*32767))*0x100000000000n}return e}function Ee(u){let t=u.length,e=new Float32Array(t);for(;t--;){let s=u[t];e[t]=s>=32768?-(65536-s)/32768:s/32767}return e}import{countTokens as oe}from"gpt-tokenizer";import{countTokens as M}from"gpt-tokenizer";import{v4 as ie}from"uuid";var A=class{constructor(){this.size=4096;this.groups=[]}createGroup(t){let e=new U;return e.id=t,this.groups.push(e),e}group(t){return this.groups.find(e=>e.id===t)}countTokens(){return this.groups.reduce((t,e)=>t+e.tokenCount,0)}removeOverflow(){let t=this.countTokens(),e=this.groups.reduce((s,n)=>s+n.weight,0);for(;t>this.size;){let s=this.groups.slice().sort((i,o)=>{let a=Math.floor(i.weight/e*this.size),r=Math.floor(o.weight/e*this.size),c=i.tokenCount-a;return o.tokenCount-r-c}),n=this.removeOneItem(s);if(!n)throw new Error("Too many items in the token window that cannot be removed.");t-=n.tokenCount}}removeOneItem(t){for(let e of t){let s=e.items.findIndex(i=>!i.cannotRemove);if(s===-1)continue;let n=e.items[s];return e.items.splice(s,1),e.tokenCount-=n.tokenCount,n}return null}},U=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
10
10
  `;this.itemPadding=0;this.sortFunction=(t,e)=>t.sortOrder!==e.sortOrder?t.sortOrder-e.sortOrder:t.dateAdded!==e.dateAdded?t.dateAdded-e.dateAdded:t.content.localeCompare(e.content)}setItemPadding(t){return this.itemPadding=t,this.recalculateTokens(),this}sortBy(t){return this.sortFunction=t,this.items.sort(this.sortFunction),this}setSeparator(t){return this.separator==t?this:(this.separator=t,this.recalculateTokens(),this)}setWeight(t){return this.weight=t,this}recalculateTokens(){this.tokenCount=this.items.reduce((t,e)=>(e.tokenCount=M(e.content)+M(this.separator)+this.itemPadding,t+e.tokenCount),0)}add(t){typeof t=="string"&&(t={content:t});let e=t;e.id===void 0&&(e.id=ie());let s=this.items.find(n=>n.id===e.id);return s?(this.tokenCount-=s.tokenCount,Object.assign(s,e),e=s):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.tokenCount=e.disabled?0:M(t.content)+M(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}getAllAsString(){return this.getAll().map(t=>t.content).join(this.separator)}getAll(){return this.items.filter(t=>!t.disabled)}empty(){this.items=[],this.tokenCount=0}};var I=class{constructor(t){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let t=new A;return t.createGroup("context").setSeparator(`
11
11
 
12
- `),t.createGroup("actions").setItemPadding(25),t.createGroup("messages").setItemPadding(10),t})();this.config=t,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(t){throw new Error("Not implemented")}addUserMessage(t){throw new Error("Not implemented")}addAssistantMessage(t){throw new Error("Not implemented")}onBeforeIncomingMessage(t){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(t){return this.toolGroup.add({id:t.name,customData:t,cannotRemove:t.isContext,sortOrder:101,disabled:t.disabled,content:JSON.stringify(t)})}};import{v4 as T}from"uuid";var w=new g("ChatGPT"),D=class extends I{async sendMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e}),await this.processMessages();let n=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return n?.role=="assistant"&&n.content||""}addAssistantMessage(t){let e={role:"assistant",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e})}addUserMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(t=>t.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),w.debugEnabled&&w.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(s=>s.customData),messages:this.messageGroup.items.map(s=>s.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let s of e.tool_calls)await this.processToolCall(s);await this.processMessages()}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendRequest(t){let e={};return e["Content-Type"]="application/json",this.config.apiKey&&(e.Authorization=`Bearer ${this.config.apiKey}`),await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:e,body:JSON.stringify(t)})}async sendToAPI(t){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let a=this.messageGroup.items.length-1;a>=0;a--){let r=this.messageGroup.items[a].customData;if(r.role=="assistant"&&r.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(r.role=="user")break}w.debugEnabled&&w.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(a=>a.customData),messages:this.messageGroup.items.map(a=>a.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let s={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(a=>a.customData)]};for(let a of this.toolGroup.getAll()){let r=a.customData;r.description&&r.description.length>1024&&w.warn(`Tool description for "${r.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:r.name,description:(r.description||"").substring(0,1024),parameters:r.params}};s.tools.push(c)}if(s.user||delete s.user,s.tools.length||delete s.tools,t)return s;let n=await this.sendRequest(s);if(!n.ok){let a=`${n.status} ${n.statusText}`;try{let c=await n.json();a=c.errorText||c.error?.message||c.error||a}catch{}let r=new Error(a);throw r.code=n.status,r}let i=null,o=null;if(this.config.stream){for await(let r of q(n.body)){if(r.data=="[DONE]")break;if(!r.data)continue;let c=JSON.parse(r.data);if(o){for(let l in c.choices[0].delta)if(typeof c.choices[0].delta[l]=="string"){if(l=="role"&&o[l]==c.choices[0].delta[l])continue;o[l]=(o[l]||"")+c.choices[0].delta[l]}for(let l of c.choices[0].delta.tool_calls||[]){if(o.tool_calls||(o.tool_calls=[]),!o.tool_calls[l.index]){o.tool_calls[l.index]=l;continue}let m=o.tool_calls[l.index];m.function=m.function||{},m.function.name=(m.function.name||"")+(l.function?.name||""),m.function.arguments=(m.function.arguments||"")+(l.function?.arguments||"")}}else o={chunkID:c.id,...c.choices[0].delta};o?.content&&!o.content.startsWith("{")&&this.config.onAIMessage?.(o.content,!0)}let a=oe(JSON.stringify(s)+JSON.stringify(o)||"");this.stats.tokensUsed+=a,w.debug(`Estimated ${a} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else i=await n.json(),this.stats.tokensUsed+=i?.usage?.total_tokens||0,w.debug(`Used ${i?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),o=i?.choices?.[0]?.message;if(o||(w.warn("No response block in API response."),o={role:"assistant",content:""}),o.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(o),this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(o),customData:o}),o.content&&this.config.onAIMessage?.(o.content,!1)}async processToolCall(t){try{let s=this.toolGroup.items.find(a=>a.id==t.function.name)?.customData;if(!s)throw new Error(`Tool "${t.function.name}" not found.`);let n=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,n);let i=await s.callback(n);typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success");let o={role:"tool",content:i,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(o),customData:o})}catch(e){w.warn(`Unable to process tool call for "${t?.function?.name}"`,e);let s={role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(s),customData:s})}}};import re from"@anthropic-ai/sdk";import{v4 as P}from"uuid";var O=new g("AnthropicChat"),N=class extends I{addUserMessage(t){let e={role:"user",content:t||""};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(e),customData:e})}addAssistantMessage(t){let e={role:"assistant",content:t||""};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(e),customData:e})}async sendMessage(t){this.addUserMessage(t);let e=new re({apiKey:this.config.apiKey,baseURL:this.config.endpoint,dangerouslyAllowBrowser:!0}),s=!0,n="",i="";for(;s;){s=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),O.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.customData),tools:this.toolGroup.getAll().map(d=>d.customData),context:this.contextGroup.getAll().map(d=>d.content)});let o=this.toolGroup.getAll().map(d=>({name:d.customData?.name||"",description:d.customData?.description||"",input_schema:{type:"object",required:d.customData?.params.required||[],properties:d.customData?.params.properties||{}}})),a;if(this.config.stream){let d=e.messages.stream({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(v=>v.customData),tools:o,stream:!0});d.on("text",v=>{i+=v,this.config.onAIMessage?.(i,!0)}),a=await d.finalMessage()}else a=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(d=>d.customData),tools:o});O.debug("Message received",a);let r=!0;Array.isArray(a.content)&&a.content.length==0&&(r=!1);let c={role:a.role,content:a.content};r&&this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(c),customData:c});let l=[];for(let d of a.content)d.type=="thinking"?O.debug(`AI is thinking: ${d.thinking}`):d.type=="text"?n+=d.text||`
12
+ `),t.createGroup("actions").setItemPadding(25),t.createGroup("messages").setItemPadding(10),t})();this.config=t,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(t){throw new Error("Not implemented")}addUserMessage(t){throw new Error("Not implemented")}addAssistantMessage(t){throw new Error("Not implemented")}onBeforeIncomingMessage(t){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(t){return this.toolGroup.add({id:t.name,customData:t,cannotRemove:t.isContext,sortOrder:101,disabled:t.disabled,content:JSON.stringify(t)})}};import{v4 as T}from"uuid";var w=new h("ChatGPT"),D=class extends I{async sendMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e}),await this.processMessages();let n=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return n?.role=="assistant"&&n.content||""}addAssistantMessage(t){let e={role:"assistant",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e})}addUserMessage(t){let e={role:"user",content:t};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(t=>t.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),w.debugEnabled&&w.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(s=>s.customData),messages:this.messageGroup.items.map(s=>s.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let s of e.tool_calls)await this.processToolCall(s);await this.processMessages()}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendRequest(t){let e={};return e["Content-Type"]="application/json",this.config.apiKey&&(e.Authorization=`Bearer ${this.config.apiKey}`),await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:e,body:JSON.stringify(t)})}async sendToAPI(t){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let a=this.messageGroup.items.length-1;a>=0;a--){let r=this.messageGroup.items[a].customData;if(r.role=="assistant"&&r.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(r.role=="user")break}w.debugEnabled&&w.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(a=>a.customData),messages:this.messageGroup.items.map(a=>a.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let s={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(a=>a.customData)]};for(let a of this.toolGroup.getAll()){let r=a.customData;r.description&&r.description.length>1024&&w.warn(`Tool description for "${r.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:r.name,description:(r.description||"").substring(0,1024),parameters:r.params}};s.tools.push(c)}if(s.user||delete s.user,s.tools.length||delete s.tools,t)return s;let n=await this.sendRequest(s);if(!n.ok){let a=`${n.status} ${n.statusText}`;try{let c=await n.json();a=c.errorText||c.error?.message||c.error||a}catch{}let r=new Error(a);throw r.code=n.status,r}let i=null,o=null;if(this.config.stream){for await(let r of q(n.body)){if(r.data=="[DONE]")break;if(!r.data)continue;let c=JSON.parse(r.data);if(o){for(let l in c.choices[0].delta)if(typeof c.choices[0].delta[l]=="string"){if(l=="role"&&o[l]==c.choices[0].delta[l])continue;o[l]=(o[l]||"")+c.choices[0].delta[l]}for(let l of c.choices[0].delta.tool_calls||[]){if(o.tool_calls||(o.tool_calls=[]),!o.tool_calls[l.index]){o.tool_calls[l.index]=l;continue}let m=o.tool_calls[l.index];m.function=m.function||{},m.function.name=(m.function.name||"")+(l.function?.name||""),m.function.arguments=(m.function.arguments||"")+(l.function?.arguments||"")}}else o={chunkID:c.id,...c.choices[0].delta};o?.content&&!o.content.startsWith("{")&&this.config.onAIMessage?.(o.content,!0)}let a=oe(JSON.stringify(s)+JSON.stringify(o)||"");this.stats.tokensUsed+=a,w.debug(`Estimated ${a} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else i=await n.json(),this.stats.tokensUsed+=i?.usage?.total_tokens||0,w.debug(`Used ${i?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),o=i?.choices?.[0]?.message;if(o||(w.warn("No response block in API response."),o={role:"assistant",content:""}),o.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(o),this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(o),customData:o}),o.content&&this.config.onAIMessage?.(o.content,!1)}async processToolCall(t){try{let s=this.toolGroup.items.find(a=>a.id==t.function.name)?.customData;if(!s)throw new Error(`Tool "${t.function.name}" not found.`);let n=JSON.parse(t.function.arguments);this.config.onAIToolStart?.(t.function.name,n);let i=await s.callback(n);typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success");let o={role:"tool",content:i,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(o),customData:o})}catch(e){w.warn(`Unable to process tool call for "${t?.function?.name}"`,e);let s={role:"tool",content:`Error: ${e.message}`,tool_call_id:t.id};this.messageGroup.add({id:"msg-"+T(),content:JSON.stringify(s),customData:s})}}};import re from"@anthropic-ai/sdk";import{v4 as P}from"uuid";var O=new h("AnthropicChat"),N=class extends I{addUserMessage(t){let e={role:"user",content:t||""};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(e),customData:e})}addAssistantMessage(t){let e={role:"assistant",content:t||""};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(e),customData:e})}async sendMessage(t){this.addUserMessage(t);let e=new re({apiKey:this.config.apiKey,baseURL:this.config.endpoint,dangerouslyAllowBrowser:!0}),s=!0,n="",i="";for(;s;){s=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),O.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.customData),tools:this.toolGroup.getAll().map(d=>d.customData),context:this.contextGroup.getAll().map(d=>d.content)});let o=this.toolGroup.getAll().map(d=>({name:d.customData?.name||"",description:d.customData?.description||"",input_schema:{type:"object",required:d.customData?.params.required||[],properties:d.customData?.params.properties||{}}})),a;if(this.config.stream){let d=e.messages.stream({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(v=>v.customData),tools:o,stream:!0});d.on("text",v=>{i+=v,this.config.onAIMessage?.(i,!0)}),a=await d.finalMessage()}else a=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(d=>d.customData),tools:o});O.debug("Message received",a);let r=!0;Array.isArray(a.content)&&a.content.length==0&&(r=!1);let c={role:a.role,content:a.content};r&&this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(c),customData:c});let l=[];for(let d of a.content)d.type=="thinking"?O.debug(`AI is thinking: ${d.thinking}`):d.type=="text"?n+=d.text||`
13
13
 
14
- `:d.type=="tool_use"&&l.push(this.performToolCall(d));let m=await Promise.all(l);if(m.length>0){let d={role:"user",content:m};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(d),customData:d}),s=!0}this.config.onAIMessage?.(n,!0),this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return n=n.trim(),this.config.onAIMessage?.(n,!1),n}async performToolCall(t){try{let e=this.toolGroup.getAll().find(n=>n.customData?.name==t.name);if(!e)throw new Error(`Tool ${t.name} not found`);this.config.onAIToolStart?.(t.name,t.input);let s=await e.customData.callback(t.input);return typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),{type:"tool_result",tool_use_id:t.id,content:String(s||"")}}catch(e){return O.error(`Error performing tool call ${t.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:t.id,content:`Error performing tool call ${t.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import ge from"minisearch";var Q=u=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(t,e)=>{let s=await e.knowledgeBase.search(t.query),n=e;n._lastKBsearch=t.query,n._nextRequestUseKBitems=s,e.submitAnalyticsEvent({type:"kb-search",query:t.query,results:s});let i=s.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=s.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!t.url||typeof t.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(t.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:t.url}),`Opened URL: ${t.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!t.path||typeof t.path!="string")throw new Error("Path parameter is required and must be a string.");let s=new URL(t.path,window.location.origin).pathname;return window.location.href=s,e.submitAnalyticsEvent({type:"change-route",path:s}),`Changed route to: ${s}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!t.email_address||typeof t.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!t.subject||typeof t.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!t.body||typeof t.body!="string")throw new Error("Body parameter is required and must be a string.");let s=encodeURIComponent(t.email_address),n=encodeURIComponent(t.subject),i=encodeURIComponent(t.body),o=`mailto:${s}?subject=${n}&body=${i}`;try{window.location.href=o}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:t.email_address,subject:t.subject,body_length:t.body.length}),`Email opened in default mail client. Recipient: ${t.email_address}, Subject: ${t.subject}`}}];import{Client as ee}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as le}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as ce}from"@modelcontextprotocol/sdk/client/sse.js";var y={name:"@intelliweave/embedded",version:"2.0.71",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as ue,ToolListChangedNotificationSchema as de}from"@modelcontextprotocol/sdk/types.js";var h=new g("MCPKnowledgeClient"),W=class{constructor(t){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=t}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){h.debug("Connecting to MCP client");let t=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new ee({name:y.name,version:y.version}),s=new le(new URL(this.config.baseURL));return await e.connect(s),h.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let s=new ee({name:y.name,version:y.version}),n=new ce(new URL(this.config.baseURL));return await s.connect(n),h.debug("Connected with SSE mode"),s});return await this.disconnect(),this.client=t,t.onerror=e=>{h.error(`MCP client error: ${e.message}`)},t.onclose=()=>{h.debug("MCP client connection closed"),this.client=void 0},t.setNotificationHandler(ue,e=>{e.params.level=="critical"?h.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?h.error(`[Server] ${e.params.data}`):e.params.level=="error"?h.error(`[Server] ${e.params.data}`):e.params.level=="warning"?h.warn(`[Server] ${e.params.data}`):e.params.level=="info"?h.info(`[Server] ${e.params.data}`):e.params.level=="debug"?h.debug(`[Server] ${e.params.data}`):h.log(`[Server] ${e.params.data}`)}),t.setNotificationHandler(de,e=>{h.debug("Tool list changed",e),this.fetchTools()}),h.debug("Fetching tools from MCP server..."),await this.fetchTools(),t}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let t=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let i of n.tools||[])t.push(i);if(!n?.tools?.length||!e)break}let s=[];for(let n of t){let i=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:o=>this.performToolCall(n.name,o),disabled:i})}h.debug(`Fetched ${t.length} tools from MCP server.`),this.tools=t,this.iwActions=s}async search(t){if(t==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),s=await this.performSearchCall(t);return e=e.concat(s),this.lastSearchQuery=t,this.lastSearchResults=e,h.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(t){let e=[];if(!this.config.searchToolName)return e;let s=this.tools.find(i=>i.name==this.config.searchToolName);if(!s)return h.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(s.inputSchema.required?.length==1){let i=s.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let i=Object.keys(s.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let i=0;i<n.length;i++){let o=n[i];e.push({id:this.config.id+":"+this.config.searchToolName+":"+i,name:`Search result ${i+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(t,e){await this.connect(),h.debug(`Performing tool call for ${t} with params:`,e),this.stats.toolsCalled+=1;let s=await this.client.callTool({name:t,arguments:e});if(s.isError){let n=s.content?.[0]?.text||"Unknown error";throw h.error(`Error calling tool ${t}: ${n}`),new Error(`Error calling tool ${t}: ${n}`)}if(Array.isArray(s.content)&&s.content.length==1&&s.content[0].type=="text")try{return JSON.parse(s.content[0].text)}catch{}return s.content||[]}};import{v4 as me}from"uuid";var he=new g("Statistics"),_=[];async function b(u,t){let e={...t,event_id:me(),event_date:new Date().toISOString(),sdk_version:y.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(_.push(e),!u||(await new Promise(n=>setTimeout(n,5e3)),_.length===0))return;let s=_.slice();_.length=0;try{let n=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){he.warn("Failed to submit analytics event:",n),_.push(...s);return}}var S=new g("KnowledgeBase"),j=1,$=class u{constructor(t){this._sources=[{id:"core.internal",query:async()=>Q(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${j++}`),this._sources.push({id:s,query:e}),s}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return p().knowledgeBaseSources&&(t=t.concat(p().knowledgeBaseSources)),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){let e=Date.now();S.debug(`Searching knowledge base for: ${t}`);let s=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});s.query=t,s.entries=[],s.sources=[],typeof document<"u"&&document.dispatchEvent(s),this._windowSources=s.sources;let i=(await Promise.all(this.sources.map(async c=>{try{let l=Date.now(),m=await c.query(t);return S.debug(`Source '${c.id}' took ${Date.now()-l}ms`),m||[]}catch(l){return S.warn(`Knowledge source '${c.id}' failed:`,l),[]}}))).flat();i=i.concat(s.entries),i=i.concat(this.manualEntries),p().knowledgeBase&&(i=i.concat(p().knowledgeBase)),i=i.filter(c=>c&&!c.disabled);for(let c=0;c<i.length;c++){let l=i[c];l.id=l.id||`temp.${c}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!l.action&&l.type=="tour"&&(l.action=m=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=m=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new ge({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let r=o.search(t).map(c=>i.find(l=>l.id==c.id));for(let c of i)c.isContext&&(r.find(l=>l.id===c.id)||r.push(c));return this.lastResults=r,b(this.ai,{event_type:"kb_search",value:r.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),S.debug("Found results:",r),r}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${j++}`),S.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],i=!0,o=async(r,c)=>{S.debug(`Calling remote knowledge base action: ${r.id}`);let l={type:"action",userID:this.ai.userID,actionID:r.id,parameters:c},m=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!m.ok)throw new Error(`HTTP Error ${m.status} ${m.statusText}`);let d=await m.json();return a(d.updateItems||[]),d.response},a=r=>{for(let c of r){if(!c.id){S.warn("KB item skipped since it has no ID.",c);continue}let l=s.find(m=>m.id==c.id);if(l){l.name=c.name||l.name||"",l.content=c.content||l.content||"",l.disabled=c.disabled??l.disabled,l.isContext=c.isContext??l.isContext,l.parameters=c.parameters||l.parameters||[],l.tags=c.tags||l.tags,l.type=c.type||l.type;continue}s.push({...c,action:m=>o(c,m)})}};this.registerSource(e,async r=>{if(i&&n.includes(r))return s;let c={type:"search",userID:this.ai?.userID||"",query:r},l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let m=await l.json();return i=!m.noCache,n.includes(r)||n.push(r),a(m.items),s})}clone(){let t=new u(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}registerMCPSource(t){t.id||(t.id=`external.${j++}`);let e=new W(t);return this.registerSource(t.id,s=>e.search(s)),e}};import{v4 as F}from"uuid";var K=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
14
+ `:d.type=="tool_use"&&l.push(this.performToolCall(d));let m=await Promise.all(l);if(m.length>0){let d={role:"user",content:m};this.messageGroup.add({id:"msg-"+P(),content:JSON.stringify(d),customData:d}),s=!0}this.config.onAIMessage?.(n,!0),this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return n=n.trim(),this.config.onAIMessage?.(n,!1),n}async performToolCall(t){try{let e=this.toolGroup.getAll().find(n=>n.customData?.name==t.name);if(!e)throw new Error(`Tool ${t.name} not found`);this.config.onAIToolStart?.(t.name,t.input);let s=await e.customData.callback(t.input);return typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),{type:"tool_result",tool_use_id:t.id,content:String(s||"")}}catch(e){return O.error(`Error performing tool call ${t.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:t.id,content:`Error performing tool call ${t.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import he from"minisearch";var Q=u=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(t,e)=>{let s=await e.knowledgeBase.search(t.query),n=e;n._lastKBsearch=t.query,n._nextRequestUseKBitems=s,e.submitAnalyticsEvent({type:"kb-search",query:t.query,results:s});let i=s.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=s.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!t.url||typeof t.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(t.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:t.url}),`Opened URL: ${t.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!t.path||typeof t.path!="string")throw new Error("Path parameter is required and must be a string.");let s=new URL(t.path,window.location.origin).pathname;return window.location.href=s,e.submitAnalyticsEvent({type:"change-route",path:s}),`Changed route to: ${s}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!t.email_address||typeof t.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!t.subject||typeof t.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!t.body||typeof t.body!="string")throw new Error("Body parameter is required and must be a string.");let s=encodeURIComponent(t.email_address),n=encodeURIComponent(t.subject),i=encodeURIComponent(t.body),o=`mailto:${s}?subject=${n}&body=${i}`;try{window.location.href=o}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:t.email_address,subject:t.subject,body_length:t.body.length}),`Email opened in default mail client. Recipient: ${t.email_address}, Subject: ${t.subject}`}}];import{Client as ee}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as le}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as ce}from"@modelcontextprotocol/sdk/client/sse.js";var y={name:"@intelliweave/embedded",version:"2.0.72-beta.1",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as ue,ToolListChangedNotificationSchema as de}from"@modelcontextprotocol/sdk/types.js";var g=new h("MCPKnowledgeClient"),W=class{constructor(t){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=t}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){g.debug("Connecting to MCP client");let t=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new ee({name:y.name,version:y.version}),s=new le(new URL(this.config.baseURL));return await e.connect(s),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let s=new ee({name:y.name,version:y.version}),n=new ce(new URL(this.config.baseURL));return await s.connect(n),g.debug("Connected with SSE mode"),s});return await this.disconnect(),this.client=t,t.onerror=e=>{g.error(`MCP client error: ${e.message}`)},t.onclose=()=>{g.debug("MCP client connection closed"),this.client=void 0},t.setNotificationHandler(ue,e=>{e.params.level=="critical"?g.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?g.error(`[Server] ${e.params.data}`):e.params.level=="error"?g.error(`[Server] ${e.params.data}`):e.params.level=="warning"?g.warn(`[Server] ${e.params.data}`):e.params.level=="info"?g.info(`[Server] ${e.params.data}`):e.params.level=="debug"?g.debug(`[Server] ${e.params.data}`):g.log(`[Server] ${e.params.data}`)}),t.setNotificationHandler(de,e=>{g.debug("Tool list changed",e),this.fetchTools()}),g.debug("Fetching tools from MCP server..."),await this.fetchTools(),t}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let t=[],e;for(;;){let n=await this.client.listTools({cursor:e});e=n.nextCursor;for(let i of n.tools||[])t.push(i);if(!n?.tools?.length||!e)break}let s=[];for(let n of t){let i=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:o=>this.performToolCall(n.name,o),disabled:i})}g.debug(`Fetched ${t.length} tools from MCP server.`),this.tools=t,this.iwActions=s}async search(t){if(t==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),s=await this.performSearchCall(t);return e=e.concat(s),this.lastSearchQuery=t,this.lastSearchResults=e,g.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(t){let e=[];if(!this.config.searchToolName)return e;let s=this.tools.find(i=>i.name==this.config.searchToolName);if(!s)return g.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let n;if(s.inputSchema.required?.length==1){let i=s.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let i=Object.keys(s.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[i]:t})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let i=0;i<n.length;i++){let o=n[i];e.push({id:this.config.id+":"+this.config.searchToolName+":"+i,name:`Search result ${i+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return e}async performToolCall(t,e){await this.connect(),g.debug(`Performing tool call for ${t} with params:`,e),this.stats.toolsCalled+=1;let s=await this.client.callTool({name:t,arguments:e});if(s.isError){let n=s.content?.[0]?.text||"Unknown error";throw g.error(`Error calling tool ${t}: ${n}`),new Error(`Error calling tool ${t}: ${n}`)}if(Array.isArray(s.content)&&s.content.length==1&&s.content[0].type=="text")try{return JSON.parse(s.content[0].text)}catch{}return s.content||[]}};import{v4 as me}from"uuid";var ge=new h("Statistics"),_=[];async function b(u,t){let e={...t,event_id:me(),event_date:new Date().toISOString(),sdk_version:y.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(_.push(e),!u||(await new Promise(n=>setTimeout(n,5e3)),_.length===0))return;let s=_.slice();_.length=0;try{let n=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){ge.warn("Failed to submit analytics event:",n),_.push(...s);return}}var S=new h("KnowledgeBase"),j=1,$=class u{constructor(t){this._sources=[{id:"core.internal",query:async()=>Q(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=t}registerSource(t,e){let s=t;return typeof t=="function"&&(e=t,s=`source.${j++}`),this._sources.push({id:s,query:e}),s}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return p().knowledgeBaseSources&&(t=t.concat(p().knowledgeBaseSources)),t=t.concat(this._windowSources),t=t.filter(e=>!e.disabled),t}async search(t){let e=Date.now();S.debug(`Searching knowledge base for: ${t}`);let s=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});s.query=t,s.entries=[],s.sources=[],typeof document<"u"&&document.dispatchEvent(s),this._windowSources=s.sources;let i=(await Promise.all(this.sources.map(async c=>{try{let l=Date.now(),m=await c.query(t);return S.debug(`Source '${c.id}' took ${Date.now()-l}ms`),m||[]}catch(l){return S.warn(`Knowledge source '${c.id}' failed:`,l),[]}}))).flat();i=i.concat(s.entries),i=i.concat(this.manualEntries),p().knowledgeBase&&(i=i.concat(p().knowledgeBase)),i=i.filter(c=>c&&!c.disabled);for(let c=0;c<i.length;c++){let l=i[c];l.id=l.id||`temp.${c}`,l._functionID=l.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!l.action&&l.type=="tour"&&(l.action=m=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!l.action&&l.type=="info"&&(l.action=m=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new he({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let r=o.search(t).map(c=>i.find(l=>l.id==c.id));for(let c of i)c.isContext&&(r.find(l=>l.id===c.id)||r.push(c));return this.lastResults=r,b(this.ai,{event_type:"kb_search",value:r.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),S.debug("Found results:",r),r}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${j++}`),S.debug(`Registering remote knowledge base source: ${t}`);let s=[],n=[],i=!0,o=async(r,c)=>{S.debug(`Calling remote knowledge base action: ${r.id}`);let l={type:"action",userID:this.ai.userID,actionID:r.id,parameters:c},m=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!m.ok)throw new Error(`HTTP Error ${m.status} ${m.statusText}`);let d=await m.json();return a(d.updateItems||[]),d.response},a=r=>{for(let c of r){if(!c.id){S.warn("KB item skipped since it has no ID.",c);continue}let l=s.find(m=>m.id==c.id);if(l){l.name=c.name||l.name||"",l.content=c.content||l.content||"",l.disabled=c.disabled??l.disabled,l.isContext=c.isContext??l.isContext,l.parameters=c.parameters||l.parameters||[],l.tags=c.tags||l.tags,l.type=c.type||l.type;continue}s.push({...c,action:m=>o(c,m)})}};this.registerSource(e,async r=>{if(i&&n.includes(r))return s;let c={type:"search",userID:this.ai?.userID||"",query:r},l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let m=await l.json();return i=!m.noCache,n.includes(r)||n.push(r),a(m.items),s})}clone(){let t=new u(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t}registerMCPSource(t){t.id||(t.id=`external.${j++}`);let e=new W(t);return this.registerSource(t.id,s=>e.search(s)),e}};import{v4 as F}from"uuid";var K=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
15
15
 
16
16
  Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(e.toLowerCase().includes("true"))return!0;if(e.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+e)}async choose(t){let e=await this.instruct({...t,instruction:`${t.instruction}
17
17
 
@@ -28,10 +28,10 @@ Objects should have the following keys:
28
28
  ${t.extractions.map(n=>`- ${n.name} (${n.type}): ${n.description||"No description provided."}`).join(`
29
29
  `)}
30
30
  `,s=await this.instruct({...t,instruction:e});if(s=s.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),t.allowMultiple){let n=s.split(`
31
- `).map(o=>o.trim()).filter(o=>!!o.trim()),i=[];for(let o of n)try{i.push(JSON.parse(o))}catch(a){console.error("Failed to parse line as JSON:",o,a.message)}return i}else return[JSON.parse(s.trim())]}async generateMarkdown(t){return this.instruct({...t,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(t){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>t.instruction,t.callback&&e.addEventListener("output",s=>{t.callback(s.detail.message)}),t.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof t.data=="string"?t.data:JSON.stringify(t.data))||""}};var f=new g("Main"),te=new Set,x=class x extends EventTarget{constructor(){super(...arguments);this.conversationID=F();this.knowledgeBase=new $(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new K(this);this.userID=z();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this._lastTrackedTokens=0}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:x.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(e){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{f.debug("Loading configuration...");let s=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!s.ok)throw new Error(`Failed to load configuration: ${s.status} ${s.statusText}`);try{this.config=await s.json(),f.debug("Config loaded successfully:",this.config),this.config&&f.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(n){f.error("Failed to parse JSON response:",n);try{let i=await s.clone().text();f.error("Raw response that failed parsing:",i)}catch{f.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${n}`)}})(),(async()=>{try{let s=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!s.ok)throw new Error(`Failed to load VAD model: ${s.status} ${s.statusText}`);this.vadModel=await s.blob()}catch(s){f.warn(`Failed to load VAD model, some features will be unavailable. ${s.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let s of this.config.knowledge||[])s.url&&s.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:s.id,searchToolName:s.mcpSearchToolName,baseURL:s.url}):s.url&&this.knowledgeBase.registerSourceFromURL(s.url);for(let s of this.config.knowledge||[])s.entries?.length&&this.knowledgeBase.registerSource(s.id,()=>s.entries||[]);if(this.config.mcpServers)for(let s of this.config.mcpServers)this.knowledgeBase.registerMCPSource(s);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this.config}catch(s){throw f.warn("Failed to load:",s),this.error=s,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:s}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:s}})),s}}setModel(e){let s=this.models.find(i=>i.id==e);if(!s)throw new Error(`Model with ID "${e}" not found.`);let n={...s.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(i,o)=>{let a=this.knowledgeBase.getCachedEntry(i);this.onAIToolStart?.(a?.id||i,o)}};s.config.providerID==="anthropic"?this.currentModel=new N(n):this.currentModel=new D(n),this.currentModel.id=s.id,this.currentModel.metadata=s}async getContextPrefix(){let e=p().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let s=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,content:s}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,content:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,content:`# Knowledge Database
31
+ `).map(o=>o.trim()).filter(o=>!!o.trim()),i=[];for(let o of n)try{i.push(JSON.parse(o))}catch(a){console.error("Failed to parse line as JSON:",o,a.message)}return i}else return[JSON.parse(s.trim())]}async generateMarkdown(t){return this.instruct({...t,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(t){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>t.instruction,t.callback&&e.addEventListener("output",s=>{t.callback(s.detail.message)}),t.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof t.data=="string"?t.data:JSON.stringify(t.data))||""}};var f=new h("Main"),te=new Set,x=class x extends EventTarget{constructor(){super(...arguments);this.conversationID=F();this.knowledgeBase=new $(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new K(this);this.userID=z();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this._lastTrackedTokens=0}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:x.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(e){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{f.debug("Loading configuration...");let s=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!s.ok)throw new Error(`Failed to load configuration: ${s.status} ${s.statusText}`);try{this.config=await s.json(),f.debug("Config loaded successfully:",this.config),this.config&&f.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(n){f.error("Failed to parse JSON response:",n);try{let i=await s.clone().text();f.error("Raw response that failed parsing:",i)}catch{f.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${n}`)}})(),(async()=>{try{let s=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!s.ok)throw new Error(`Failed to load VAD model: ${s.status} ${s.statusText}`);this.vadModel=await s.blob()}catch(s){f.warn(`Failed to load VAD model, some features will be unavailable. ${s.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let s of this.config.knowledge||[])s.url&&s.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:s.id,searchToolName:s.mcpSearchToolName,baseURL:s.url}):s.url&&this.knowledgeBase.registerSourceFromURL(s.url);for(let s of this.config.knowledge||[])s.entries?.length&&this.knowledgeBase.registerSource(s.id,()=>s.entries||[]);if(this.config.mcpServers)for(let s of this.config.mcpServers)this.knowledgeBase.registerMCPSource(s);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this.config}catch(s){throw f.warn("Failed to load:",s),this.error=s,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:s}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:s}})),s}}setModel(e){let s=this.models.find(i=>i.id==e);if(!s)throw new Error(`Model with ID "${e}" not found.`);let n={...s.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(i,o)=>{let a=this.knowledgeBase.getCachedEntry(i);this.onAIToolStart?.(a?.id||i,o)}};s.config.providerID==="anthropic"?this.currentModel=new N(n):this.currentModel=new D(n),this.currentModel.id=s.id,this.currentModel.metadata=s}async getContextPrefix(){let e=p().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let s=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,content:s}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,content:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,content:`# Knowledge Database
32
32
  You have access to a database of knowledge base items. These include "info" type items which provide information and "tour" type items which contain instructions you should follow (only do one item at a time).${e.length==0?`
33
33
 
34
- (no items found)`:""}`});for(let i of e)if(i.type=="info"||i.type=="tour"||i.type=="input-event"){let o=G(typeof i.content=="function"?i.content():i.content);this.currentModel.contextGroup.add({id:i.id,customData:i,cannotRemove:i.isContext,sortOrder:101,disabled:i.disabled,content:`## ${i.type}: ${i.name}
35
- ${o}`})}else if(i.type=="action"){let o={name:i._functionID,description:G(typeof i.content=="function"?i.content():i.content),params:V(i.parameters||[{name:"value",type:"string",description:"Input"}]),removeFromMessageHistory:!!i.removeFromMessageHistory,callback:a=>this.toolRunKBAction(i,a),kb:i};this.currentModel.registerTool(o)}else continue;let n=this.currentModel.contextGroup.getAllAsString();this._lastSystemMsg!=n&&(this._lastSystemMsg=n,this.submitAnalyticsEvent({type:"system-msg",txt:n}))}processIncomingMessage(e,s){if(!s){let n=this.currentModel?.stats?.tokensUsed||0,i=n-(this._lastTrackedTokens||0);this._lastTrackedTokens=n,b(this,{event_type:"message_receive",value:i,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:n}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:s,message:e}})),this.onAIMessage?.(e,!!s)}async sendMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)return f.warn("Cannot send message while another message is being processed."),null;this.isProcessing=!0;try{this._messageStartTime=Date.now(),te.has(this.conversationID)||(te.add(this.conversationID),b(this,{event_type:"session_start"})),this._lastTrackedTokens=this.currentModel?.stats?.tokensUsed||0,b(this,{event_type:"message_send",value_str:"",event_properties:{message_length:e.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),this.submitAnalyticsEvent({type:"message",role:"user",message:e,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()});let s=await this.currentModel.sendMessage(e);return s&&typeof s=="string"&&s.trim().length>0&&this.submitAnalyticsEvent({type:"message",role:"assistant",message:s,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()}),s}finally{this.isProcessing=!1}}async toolRunKBAction(e,s){let n=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:s,ai:this}}));let i=await e.action(s,this),o=Date.now()-n;return b(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:s,execution_time_ms:o,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:s,ai:this,result:i}})),i}catch(i){let o=Date.now()-n;throw b(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:s,execution_time_ms:o,success:!1,error_message:i.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:s,ai:this,error:i}})),i}}submitAnalyticsEvent(e){p().analytics===!1||this.config?.analytics===!1||fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(s=>{process.env.NODE_ENV==="development"?f.warn(`Failed to submit analytics event to ${this.hubAPI+"/analytics/post"}:`,s):f.debug("Failed to submit analytics event:",s)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=F(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(e)}exportState(){return{type:"intelliweave/state/v1",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll().map(e=>e.customData)}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v1")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let s of e.messages)this.currentModel.messageGroup.add({id:F(),content:JSON.stringify(s),customData:s})}clone(){let e=new x;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.knowledgeBase=this.knowledgeBase.clone(),e}};x.version=y.version,x.builtInActionsVersion="1.0.0",f.debug("\u{1F6A8}\u{1F6A8}\u{1F6A8} NEW SDK BUILD LOADED - Built-in Actions Version:",x.builtInActionsVersion);var R=x;var L=new g("Stream"),se=class extends R{constructor(){super(...arguments);this.pendingEvents=[];this._isProcessingEvents=!1}async getContextPrefix(){let e=`You will receive an event stream, a list of JSON objects, one on each line. Respond with tool calls only and no text output.
34
+ (no items found)`:""}`});for(let i of e)if(i.type=="info"||i.type=="tour"||i.type=="input-event"){let o=G(typeof i.content=="function"?i.content():i.content);this.currentModel.contextGroup.add({id:i.id,customData:i,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="function"?i.disabled(this):i.disabled,content:`## ${i.type}: ${i.name}
35
+ ${o}`})}else if(i.type=="action"){let o={name:i._functionID,description:G(typeof i.content=="function"?i.content():i.content),params:V(i.parameters||[{name:"value",type:"string",description:"Input"}]),removeFromMessageHistory:!!i.removeFromMessageHistory,callback:a=>this.toolRunKBAction(i,a),kb:i};this.currentModel.registerTool(o)}else continue;let n=this.currentModel.contextGroup.getAllAsString();this._lastSystemMsg!=n&&(this._lastSystemMsg=n,this.submitAnalyticsEvent({type:"system-msg",txt:n}))}processIncomingMessage(e,s){if(!s){let n=this.currentModel?.stats?.tokensUsed||0,i=n-(this._lastTrackedTokens||0);this._lastTrackedTokens=n,b(this,{event_type:"message_receive",value:i,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:n}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:s,message:e}})),this.onAIMessage?.(e,!!s)}async sendMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)return f.warn("Cannot send message while another message is being processed."),null;this.isProcessing=!0;try{this._messageStartTime=Date.now(),te.has(this.conversationID)||(te.add(this.conversationID),b(this,{event_type:"session_start"})),this._lastTrackedTokens=this.currentModel?.stats?.tokensUsed||0,b(this,{event_type:"message_send",value_str:"",event_properties:{message_length:e.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),this.submitAnalyticsEvent({type:"message",role:"user",message:e,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()});let s=await this.currentModel.sendMessage(e);return s&&typeof s=="string"&&s.trim().length>0&&this.submitAnalyticsEvent({type:"message",role:"assistant",message:s,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()}),s}finally{this.isProcessing=!1}}async toolRunKBAction(e,s){let n=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:s,ai:this}}));let i=await e.action(s,this),o=Date.now()-n;return b(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:s,execution_time_ms:o,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:s,ai:this,result:i}})),i}catch(i){let o=Date.now()-n;throw b(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:s,execution_time_ms:o,success:!1,error_message:i.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:s,ai:this,error:i}})),i}}submitAnalyticsEvent(e){p().analytics===!1||this.config?.analytics===!1||fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(s=>{process.env.NODE_ENV==="development"?f.warn(`Failed to submit analytics event to ${this.hubAPI+"/analytics/post"}:`,s):f.debug("Failed to submit analytics event:",s)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=F(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(e)}exportState(){return{type:"intelliweave/state/v1",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll().map(e=>e.customData)}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v1")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let s of e.messages)this.currentModel.messageGroup.add({id:F(),content:JSON.stringify(s),customData:s})}clone(){let e=new x;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.knowledgeBase=this.knowledgeBase.clone(),e}};x.version=y.version,x.builtInActionsVersion="1.0.0",f.debug("\u{1F6A8}\u{1F6A8}\u{1F6A8} NEW SDK BUILD LOADED - Built-in Actions Version:",x.builtInActionsVersion);var R=x;var L=new h("Stream"),se=class extends R{constructor(){super(...arguments);this.pendingEvents=[];this._isProcessingEvents=!1}async getContextPrefix(){let e=`You will receive an event stream, a list of JSON objects, one on each line. Respond with tool calls only and no text output.
36
36
 
37
- `;return e+=await super.getContextPrefix(),e}postEvent(e){if(!e.eventName)throw new Error("Missing event name");if(e.direction||(e.direction="input"),e.direction!="input")throw new Error('Invalid event direction, must be "input".');e.timestamp||(e.timestamp=Date.now()),e.timestampDate=new Date(e.timestamp).toString(),L.log("Event in",JSON.stringify(e)),this.pendingEvents.push(e),this.processEvents()}async toolRunKBAction(e,s){if(e.type!="output-event")return await super.toolRunKBAction(e,s);this.emitEvent({...s,eventName:e.id,timestamp:Date.now(),timestampDate:new Date().toString(),direction:"output"})}emitEvent(e){L.log("Event out",JSON.stringify(e)),this.dispatchEvent(new CustomEvent("event",{detail:{ai:this,event:e}}))}async processEvents(){if(!this._isProcessingEvents){this._isProcessingEvents=!0;try{let e=this.pendingEvents.shift();if(!e)return;let s=this.knowledgeBase.getCachedEntry(e.eventName);s&&(e.assistantHint=typeof s.content=="function"?s.content():s.content);let n=JSON.stringify(e),i=await this.sendMessage(n)||"";if(!i.trim())return;this.emitEvent({eventName:"text",text:i,timestamp:Date.now(),timestampDate:new Date().toString(),direction:"output"})}catch(e){L.error("Error processing events:",e),this.emitEvent({eventName:"error",timestamp:Date.now(),timestampDate:new Date().toString(),errorMessage:e.message,direction:"output"})}finally{this._isProcessingEvents=!1,this.pendingEvents.length>0&&this.processEvents()}}}};export{N as AnthropicChat,X as BufferedWebSocket,I as ChatBase,D as ChatGPT,Y as FixedBufferStream,R as IntelliWeave,se as IntelliWeaveStream,$ as KnowledgeBase,g as Logging,W as MCPKnowledgeClient,H as ONNXModel,Z as Resampler,A as TokenWindow,U as TokenWindowGroup,Se as audioToWav,V as convertParamsToJSONSchema,Te as floatTo16BitPCM,_e as floatTo64BitPCM,z as getDefaultUserID,Ee as int16ToFloat32BitPCM,p as intelliweaveConfig,C as intelliweaveGlobalThis,q as sseEvents,G as trimWhitespaceInText};
37
+ `;return e+=await super.getContextPrefix(),e}postEvent(e){if(!e.eventName)throw new Error("Missing event name");if(e.direction||(e.direction="input"),e.direction!="input")throw new Error('Invalid event direction, must be "input".');e.timestamp||(e.timestamp=Date.now()),e.timestampDate=new Date(e.timestamp).toString(),L.log("Event in",JSON.stringify(e)),this.pendingEvents.push(e),this.processEvents()}async toolRunKBAction(e,s){if(e.type!="output-event")return await super.toolRunKBAction(e,s);this.emitEvent({...s,eventName:e.id,timestamp:Date.now(),timestampDate:new Date().toString(),direction:"output"})}emitEvent(e){L.log("Event out",JSON.stringify(e)),this.dispatchEvent(new CustomEvent("event",{detail:{ai:this,event:e}}))}async processEvents(){if(!this._isProcessingEvents){this._isProcessingEvents=!0;try{let e=this.pendingEvents.shift();if(!e)return;let s=this.knowledgeBase.getCachedEntry(e.eventName);s&&(e.assistantHint=typeof s.content=="function"?s.content():s.content);let n=JSON.stringify(e),i=await this.sendMessage(n)||"";if(!i.trim())return;this.emitEvent({eventName:"text",text:i,timestamp:Date.now(),timestampDate:new Date().toString(),direction:"output"})}catch(e){L.error("Error processing events:",e),this.emitEvent({eventName:"error",timestamp:Date.now(),timestampDate:new Date().toString(),errorMessage:e.message,direction:"output"})}finally{this._isProcessingEvents=!1,this.pendingEvents.length>0&&this.processEvents()}}}};export{N as AnthropicChat,X as BufferedWebSocket,I as ChatBase,D as ChatGPT,Y as FixedBufferStream,R as IntelliWeave,se as IntelliWeaveStream,$ as KnowledgeBase,h as Logging,W as MCPKnowledgeClient,H as ONNXModel,Z as Resampler,A as TokenWindow,U as TokenWindowGroup,Se as audioToWav,V as convertParamsToJSONSchema,Te as floatTo16BitPCM,_e as floatTo64BitPCM,z as getDefaultUserID,Ee as int16ToFloat32BitPCM,p as intelliweaveConfig,C as intelliweaveGlobalThis,q as sseEvents,G as trimWhitespaceInText};
@@ -821,6 +821,8 @@ interface WebWeaverGPTConfig {
821
821
  textColor?: string;
822
822
  /** Display mode: 'closed' (default - starts minimized) or 'open' (always open) */
823
823
  displayMode?: 'closed' | 'open';
824
+ /** Layout preset: 'widget' (default) or 'fullscreen' */
825
+ layout?: 'widget' | 'fullscreen';
824
826
  /** Positioning mode: 'fixed' (default - floats on page) or 'container' (fills parent container) */
825
827
  positioningMode?: 'fixed' | 'container';
826
828
  /** Horizontal position: 'left' or 'right' (default: 'right') - only used when positioningMode is 'fixed' */
@@ -1045,7 +1047,7 @@ interface KnowledgeBaseItem {
1045
1047
  /** If true, this item will always be returned from all search results. */
1046
1048
  isContext?: boolean;
1047
1049
  /** If true, this item will not be visible to the AI. */
1048
- disabled?: boolean;
1050
+ disabled?: boolean | ((ai: IntelliWeave) => boolean);
1049
1051
  /** List of parameters for an action function. Can either use IW's format, or a JSON Schema object. */
1050
1052
  parameters?: KnowledgeBaseActionParameterSchema;
1051
1053
  /**
@@ -1105,6 +1107,10 @@ declare const WebWeaverUI: (props: {
1105
1107
  hubAPI?: string;
1106
1108
  /** Display mode: 'closed' (default - starts minimized) or 'open' (always open) */
1107
1109
  displayMode?: "closed" | "open";
1110
+ /** Layout preset: 'widget' (default) or 'fullscreen' */
1111
+ layout?: "widget" | "fullscreen";
1112
+ /** Fullscreen header: 'show' (default) or 'hidden' */
1113
+ header?: "show" | "hidden";
1108
1114
  /** Positioning mode: 'fixed' (default - floats on page) or 'container' (fills parent container) */
1109
1115
  positioningMode?: "fixed" | "container";
1110
1116
  /** Horizontal position: 'left' or 'right' (default: 'right') - only used when positioningMode is 'fixed' */