@intelliweave/embedded 2.2.84 → 2.2.85

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
@@ -1276,6 +1276,10 @@ ConfigFormat extends ChatBaseConfig = ChatBaseConfig> {
1276
1276
  resetConversation(): void;
1277
1277
  /** Trim message list */
1278
1278
  trimMessages(): Promise<void>;
1279
+ /** Extract the most useful provider error message from the OpenAI and Anthropic SDK error shapes. */
1280
+ protected getProviderErrorMessage(err: any): string;
1281
+ /** Wrap raw provider errors in a standard Error while preserving the original cause for debugging. */
1282
+ protected createProviderError(providerName: string, err: any): Error;
1279
1283
  /** Register a tool. */
1280
1284
  registerTool(tool: ChatBaseToolConfig): TokenWindowGroupItem<ChatBaseToolConfig>;
1281
1285
  /** Find a tool based on the AI-safe name */
@@ -1377,6 +1381,8 @@ interface WebWeaverGPTConfig {
1377
1381
  instructions?: string;
1378
1382
  /** Introduction message, used in the automatic UI */
1379
1383
  introductionMessage?: string;
1384
+ /** Hidden prompt that the built-in UI runs when the chat opens for the first time */
1385
+ autoStartPrompt?: string;
1380
1386
  /** URL to the logo image to display in the chat UI */
1381
1387
  logo?: string;
1382
1388
  /** Background color or gradient or image for the chat UI */
@@ -1435,6 +1441,8 @@ interface WebWeaverGPTConfig {
1435
1441
  onCreateProvider?: (config: ChatBaseConfig) => ChatBase;
1436
1442
  /** Subagents */
1437
1443
  subagents?: SubAgentConfig[];
1444
+ /** Configuration cache key */
1445
+ cacheKey?: string;
1438
1446
  }
1439
1447
  /** Configuration for the IntelliWeave initialization */
1440
1448
  interface IntelliWeaveConfig extends Partial<WebWeaverGPTConfig> {
@@ -1802,6 +1810,8 @@ declare class WebWeaverEmbed extends BaseComponent {
1802
1810
  private _uiSessionStartTime?;
1803
1811
  /** Embedded action blocks already handled for each streamed message section */
1804
1812
  private _handledEmbeddedActionBlocks;
1813
+ /** True once the auto-start prompt has been sent for the current conversation */
1814
+ private _autoStartPromptHasRun;
1805
1815
  /** If opened by mobile swipe from the collapsed tab, swipe-close should return to collapsed tab */
1806
1816
  private _returnToCollapsedOnSwipeClose;
1807
1817
  /** Suppress the next container click event (used after a swipe-close to prevent re-opening) */
@@ -1844,6 +1854,12 @@ declare class WebWeaverEmbed extends BaseComponent {
1844
1854
  private applyConfigStylesAndAttributes;
1845
1855
  /** Called on update */
1846
1856
  onUpdate(): void;
1857
+ /** Get the hidden auto-start prompt from attributes, global config, or the loaded hub config. */
1858
+ private getAutoStartPrompt;
1859
+ /** Wrap the creator's prompt so the model knows this is a hidden first-open instruction. */
1860
+ private buildAutoStartPromptMessage;
1861
+ /** Run the auto-start prompt if the chat is open, loaded, and has not already run. */
1862
+ private maybeRunAutoStartPrompt;
1847
1863
  /** True when a config value explicitly enables a feature flag. */
1848
1864
  private isTruthyFeatureFlag;
1849
1865
  /** True when the current hub config or explicit attribute should remove the powered-by footer. */
@@ -1906,8 +1922,8 @@ declare class WebWeaverEmbed extends BaseComponent {
1906
1922
  private _isProcessing;
1907
1923
  /** The element which will receive the current message from the AI */
1908
1924
  currentOutputElement?: HTMLElement;
1909
- /** Process input text from the user */
1910
- processInput(inputText: string): Promise<void>;
1925
+ /** Process input text from the user. Set hideInputMessage to send a hidden prompt (e.g. the auto-start opener) without rendering a user bubble. */
1926
+ processInput(inputText: string, hideInputMessage?: boolean): Promise<void>;
1911
1927
  /** Called when the AI responds with some text */
1912
1928
  onAIMessage(messages: TokenWindowGroupItemParams<unknown>[], isPartial: boolean): Promise<void>;
1913
1929
  /** Updates a text element */
@@ -1948,6 +1964,7 @@ interface IntelliWeaveGlobalConfig {
1948
1964
  debug?: boolean;
1949
1965
  context?: string;
1950
1966
  introductionMessage?: string;
1967
+ autoStartPrompt?: string;
1951
1968
  introductionSuggestions?: string[];
1952
1969
  knowledgeBase?: KnowledgeBaseItem[];
1953
1970
  sources?: any[];
@@ -1966,8 +1983,6 @@ interface IntelliWeaveGlobalConfig {
1966
1983
  positionX?: 'left' | 'right';
1967
1984
  /** Vertical position: 'top' or 'bottom' (default: 'bottom') - only used when positioningMode is 'fixed' */
1968
1985
  positionY?: 'top' | 'bottom';
1969
- /** Extra data that will be passed to external knowledge base actions. */
1970
- extra: any;
1971
1986
  /** @deprecated Override the AI system context prefix. This should be controlled from the Hub now. */
1972
1987
  pageSummary?: string | (() => string) | (() => Promise<string>);
1973
1988
  /** List of knowledge base sources */
package/dist/node/node.js CHANGED
@@ -1,26 +1,26 @@
1
- import{v4 as j}from"uuid";function A(u){let e=(u||"").split(`
1
+ import{v4 as q}from"uuid";function P(d){let e=(d||"").split(`
2
2
  `);for(;e.length>0&&e[0].trim()=="";)e.shift();for(;e.length>0&&e[e.length-1].trim()=="";)e.pop();let t=1/0;for(let n of e){let s=n.match(/^\s*/)?.[0].length||0;t=Math.min(t,s)}return t>0&&t<1/0&&(e=e.map(n=>n.substring(t))),e.join(`
3
- `)}var se={};function B(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:se}function y(){return B().intelliweave=B().intelliweave||B().webWeaver||{},B().intelliweave}async function*ke(u){let e="",t=function*(){for(;;){let o=e.indexOf(`
3
+ `)}var ae={};function M(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:ae}function w(){return M().intelliweave=M().intelliweave||M().webWeaver||{},M().intelliweave}async function*Me(d){let e="",t=function*(){for(;;){let o=e.indexOf(`
4
4
 
5
- `);if(o==-1)break;let r=e.slice(0,o);e=e.slice(o+2);let c={},l=r.split(`
6
- `);for(let d of l){o=d.indexOf(": ");let a=d.slice(0,o),i=d.slice(o+2);o==-1&&(a=d,i=""),a&&(c[a]!==void 0?c[a]+=`
7
- `+i:c[a]=i)}yield c}},n=new TextDecoder,s=u.getReader();for(;;){let{done:o,value:r}=await s.read();if(o)break;e+=n.decode(r,{stream:!0}),yield*t()}e+=n.decode()+`
5
+ `);if(o==-1)break;let a=e.slice(0,o);e=e.slice(o+2);let u={},l=a.split(`
6
+ `);for(let c of l){o=c.indexOf(": ");let r=c.slice(0,o),i=c.slice(o+2);o==-1&&(r=c,i=""),r&&(u[r]!==void 0?u[r]+=`
7
+ `+i:u[r]=i)}yield u}},n=new TextDecoder,s=d.getReader();for(;;){let{done:o,value:a}=await s.read();if(o)break;e+=n.decode(a,{stream:!0}),yield*t()}e+=n.decode()+`
8
8
 
9
- `,yield*t()}function F(){if(y().userID)return y().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 q(u){let e=u;if(e?.type=="object"&&e.properties)return u;let t={type:"object",properties:{},required:[]};if(u&&Array.isArray(u)){let n=u;for(let s of n)t.properties[s.name]={type:s.type||"string",description:s.description||""}}return t}var M=class M{constructor(e){this.module="IntelliWeave";this.module=e}get debugEnabled(){return M.debug?!0:typeof window<"u"&&y().debug}log(...e){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...e)}debug(...e){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...e)}info(...e){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...e)}warn(...e){console.warn(`[IntelliWeave > ${this.module}]`,...e)}error(...e){console.error(`[IntelliWeave > ${this.module}]`,...e)}timer(e,...t){let n=Date.now();return this.debug(`[${e} 0ms] Started`,...t),(...s)=>this.debug(`[${e} ${Math.floor(Date.now()-n)}ms]`,...s)}};M.debug=!1;var g=M;var x=new g("ONNXModel"),J=class u{constructor(e){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=e,x.debug(`Model input parameters: ${e.inputNames.join(", ")}`),x.debug(`Model output parameters: ${e.outputNames.join(", ")}`)}static isSupported(){return!!u.lib}static async load(e){if(!u.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(x.debug("Loading ONNX runtime"),this.onnx=await u.lib()),x.debug(`Loading model: ${e}`);let t=await this.onnx.InferenceSession.create(e);return new u(t)}makeTensor(e,t,n=0){let s=1;for(let r of t)s*=r;let o;if(e=="float32")o=new u.onnx.Tensor(new Float32Array(s),t);else if(e=="int8")o=new u.onnx.Tensor(new Int8Array(s),t);else if(e=="int16")o=new u.onnx.Tensor(new Int16Array(s),t);else if(e=="int32")o=new u.onnx.Tensor(new Int32Array(s),t);else if(e=="int64")o=new u.onnx.Tensor(new BigInt64Array(s),t);else if(e=="uint8")o=new u.onnx.Tensor(new Uint8Array(s),t);else if(e=="uint16")o=new u.onnx.Tensor(new Uint16Array(s),t);else if(e=="uint32")o=new u.onnx.Tensor(new Uint32Array(s),t);else if(e=="uint64")o=new u.onnx.Tensor(new BigUint64Array(s),t);else throw new Error(`Invalid type: ${e}`);return n!==0&&(e=="int64"||e=="uint64")?o.data.fill(BigInt(n)):n!==0&&o.data.fill(n),o}registerConstant(e,t){if(!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);return this.constantTensors[e]=t,t}makeConstant(e,t,n,s=0){return this.registerConstant(e,this.makeTensor(t,n,s))}registerState(e,t,n){if(t||(t=e),!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);if(!this.session.outputNames.includes(t))throw new Error(`Model does not have an output named: ${t}`);return this.stateTensors[e]={outputName:t,tensor:n},n}makeState(e,t,n,s,o=0){return this.registerState(e,t,this.makeTensor(n,s,o))}async run(e={}){if(this._runActive&&this.ignoreIfBusy)return x.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 t in this.stateTensors)e[t]=this.stateTensors[t].tensor;for(let t in this.constantTensors)e[t]=this.constantTensors[t];try{let t=await this.session.run(e);for(let n in this.stateTensors){let s=t[this.stateTensors[n].outputName];this.stateTensors[n].tensor=s}return t}finally{this._runActive=!1}}resetState(){x.debug("Resetting state tensors");for(let e in this.stateTensors)this.stateTensors[e].tensor.data.fill(0)}};function Ee(u,e){let t=e.reduce((l,d)=>l+d.byteLength,0),n=new DataView(new ArrayBuffer(44));n.setUint8(0,82),n.setUint8(1,73),n.setUint8(2,70),n.setUint8(3,70),n.setUint32(4,44+t,!0),n.setUint8(8,87),n.setUint8(9,65),n.setUint8(10,86),n.setUint8(11,69);let s=1,o=32,r=s*o/8,c=u*r;return n.setUint8(12,102),n.setUint8(13,109),n.setUint8(14,116),n.setUint8(15,32),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,s,!0),n.setUint32(24,u,!0),n.setUint32(28,c,!0),n.setUint16(32,r,!0),n.setUint16(34,o,!0),n.setUint8(36,100),n.setUint8(37,97),n.setUint8(38,116),n.setUint8(39,97),n.setUint32(40,t,!0),new File([n,...e],"audio.wav",{type:"audio/wav"})}var z=class extends WebSocket{constructor(t){super(t);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(t){this.readyState==WebSocket.OPEN?super.send(t):this.pendingData.push(t)}_onOpen(){for(let t of this.pendingData)super.send(t);this.pendingData=[]}};var V=class{constructor(e,t){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!e)throw new Error(`Invalid array class: ${e}`);if(!t||t<=0)throw new Error(`Invalid output buffer size: ${t}`);this.ArrayClass=e,this.outputBufferSize=t}get queuedSize(){return this.partialBuffers.reduce((e,t)=>e+t.length,0)}feed(e){this.partialBuffers.push(e)}get canDrain(){return this.partialBuffers.reduce((t,n)=>t+n.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let e=this.ArrayClass,t=new e(this.outputBufferSize),n=0;for(;n!=t.length;){if(n>t.length)throw new Error(`Buffer overflow: ${n} > ${t.length}`);let s=t.length-n,o=this.partialBuffers[0],r=o.length-this.partialBufferOffset;r<s?(t.set(o.subarray(this.partialBufferOffset),n),n+=r,this.partialBuffers.shift(),this.partialBufferOffset=0):(t.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+s),n),n+=s,this.partialBufferOffset+=s)}return t}pad(){let e=this.queuedSize%this.outputBufferSize;if(e==0)return;let t=this.ArrayClass,n=new t(e);this.feed(n)}};var H=class{constructor(e,t,n,s){if(!e||!t||!n)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=e,this.toSampleRate=t,this.channels=n||0,this.inputBufferSize=s,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=e=>e,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(e){try{return this.outputBuffer.subarray(0,e)}catch{try{return this.outputBuffer.length=e,this.outputBuffer}catch{return this.outputBuffer.slice(0,e)}}}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=e=>{let t=e.length,n=this.channels,s,o,r,c,l,d,a,i,p;if(t%n!==0)throw new Error("Buffer was of incorrect sample length.");if(t<=0)return[];for(s=this.outputBufferSize,o=this.ratioWeight,r=this.lastWeight,c=0,l=0,d=0,a=0,i=this.outputBuffer;r<1;r+=o)for(l=r%1,c=1-l,this.lastWeight=r%1,p=0;p<this.channels;++p)i[a++]=this.lastOutput[p]*c+e[p]*l;for(r-=1,t-=n,d=Math.floor(r)*n;a<s&&d<t;){for(l=r%1,c=1-l,p=0;p<this.channels;++p)i[a++]=e[d+(p>0?p:0)]*c+e[d+(n+p)]*l;r+=o,d=Math.floor(r)*n}for(p=0;p<n;++p)this.lastOutput[p]=e[d++];return this.bufferSlice(a)}}multiTap(){this.resampler=e=>{let t=e.length,n,s,o=this.channels,r,c,l,d,a,i,p,h,f;if(t%o!==0)throw new Error("Buffer was of incorrect sample length.");if(t<=0)return[];for(n=this.outputBufferSize,s=[],r=this.ratioWeight,c=0,d=0,a=0,i=!this.tailExists,this.tailExists=!1,p=this.outputBuffer,h=0,f=0,l=0;l<o;++l)s[l]=0;do{if(i)for(c=r,l=0;l<o;++l)s[l]=0;else{for(c=this.lastWeight,l=0;l<o;++l)s[l]=this.lastOutput[l];i=!0}for(;c>0&&d<t;)if(a=1+d-f,c>=a){for(l=0;l<o;++l)s[l]+=e[d++]*a;f=d,c-=a}else{for(l=0;l<o;++l)s[l]+=e[d+(l>0?l:0)]*c;f+=c,c=0;break}if(c===0)for(l=0;l<o;++l)p[h++]=s[l]/r;else{for(this.lastWeight=c,l=0;l<o;++l)this.lastOutput[l]=s[l];this.tailExists=!0;break}}while(d<t&&h<n);return this.bufferSlice(h)}}resample(e){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(e)}};function Pe(u){let e=u.length,t=new Int16Array(e);for(;e--;){let n=Math.max(-1,Math.min(1,u[e]));t[e]=n<0?n*32768:n*32767}return t}function De(u){let e=u.length,t=new BigInt64Array(e);for(;e--;){let n=Math.max(-1,Math.min(1,u[e]));t[e]=BigInt(Math.floor(n<0?n*32768:n*32767))*0x100000000000n}return t}function We(u){let e=u.length,t=new Float32Array(e);for(;e--;){let n=u[e];t[e]=n>=32768?-(65536-n)/32768:n/32767}return t}import re from"openai";import{v4 as oe}from"uuid";var b=class{constructor(){this.size=4096;this.groups=[]}createGroup(e){let t=new G;return t.id=e,this.groups.push(t),t}group(e){return this.groups.find(t=>t.id===e)}static countTokensInText(e){return e==null?e="":typeof e=="number"?e=e+"":typeof e!="string"&&(e=JSON.stringify(e)),Math.ceil(e.length/3)}countTokens(){return this.groups.reduce((e,t)=>e+t.tokenCount,0)}removeOverflow(){let e=this.countTokens(),t=this.groups.reduce((n,s)=>n+s.weight,0);for(;e>this.size;){let n=this.groups.slice().sort((o,r)=>{let c=Math.floor(o.weight/t*this.size),l=Math.floor(r.weight/t*this.size),d=o.tokenCount-c;return r.tokenCount-l-d}),s=this.removeOneItem(n);if(!s)throw new Error("Too many items in the token window that cannot be removed.");e-=s.tokenCount}}removeOneItem(e){for(let t of e){let n=t.items.findIndex(o=>!o.cannotRemove);if(n===-1)continue;let s=t.items[n];return t.items.splice(n,1),t.tokenCount-=s.tokenCount,s}return null}},G=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
10
- `;this.itemPadding=0;this.sortFunction=(e,t)=>e.sortOrder!==t.sortOrder?e.sortOrder-t.sortOrder:e.dateAdded!==t.dateAdded?e.dateAdded-t.dateAdded:0}setItemPadding(e){return this.itemPadding=e,this.recalculateTokens(),this}sortBy(e){return this.sortFunction=e,this.items.sort(this.sortFunction),this}setSeparator(e){return this.separator==e?this:(this.separator=e,this.recalculateTokens(),this)}setWeight(e){return this.weight=e,this}recalculateTokens(){this.tokenCount=this.items.reduce((e,t)=>(t.tokenCount=b.countTokensInText(typeof t.data=="string"?t.data:JSON.stringify(t.data))+b.countTokensInText(this.separator)+this.itemPadding,e+t.tokenCount),0)}add(e){typeof e=="string"&&(e={source:"user",data:e});let t=e;t.id===void 0&&(t.id=oe()),!t.sections?.length&&typeof t.data=="string"?t.text=t.data:t.text=t.sections?.map(s=>{if(s.type==="text")return s.text||"";if(s.type==="tool_call")return`[Tool Call: ${s.toolKbName||s.toolName}] `;if(s.type==="tool_result"&&s.toolErrorResponse)return`[Tool Error: ${s.toolErrorResponse}] `}).filter(s=>!!s).join(`
9
+ `,yield*t()}function z(){if(w().userID)return w().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let d=localStorage.getItem("intelliweave.uid")||"";return d||(d=q(),localStorage.setItem("intelliweave.uid",d),d)}else return q()}function V(d){let e=d;if(e?.type=="object"&&e.properties)return d;let t={type:"object",properties:{},required:[]};if(d&&Array.isArray(d)){let n=d;for(let s of n)t.properties[s.name]={type:s.type||"string",description:s.description||""}}return t}var D=class D{constructor(e){this.module="IntelliWeave";this.module=e}get debugEnabled(){return D.debug?!0:typeof window<"u"&&w().debug}log(...e){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...e)}debug(...e){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...e)}info(...e){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...e)}warn(...e){console.warn(`[IntelliWeave > ${this.module}]`,...e)}error(...e){console.error(`[IntelliWeave > ${this.module}]`,...e)}timer(e,...t){let n=Date.now();return this.debug(`[${e} 0ms] Started`,...t),(...s)=>this.debug(`[${e} ${Math.floor(Date.now()-n)}ms]`,...s)}};D.debug=!1;var g=D;var S=new g("ONNXModel"),H=class d{constructor(e){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=e,S.debug(`Model input parameters: ${e.inputNames.join(", ")}`),S.debug(`Model output parameters: ${e.outputNames.join(", ")}`)}static isSupported(){return!!d.lib}static async load(e){if(!d.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(S.debug("Loading ONNX runtime"),this.onnx=await d.lib()),S.debug(`Loading model: ${e}`);let t=await this.onnx.InferenceSession.create(e);return new d(t)}makeTensor(e,t,n=0){let s=1;for(let a of t)s*=a;let o;if(e=="float32")o=new d.onnx.Tensor(new Float32Array(s),t);else if(e=="int8")o=new d.onnx.Tensor(new Int8Array(s),t);else if(e=="int16")o=new d.onnx.Tensor(new Int16Array(s),t);else if(e=="int32")o=new d.onnx.Tensor(new Int32Array(s),t);else if(e=="int64")o=new d.onnx.Tensor(new BigInt64Array(s),t);else if(e=="uint8")o=new d.onnx.Tensor(new Uint8Array(s),t);else if(e=="uint16")o=new d.onnx.Tensor(new Uint16Array(s),t);else if(e=="uint32")o=new d.onnx.Tensor(new Uint32Array(s),t);else if(e=="uint64")o=new d.onnx.Tensor(new BigUint64Array(s),t);else throw new Error(`Invalid type: ${e}`);return n!==0&&(e=="int64"||e=="uint64")?o.data.fill(BigInt(n)):n!==0&&o.data.fill(n),o}registerConstant(e,t){if(!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);return this.constantTensors[e]=t,t}makeConstant(e,t,n,s=0){return this.registerConstant(e,this.makeTensor(t,n,s))}registerState(e,t,n){if(t||(t=e),!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);if(!this.session.outputNames.includes(t))throw new Error(`Model does not have an output named: ${t}`);return this.stateTensors[e]={outputName:t,tensor:n},n}makeState(e,t,n,s,o=0){return this.registerState(e,t,this.makeTensor(n,s,o))}async run(e={}){if(this._runActive&&this.ignoreIfBusy)return S.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let t in this.stateTensors)e[t]=this.stateTensors[t].tensor;for(let t in this.constantTensors)e[t]=this.constantTensors[t];try{let t=await this.session.run(e);for(let n in this.stateTensors){let s=t[this.stateTensors[n].outputName];this.stateTensors[n].tensor=s}return t}finally{this._runActive=!1}}resetState(){S.debug("Resetting state tensors");for(let e in this.stateTensors)this.stateTensors[e].tensor.data.fill(0)}};function Ke(d,e){let t=e.reduce((l,c)=>l+c.byteLength,0),n=new DataView(new ArrayBuffer(44));n.setUint8(0,82),n.setUint8(1,73),n.setUint8(2,70),n.setUint8(3,70),n.setUint32(4,44+t,!0),n.setUint8(8,87),n.setUint8(9,65),n.setUint8(10,86),n.setUint8(11,69);let s=1,o=32,a=s*o/8,u=d*a;return n.setUint8(12,102),n.setUint8(13,109),n.setUint8(14,116),n.setUint8(15,32),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,s,!0),n.setUint32(24,d,!0),n.setUint32(28,u,!0),n.setUint16(32,a,!0),n.setUint16(34,o,!0),n.setUint8(36,100),n.setUint8(37,97),n.setUint8(38,116),n.setUint8(39,97),n.setUint32(40,t,!0),new File([n,...e],"audio.wav",{type:"audio/wav"})}var X=class extends WebSocket{constructor(t){super(t);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(t){this.readyState==WebSocket.OPEN?super.send(t):this.pendingData.push(t)}_onOpen(){for(let t of this.pendingData)super.send(t);this.pendingData=[]}};var Y=class{constructor(e,t){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!e)throw new Error(`Invalid array class: ${e}`);if(!t||t<=0)throw new Error(`Invalid output buffer size: ${t}`);this.ArrayClass=e,this.outputBufferSize=t}get queuedSize(){return this.partialBuffers.reduce((e,t)=>e+t.length,0)}feed(e){this.partialBuffers.push(e)}get canDrain(){return this.partialBuffers.reduce((t,n)=>t+n.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let e=this.ArrayClass,t=new e(this.outputBufferSize),n=0;for(;n!=t.length;){if(n>t.length)throw new Error(`Buffer overflow: ${n} > ${t.length}`);let s=t.length-n,o=this.partialBuffers[0],a=o.length-this.partialBufferOffset;a<s?(t.set(o.subarray(this.partialBufferOffset),n),n+=a,this.partialBuffers.shift(),this.partialBufferOffset=0):(t.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+s),n),n+=s,this.partialBufferOffset+=s)}return t}pad(){let e=this.queuedSize%this.outputBufferSize;if(e==0)return;let t=this.ArrayClass,n=new t(e);this.feed(n)}};var Q=class{constructor(e,t,n,s){if(!e||!t||!n)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=e,this.toSampleRate=t,this.channels=n||0,this.inputBufferSize=s,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=e=>e,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(e){try{return this.outputBuffer.subarray(0,e)}catch{try{return this.outputBuffer.length=e,this.outputBuffer}catch{return this.outputBuffer.slice(0,e)}}}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=e=>{let t=e.length,n=this.channels,s,o,a,u,l,c,r,i,p;if(t%n!==0)throw new Error("Buffer was of incorrect sample length.");if(t<=0)return[];for(s=this.outputBufferSize,o=this.ratioWeight,a=this.lastWeight,u=0,l=0,c=0,r=0,i=this.outputBuffer;a<1;a+=o)for(l=a%1,u=1-l,this.lastWeight=a%1,p=0;p<this.channels;++p)i[r++]=this.lastOutput[p]*u+e[p]*l;for(a-=1,t-=n,c=Math.floor(a)*n;r<s&&c<t;){for(l=a%1,u=1-l,p=0;p<this.channels;++p)i[r++]=e[c+(p>0?p:0)]*u+e[c+(n+p)]*l;a+=o,c=Math.floor(a)*n}for(p=0;p<n;++p)this.lastOutput[p]=e[c++];return this.bufferSlice(r)}}multiTap(){this.resampler=e=>{let t=e.length,n,s,o=this.channels,a,u,l,c,r,i,p,m,f;if(t%o!==0)throw new Error("Buffer was of incorrect sample length.");if(t<=0)return[];for(n=this.outputBufferSize,s=[],a=this.ratioWeight,u=0,c=0,r=0,i=!this.tailExists,this.tailExists=!1,p=this.outputBuffer,m=0,f=0,l=0;l<o;++l)s[l]=0;do{if(i)for(u=a,l=0;l<o;++l)s[l]=0;else{for(u=this.lastWeight,l=0;l<o;++l)s[l]=this.lastOutput[l];i=!0}for(;u>0&&c<t;)if(r=1+c-f,u>=r){for(l=0;l<o;++l)s[l]+=e[c++]*r;f=c,u-=r}else{for(l=0;l<o;++l)s[l]+=e[c+(l>0?l:0)]*u;f+=u,u=0;break}if(u===0)for(l=0;l<o;++l)p[m++]=s[l]/a;else{for(this.lastWeight=u,l=0;l<o;++l)this.lastOutput[l]=s[l];this.tailExists=!0;break}}while(c<t&&m<n);return this.bufferSlice(m)}}resample(e){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(e)}};function $e(d){let e=d.length,t=new Int16Array(e);for(;e--;){let n=Math.max(-1,Math.min(1,d[e]));t[e]=n<0?n*32768:n*32767}return t}function je(d){let e=d.length,t=new BigInt64Array(e);for(;e--;){let n=Math.max(-1,Math.min(1,d[e]));t[e]=BigInt(Math.floor(n<0?n*32768:n*32767))*0x100000000000n}return t}function Le(d){let e=d.length,t=new Float32Array(e);for(;e--;){let n=d[e];t[e]=n>=32768?-(65536-n)/32768:n/32767}return t}import ue from"openai";import{v4 as le}from"uuid";var y=class{constructor(){this.size=4096;this.groups=[]}createGroup(e){let t=new j;return t.id=e,this.groups.push(t),t}group(e){return this.groups.find(t=>t.id===e)}static countTokensInText(e){return e==null?e="":typeof e=="number"?e=e+"":typeof e!="string"&&(e=JSON.stringify(e)),Math.ceil(e.length/3)}countTokens(){return this.groups.reduce((e,t)=>e+t.tokenCount,0)}removeOverflow(){let e=this.countTokens(),t=this.groups.reduce((n,s)=>n+s.weight,0);for(;e>this.size;){let n=this.groups.slice().sort((o,a)=>{let u=Math.floor(o.weight/t*this.size),l=Math.floor(a.weight/t*this.size),c=o.tokenCount-u;return a.tokenCount-l-c}),s=this.removeOneItem(n);if(!s)throw new Error("Too many items in the token window that cannot be removed.");e-=s.tokenCount}}removeOneItem(e){for(let t of e){let n=t.items.findIndex(o=>!o.cannotRemove);if(n===-1)continue;let s=t.items[n];return t.items.splice(n,1),t.tokenCount-=s.tokenCount,s}return null}},j=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
10
+ `;this.itemPadding=0;this.sortFunction=(e,t)=>e.sortOrder!==t.sortOrder?e.sortOrder-t.sortOrder:e.dateAdded!==t.dateAdded?e.dateAdded-t.dateAdded:0}setItemPadding(e){return this.itemPadding=e,this.recalculateTokens(),this}sortBy(e){return this.sortFunction=e,this.items.sort(this.sortFunction),this}setSeparator(e){return this.separator==e?this:(this.separator=e,this.recalculateTokens(),this)}setWeight(e){return this.weight=e,this}recalculateTokens(){this.tokenCount=this.items.reduce((e,t)=>(t.tokenCount=y.countTokensInText(typeof t.data=="string"?t.data:JSON.stringify(t.data))+y.countTokensInText(this.separator)+this.itemPadding,e+t.tokenCount),0)}add(e){typeof e=="string"&&(e={source:"user",data:e});let t=e;t.id===void 0&&(t.id=le()),!t.sections?.length&&typeof t.data=="string"?t.text=t.data:t.text=t.sections?.map(s=>{if(s.type==="text")return s.text||"";if(s.type==="tool_call")return`[Tool Call: ${s.toolKbName||s.toolName}] `;if(s.type==="tool_result"&&s.toolErrorResponse)return`[Tool Error: ${s.toolErrorResponse}] `}).filter(s=>!!s).join(`
11
11
 
12
- `)||"";let n=this.items.find(s=>s.id===t.id);return n?(this.tokenCount-=n.tokenCount,Object.assign(n,t),t=n):this.items.push(t),t.dateAdded===void 0&&(t.dateAdded=Date.now()),t.sortOrder===void 0&&(t.sortOrder=0),t.disabled===void 0&&(t.disabled=!1),t.source===void 0&&(t.source="user"),t.sections===void 0&&(t.sections=[]),t.tokenCount=t.disabled?0:b.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+b.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=t.tokenCount,this.items.sort(this.sortFunction),t}remove(e){let t=this.items.findIndex(n=>n.id===e);return t===-1?!1:(this.tokenCount-=this.items[t].tokenCount||0,this.items.splice(t,1),!0)}getAllAsString(){return this.getAll().map(e=>e.text).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}},C=(o=>(o.Text="text",o.ToolCall="tool_call",o.ToolResult="tool_result",o.Thinking="thinking",o.Other="other",o))(C||{});import{v4 as ie}from"uuid";var X=new g("ChatBase"),_=class{constructor(e){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let e=new b;return e.createGroup("context").setSeparator(`
12
+ `)||"";let n=this.items.find(s=>s.id===t.id);return n?(this.tokenCount-=n.tokenCount,Object.assign(n,t),t=n):this.items.push(t),t.dateAdded===void 0&&(t.dateAdded=Date.now()),t.sortOrder===void 0&&(t.sortOrder=0),t.disabled===void 0&&(t.disabled=!1),t.source===void 0&&(t.source="user"),t.sections===void 0&&(t.sections=[]),t.tokenCount=t.disabled?0:y.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+y.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=t.tokenCount,this.items.sort(this.sortFunction),t}remove(e){let t=this.items.findIndex(n=>n.id===e);return t===-1?!1:(this.tokenCount-=this.items[t].tokenCount||0,this.items.splice(t,1),!0)}getAllAsString(){return this.getAll().map(e=>e.text).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}},x=(o=>(o.Text="text",o.ToolCall="tool_call",o.ToolResult="tool_result",o.Thinking="thinking",o.Other="other",o))(x||{});import{v4 as ce}from"uuid";var Z=new g("ChatBase"),C=class{constructor(e){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let e=new y;return e.createGroup("context").setSeparator(`
13
13
 
14
- `),e.createGroup("actions").setItemPadding(25),e.createGroup("messages").setItemPadding(10),e})();this.config=e,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}getBaseURL(){if(!this.config.endpoint)return;let e=this.config.endpoint;return e.endsWith("/chat/completions")&&(e=e.substring(0,e.length-17)),e}async sendMessage(e,t){throw new Error("Not implemented")}addUserMessage(e){throw new Error("Not implemented")}addAssistantMessage(e){throw new Error("Not implemented")}addTextMessage(e,t,n){this.messageGroup.add({id:"msg-"+ie(),source:t,data:n,sections:[{type:"text",text:e}]})}onBeforeIncomingMessage(e){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(e){return this.toolGroup.add({id:e.name,data:e,cannotRemove:!e.canRemove,sortOrder:101,disabled:!!e.kbItem?.disabled})}findToolBySafeName(e){return this.toolGroup.getAll().find(t=>t.id==e||t.data?.kbItem?.name==e)?.data}async executeTool(e,t){if(!e)throw new Error("Tool not found");X.debug(`Executing tool '${e.name}'`,t,e),this.config.onAIToolStart?.(e.kbItem?.name||e.name,t);let n;try{n=await e.callback(t)}catch(s){throw X.error(`Error executing tool '${e.name}'`,s),s}return typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success"),n}};import{v4 as ae}from"uuid";var $=new g("ChatGPT"),P=class extends _{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}createOpenAIClient(){return new re({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(e,t){this.addUserMessage(e);let n=this.createOpenAIClient(),s=!0,o=[];for(;s;){let r="msg-"+ae();s=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),$.debug("Before processing state",{messages:this.messageGroup.getAll().map(i=>i.data),tools:this.toolGroup.getAll().map(i=>i.data),context:this.contextGroup.getAll().map(i=>i.text)});let c=this.toolGroup.getAll().filter(i=>!!i?.data).map(i=>({type:"function",function:{name:i.data.name,description:i.data.description||"",parameters:{type:"object",...i.data?.params}}})),l,d;if(this.config.stream){let i=n.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:c,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let p of i){let h=i.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!h)continue;let f=this.parseMessageBlock(r,h,void 0,!0);this.config.onAIMessage?.([...o,f],!0),t?.([...o,f])}l=await i.finalMessage(),d=await i.totalUsage()}else{let i=await n.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:c,parallel_tool_calls:!0});l=i.choices[0].message,d=i.usage}l.role=="assistant"&&!l.content&&!l.tool_calls?.length&&(l.content=""),$.debug("Message received",l);let a=this.messageGroup.add(this.parseMessageBlock(r,l,d,!1));o.push(a),await Promise.all((l.tool_calls||[]).map(async i=>{if(i.type!="function")return;let p=this.findToolBySafeName(i.function.name);try{let h=null;try{h=i.function.arguments?JSON.parse(i.function.arguments):null}catch(ne){throw new Error(`The AI provided invalid JSON arguments for tool call ${i.function.name}: ${ne.message}`)}let f=await this.executeTool(p,h),S=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:i.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolSuccessResponse:f,toolCallInstanceID:i.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:i.id,content:f}});o.push(S)}catch(h){let f=h?.message||"An unknown error occurred",S=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:i.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolErrorResponse:f,toolCallInstanceID:i.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:i.id,content:`Error performing tool call ${i.function.name}: ${f}`}});o.push(S)}s=!0,this.config.onAIMessage?.(o,!0),t?.(o)})),this.stats.tokensUsed+=d?.total_tokens||0}return this.config.onAIMessage?.(o,!1),t?.(o),o}parseMessageBlock(e,t,n,s){let o=[];t.reasoning&&o.push({type:"thinking",text:t.reasoning});for(let r of t.tool_calls||[]){if(r.type!="function")continue;let c=this.findToolBySafeName(r.function.name),l=null;if(r.function.arguments)try{l=JSON.parse(r.function.arguments)}catch(d){s||$.error(`Failed to parse tool parameters for tool call ${r.function.name}:`,d)}o.push({type:"tool_call",toolName:r.function.name,toolKbID:c?.kbItem?.id,toolKbName:c?.kbItem?.name,toolCallInstanceID:r.id,toolCallHiddenInUI:c?.kbItem?.hideActionInUI,toolParameters:l})}return typeof t.content=="string"&&o.push({type:"text",text:t.content||""}),{id:e,data:t,sections:o,source:"assistant",streamingInProgress:s,usage:{inputTokens:n?.prompt_tokens||0,outputTokens:n?.completion_tokens||0,cachedInputTokens:0,totalTokens:(n?.prompt_tokens||0)+(n?.completion_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].data?.role=="tool";)this.messageGroup.items.shift()}};import le from"@anthropic-ai/sdk";import{v4 as ce}from"uuid";var Y=new g("AnthropicChat"),D=class extends _{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}async sendMessage(e,t){this.addUserMessage(e);let n=new le({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),s=!0,o=[];for(;s;){s=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),Y.debug("Before processing state",{messages:this.messageGroup.getAll().map(a=>a.data),tools:this.toolGroup.getAll().map(a=>a.data),context:this.contextGroup.getAll().map(a=>a.text)});let r=this.toolGroup.getAll().map(a=>({name:a.data?.name||"",description:a.data?.description||"",input_schema:{...a.data?.params,type:"object"}})),c;if(this.config.stream){let a=n.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(i=>i.data),tools:r,stream:!0});a.on("streamEvent",(i,p)=>{let h=this.parseMessageBlock(p,!0);this.config.onAIMessage?.([...o,h],!0),t?.([...o,h])});try{c=await a.finalMessage()}catch(i){throw i?.error?.error?.message?i.error.error:i}}else try{c=await n.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(a=>a.data),tools:r})}catch(a){throw a?.error?.error?.message?a.error.error:a}if(Y.debug("Message received",c),c.content?.length){let a=this.messageGroup.add(this.parseMessageBlock(c,!1));o.push(a)}let l=[],d=[];if(await Promise.all(c.content.map(async a=>{if(a.type!="tool_use")return;let i=this.findToolBySafeName(a.name);try{let p=await this.executeTool(i,a.input);d.push({type:"tool_result",tool_use_id:a.id,content:p}),l.push({type:"tool_result",toolKbID:i?.kbItem?.id,toolKbName:i?.kbItem?.name,toolName:a.name,toolSuccessResponse:p,toolCallInstanceID:a.id,toolCallHiddenInUI:i?.kbItem?.hideActionInUI})}catch(p){let h=p?.message||"An unknown error occurred";d.push({type:"tool_result",tool_use_id:a.id,content:`Error performing tool call ${a.name}: ${h}`}),l.push({type:"tool_result",toolKbID:i?.kbItem?.id,toolKbName:i?.kbItem?.name,toolName:a.name,toolErrorResponse:h,toolCallInstanceID:a.id,toolCallHiddenInUI:i?.kbItem?.hideActionInUI})}})),d.length>0){let a=this.messageGroup.add({id:"msg-"+ce(),sections:l,data:{role:"user",content:d}});o.push(a),s=!0,this.config.onAIMessage?.(o,!0),t?.(o)}this.stats.tokensUsed+=c.usage.input_tokens+c.usage.output_tokens}return this.config.onAIMessage?.(o,!1),t?.(o),o}parseMessageBlock(e,t){let n=[];for(let s of e.content)if(s.type=="thinking")n.push({type:"thinking",text:s.thinking||""});else if(s.type=="text")n.push({type:"text",text:s.text||""});else if(s.type=="tool_use"){let o=this.findToolBySafeName(s.name);n.push({type:"tool_call",toolName:s.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:s.input,toolCallInstanceID:s.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:e.id,data:{role:e.role,content:e.content},sections:n,source:"assistant",streamingInProgress:t,usage:{inputTokens:e.usage?.input_tokens||0,outputTokens:e.usage?.output_tokens||0,cachedInputTokens:e.usage?.cache_read_input_tokens||0,totalTokens:(e.usage?.input_tokens||0)+(e.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import ye 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,hideActionInUI:"after-complete",disabled:!u?.knowledgeBase?.allowRagSearch,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,t)=>{let n=await t.knowledgeBase.search(e.query),s=t;s._lastKBsearch=e.query,s._nextRequestUseKBitems=n;let o=n.filter(c=>c.type!="action").map(c=>"- "+c.name).join(`
15
- `)||"- (none)",r=n.filter(c=>c.type=="action").map(c=>"- "+c._functionID).join(`
14
+ `),e.createGroup("actions").setItemPadding(25),e.createGroup("messages").setItemPadding(10),e})();this.config=e,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}getBaseURL(){if(!this.config.endpoint)return;let e=this.config.endpoint;return e.endsWith("/chat/completions")&&(e=e.substring(0,e.length-17)),e}async sendMessage(e,t){throw new Error("Not implemented")}addUserMessage(e){throw new Error("Not implemented")}addAssistantMessage(e){throw new Error("Not implemented")}addTextMessage(e,t,n){this.messageGroup.add({id:"msg-"+ce(),source:t,data:n,sections:[{type:"text",text:e}]})}onBeforeIncomingMessage(e){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}getProviderErrorMessage(e){let t=[e?.error?.error?.message,e?.error?.message,e?.message];for(let o of t)if(typeof o=="string"&&o.trim())return o.trim();if(typeof e=="string"&&e.trim())return e.trim();let n=e?.status||e?.statusCode,s=e?.code||e?.type;if(n||s)return[n,s].filter(Boolean).join(" ");try{let o=JSON.stringify(e,null,2);if(o&&o!="{}")return o}catch{}return"Unknown provider error"}createProviderError(e,t){let n=this.getProviderErrorMessage(t),s=new Error(`${e} error: ${n}`);return s.cause=t,s}registerTool(e){return this.toolGroup.add({id:e.name,data:e,cannotRemove:!e.canRemove,sortOrder:101,disabled:!!e.kbItem?.disabled})}findToolBySafeName(e){return this.toolGroup.getAll().find(t=>t.id==e||t.data?.kbItem?.name==e)?.data}async executeTool(e,t){if(!e)throw new Error("Tool not found");Z.debug(`Executing tool '${e.name}'`,t,e),this.config.onAIToolStart?.(e.kbItem?.name||e.name,t);let n;try{n=await e.callback(t)}catch(s){throw Z.error(`Error executing tool '${e.name}'`,s),s}return typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success"),n}};import{v4 as de}from"uuid";var L=new g("ChatGPT"),W=class extends C{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}createOpenAIClient(){return new ue({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(e,t){this.addUserMessage(e);let n=this.createOpenAIClient(),s=!0,o=[];for(;s;){let a="msg-"+de();s=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),L.debug("Before processing state",{messages:this.messageGroup.getAll().map(i=>i.data),tools:this.toolGroup.getAll().map(i=>i.data),context:this.contextGroup.getAll().map(i=>i.text)});let u=this.toolGroup.getAll().filter(i=>!!i?.data).map(i=>({type:"function",function:{name:i.data.name,description:i.data.description||"",parameters:{type:"object",...i.data?.params}}})),l,c;if(this.config.stream)try{let i=n.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:u,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let p of i){let m=i.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!m)continue;let f=this.parseMessageBlock(a,m,void 0,!0);this.config.onAIMessage?.([...o,f],!0),t?.([...o,f])}l=await i.finalMessage(),c=await i.totalUsage()}catch(i){throw this.createProviderError("ChatGPT provider",i)}else try{let i=await n.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:u,parallel_tool_calls:!0});l=i.choices[0].message,c=i.usage}catch(i){throw this.createProviderError("ChatGPT provider",i)}l.role=="assistant"&&!l.content&&!l.tool_calls?.length&&(l.content=""),L.debug("Message received",l);let r=this.messageGroup.add(this.parseMessageBlock(a,l,c,!1));o.push(r),await Promise.all((l.tool_calls||[]).map(async i=>{if(i.type!="function")return;let p=this.findToolBySafeName(i.function.name);try{let m=null;try{m=i.function.arguments?JSON.parse(i.function.arguments):null}catch(re){throw new Error(`The AI provided invalid JSON arguments for tool call ${i.function.name}: ${re.message}`)}let f=await this.executeTool(p,m),T=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:i.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolSuccessResponse:f,toolCallInstanceID:i.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:i.id,content:f}});o.push(T)}catch(m){let f=m?.message||"An unknown error occurred",T=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:i.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolErrorResponse:f,toolCallInstanceID:i.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:i.id,content:`Error performing tool call ${i.function.name}: ${f}`}});o.push(T)}s=!0,this.config.onAIMessage?.(o,!0),t?.(o)})),this.stats.tokensUsed+=c?.total_tokens||0}return this.config.onAIMessage?.(o,!1),t?.(o),o}parseMessageBlock(e,t,n,s){let o=[];t.reasoning&&o.push({type:"thinking",text:t.reasoning});for(let a of t.tool_calls||[]){if(a.type!="function")continue;let u=this.findToolBySafeName(a.function.name),l=null;if(a.function.arguments)try{l=JSON.parse(a.function.arguments)}catch(c){s||L.error(`Failed to parse tool parameters for tool call ${a.function.name}:`,c)}o.push({type:"tool_call",toolName:a.function.name,toolKbID:u?.kbItem?.id,toolKbName:u?.kbItem?.name,toolCallInstanceID:a.id,toolCallHiddenInUI:u?.kbItem?.hideActionInUI,toolParameters:l})}return typeof t.content=="string"&&o.push({type:"text",text:t.content||""}),{id:e,data:t,sections:o,source:"assistant",streamingInProgress:s,usage:{inputTokens:n?.prompt_tokens||0,outputTokens:n?.completion_tokens||0,cachedInputTokens:0,totalTokens:(n?.prompt_tokens||0)+(n?.completion_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].data?.role=="tool";)this.messageGroup.items.shift()}};import pe from"@anthropic-ai/sdk";import{v4 as me}from"uuid";var ee=new g("AnthropicChat"),O=class extends C{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}async sendMessage(e,t){this.addUserMessage(e);let n=new pe({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),s=!0,o=[];for(;s;){s=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),ee.debug("Before processing state",{messages:this.messageGroup.getAll().map(r=>r.data),tools:this.toolGroup.getAll().map(r=>r.data),context:this.contextGroup.getAll().map(r=>r.text)});let a=this.toolGroup.getAll().map(r=>({name:r.data?.name||"",description:r.data?.description||"",input_schema:{...r.data?.params,type:"object"}})),u;if(this.config.stream){let r=n.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(i=>i.data),tools:a,stream:!0});r.on("streamEvent",(i,p)=>{let m=this.parseMessageBlock(p,!0);this.config.onAIMessage?.([...o,m],!0),t?.([...o,m])});try{u=await r.finalMessage()}catch(i){throw this.createProviderError("Anthropic provider",i)}}else try{u=await n.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(r=>r.data),tools:a})}catch(r){throw this.createProviderError("Anthropic provider",r)}if(ee.debug("Message received",u),u.content?.length){let r=this.messageGroup.add(this.parseMessageBlock(u,!1));o.push(r)}let l=[],c=[];if(await Promise.all(u.content.map(async r=>{if(r.type!="tool_use")return;let i=this.findToolBySafeName(r.name);try{let p=await this.executeTool(i,r.input);c.push({type:"tool_result",tool_use_id:r.id,content:p}),l.push({type:"tool_result",toolKbID:i?.kbItem?.id,toolKbName:i?.kbItem?.name,toolName:r.name,toolSuccessResponse:p,toolCallInstanceID:r.id,toolCallHiddenInUI:i?.kbItem?.hideActionInUI})}catch(p){let m=p?.message||"An unknown error occurred";c.push({type:"tool_result",tool_use_id:r.id,content:`Error performing tool call ${r.name}: ${m}`}),l.push({type:"tool_result",toolKbID:i?.kbItem?.id,toolKbName:i?.kbItem?.name,toolName:r.name,toolErrorResponse:m,toolCallInstanceID:r.id,toolCallHiddenInUI:i?.kbItem?.hideActionInUI})}})),c.length>0){let r=this.messageGroup.add({id:"msg-"+me(),sections:l,data:{role:"user",content:c}});o.push(r),s=!0,this.config.onAIMessage?.(o,!0),t?.(o)}this.stats.tokensUsed+=u.usage.input_tokens+u.usage.output_tokens}return this.config.onAIMessage?.(o,!1),t?.(o),o}parseMessageBlock(e,t){let n=[];for(let s of e.content)if(s.type=="thinking")n.push({type:"thinking",text:s.thinking||""});else if(s.type=="text")n.push({type:"text",text:s.text||""});else if(s.type=="tool_use"){let o=this.findToolBySafeName(s.name);n.push({type:"tool_call",toolName:s.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:s.input,toolCallInstanceID:s.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:e.id,data:{role:e.role,content:e.content},sections:n,source:"assistant",streamingInProgress:t,usage:{inputTokens:e.usage?.input_tokens||0,outputTokens:e.usage?.output_tokens||0,cachedInputTokens:e.usage?.cache_read_input_tokens||0,totalTokens:(e.usage?.input_tokens||0)+(e.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import Te from"minisearch";var te=d=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,hideActionInUI:"after-complete",disabled:!d?.knowledgeBase?.allowRagSearch,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,t)=>{let n=await t.knowledgeBase.search(e.query),s=t;s._lastKBsearch=e.query,s._nextRequestUseKBitems=n;let o=n.filter(u=>u.type!="action").map(u=>"- "+u.name).join(`
15
+ `)||"- (none)",a=n.filter(u=>u.type=="action").map(u=>"- "+u._functionID).join(`
16
16
  `)||"- (none)";return`Search complete, context has been updated.
17
17
  New information found:
18
18
  ${o}
19
19
 
20
20
  New tools available:
21
- ${r}`}},{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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let n=new URL(e.path,window.location.origin).pathname;return window.location.href=n,`Changed route to: ${n}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let n=encodeURIComponent(e.email_address),s=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),r=`mailto:${n}?subject=${s}&body=${o}`;try{window.location.href=r}catch(c){throw new Error(`Failed to open email client: ${c instanceof Error?c.message:String(c)}`)}return`Email opened in default mail client. Recipient: ${e.email_address}, Subject: ${e.subject}`}}];import{Client as de}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as pe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var v={name:"@intelliweave/embedded",version:"2.2.84",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{LoggingMessageNotificationSchema as he,ToolListChangedNotificationSchema as ge}from"@modelcontextprotocol/sdk/types.js";var m=new g("MCPKnowledgeClient"),me="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",W=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){m.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=t.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",t=new URL(this.config.proxy.url||me));let s=new de({name:v.name,version:v.version}),o=new pe(t,{requestInit:{headers:n}});return await s.connect(o),m.debug("Connected with HTTP streaming mode"),s});return await this.disconnect(),this.client=e,e.onerror=t=>{m.error(`MCP client error: ${t.message}`)},e.onclose=()=>{m.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(he,t=>{t.params.level=="critical"?m.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?m.error(`[Server] ${t.params.data}`):t.params.level=="error"?m.error(`[Server] ${t.params.data}`):t.params.level=="warning"?m.warn(`[Server] ${t.params.data}`):t.params.level=="info"?m.info(`[Server] ${t.params.data}`):t.params.level=="debug"?m.debug(`[Server] ${t.params.data}`):m.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(ge,t=>{m.debug("Tool list changed",t),this.fetchTools()}),m.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],t;for(;;){let o=await this.client.listTools({cursor:t});t=o.nextCursor;for(let r of o.tools||[])e.push(r);if(!o?.tools?.length||!t)break}let n=[],s=this.config.id||"mcp";for(let o of e){let r=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),c=`${s}_${o.name}`;n.push({id:c,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:r})}m.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),n=await this.performSearchCall(e);return t=t.concat(n),this.lastSearchQuery=e,this.lastSearchResults=t,m.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return m.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let s;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[o]:e})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let o=0;o<s.length;o++){let r=s[o];t.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof r=="string"?r:JSON.stringify(r)})}else t.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return t}async performToolCall(e,t){await this.connect(),m.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:t});if(n.isError){let s=n.content?.[0]?.text||"Unknown error";throw m.error(`Error calling tool ${e}: ${s}`),new Error(`Error calling tool ${e}: ${s}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};import{v4 as fe}from"uuid";var we=new g("Statistics"),E=[];async function I(u,e){let t={...e,event_id:fe(),event_date:new Date().toISOString(),sdk_version:v.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(E.push(t),!u||(await new Promise(s=>setTimeout(s,5e3)),E.length===0))return;let n=E.slice();E.length=0;try{let s=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){we.warn("Failed to submit analytics event:",s),E.push(...n);return}}var k=new g("KnowledgeBase"),be=8*1024,L=1,O=class u{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>Q(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,t){let n=e;return typeof e=="function"&&(t=e,n=`source.${L++}`),this._sources.push({id:n,query:t}),n}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&y().knowledgeBaseSources&&(e=e.concat(y().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(t=>!t.disabled),e}async search(e){k.debug(`Searching knowledge base for: ${e}`);let t=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async i=>{try{let p=Date.now(),h=await i.query(e);return k.debug(`Source '${i.id}' took ${Date.now()-p}ms`),h||[]}catch(p){return k.warn(`Knowledge source '${i.id}' failed:`,p),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&y().knowledgeBase&&(o=o.concat(y().knowledgeBase)),o=o.filter(i=>i&&!i.disabled);let r=new Map;for(let i of o)i.id&&r.set(i.id,(r.get(i.id)||0)+1);for(let[i,p]of r)if(p>1){k.warn(`Duplicate knowledge base item ID detected: '${i}' appears ${p} times. Adding suffixes to make them unique.`);let h=1,f=!0;for(let S of o)if(S.id===i){if(f){f=!1;continue}S.id=`${i}(${h})`,h++}}for(let i=0;i<o.length;i++){let p=o[i];p.id=p.id||`temp.${i}`,p._functionID=p.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let c=new ye({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});c.addAll(o);let d=c.search(e).map(i=>o.find(p=>p.id==i.id)).filter(Boolean),a=0;d=d.filter(i=>{if(i.isContext)return!0;let p=(i.content||"").length;return a+p>be?!1:(a+=p,!0)});for(let i of o)i.isContext&&(d.find(p=>p.id===i.id)||d.push(i));return this.lastResults=d,I(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),k.debug("Found results:",d),d}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${L++}`),k.debug(`Registering remote knowledge base source: ${e}`);let n=[],s=[],o=!0,r=async(l,d)=>{k.debug(`Calling remote knowledge base action: ${l.id}`);let a={type:"action",userID:this.ai.userID,actionID:l.id,parameters:d},i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let p=await i.json();return c(p.updateItems||[]),p.response},c=l=>{for(let d of l){if(!d.id){k.warn("KB item skipped since it has no ID.",d);continue}let a=n.find(i=>i.id==d.id);if(a){a.name=d.name||a.name||"",a.content=d.content||a.content||"",a.disabled=d.disabled??a.disabled,a.isContext=d.isContext??a.isContext,a.parameters=d.parameters||a.parameters||[],a.tags=d.tags||a.tags,a.type=d.type||a.type;continue}n.push({...d,action:i=>r(d,i)})}};this.registerSource(t,async l=>{if(o&&s.includes(l))return n;let d={type:"search",userID:this.ai?.userID||"",query:l},a=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!a.ok)throw new Error(`HTTP Error ${a.status} ${a.statusText}`);let i=await a.json();return o=!i.noCache,s.includes(l)||s.push(l),c(i.items),n})}clone(e){let t=new u(e);return t._sources=this._sources.slice(),t._windowSources=this._windowSources.slice(),t.manualEntries=this.manualEntries.slice(),t.allowGlobalConfigSources=this.allowGlobalConfigSources,t.allowWindowSources=this.allowWindowSources,t.allowRagSearch=this.allowRagSearch,t.ensureInternalKnowledge(),t}registerMCPSource(e){e.id||(e.id=`external.${L++}`);let t=new W(e);return this.registerSource(e.id,n=>t.search(n)),t}};function ve(u){let e="",t=[],n=0;for(;n<u.length;){let s=u.indexOf("<[[",n);if(s===-1){e+=u.slice(n);break}e+=u.slice(n,s);let o=u.indexOf("]]>",s+3);if(o===-1)break;let r=u.slice(s,o+3),c=u.slice(s+3,o).trim(),l={raw:r,content:c};try{let d=JSON.parse(c);d&&typeof d=="object"&&!Array.isArray(d)&&(l.action=d)}catch{}t.push(l),n=o+3}return{visibleText:e,actions:t.flatMap(s=>s.action?[s.action]:[]),blocks:t}}function Z(u){return ve(u).visibleText}var R=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>Z(e?.text||""))?.filter(e=>!!e)?.join(`
21
+ ${a}`}},{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"||!d?.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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.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"||!d?.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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let n=new URL(e.path,window.location.origin).pathname;return window.location.href=n,`Changed route to: ${n}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!d?.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:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let n=encodeURIComponent(e.email_address),s=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),a=`mailto:${n}?subject=${s}&body=${o}`;try{window.location.href=a}catch(u){throw new Error(`Failed to open email client: ${u instanceof Error?u.message:String(u)}`)}return`Email opened in default mail client. Recipient: ${e.email_address}, Subject: ${e.subject}`}}];import{Client as he}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as fe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var F={name:"@intelliweave/embedded",version:"2.2.85",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15","idb-keyval":"^6.2.5","iron-webcrypto":"^2.0.0",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{LoggingMessageNotificationSchema as we,ToolListChangedNotificationSchema as ye}from"@modelcontextprotocol/sdk/types.js";var h=new g("MCPKnowledgeClient"),be="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",R=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}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 e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=t.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",t=new URL(this.config.proxy.url||be));let s=new he({name:F.name,version:F.version}),o=new fe(t,{requestInit:{headers:n}});return await s.connect(o),h.debug("Connected with HTTP streaming mode"),s});return await this.disconnect(),this.client=e,e.onerror=t=>{h.error(`MCP client error: ${t.message}`)},e.onclose=()=>{h.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(we,t=>{t.params.level=="critical"?h.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?h.error(`[Server] ${t.params.data}`):t.params.level=="error"?h.error(`[Server] ${t.params.data}`):t.params.level=="warning"?h.warn(`[Server] ${t.params.data}`):t.params.level=="info"?h.info(`[Server] ${t.params.data}`):t.params.level=="debug"?h.debug(`[Server] ${t.params.data}`):h.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(ye,t=>{h.debug("Tool list changed",t),this.fetchTools()}),h.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],t;for(;;){let o=await this.client.listTools({cursor:t});t=o.nextCursor;for(let a of o.tools||[])e.push(a);if(!o?.tools?.length||!t)break}let n=[],s=this.config.id||"mcp";for(let o of e){let a=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible),u=`${s}_${o.name}`;n.push({id:u,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:l=>this.performToolCall(o.name,l),disabled:a})}h.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),n=await this.performSearchCall(e);return t=t.concat(n),this.lastSearchQuery=e,this.lastSearchResults=t,h.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return h.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let s;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[o]:e})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let o=0;o<s.length;o++){let a=s[o];t.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof a=="string"?a:JSON.stringify(a)})}else t.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return t}async performToolCall(e,t){await this.connect(),h.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:t});if(n.isError){let s=n.content?.[0]?.text||"Unknown error";throw h.error(`Error calling tool ${e}: ${s}`),new Error(`Error calling tool ${e}: ${s}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var A={name:"@intelliweave/embedded",version:"2.2.85",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.97","@types/lodash":"^4.17.24","@types/react":"^19.2.14",bestzip:"^2.2.2","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.24.3",react:"^19.2.4","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.18",vitest:"^4.1.0"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.80.0","@modelcontextprotocol/sdk":"^1.27.1","@types/json-schema":"^7.0.15","idb-keyval":"^6.2.5","iron-webcrypto":"^2.0.0",minisearch:"^7.2.0",openai:"^6.32.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-gfm":"^4.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};import{v4 as Ie}from"uuid";var ke=new g("Statistics"),B=[];async function b(d,e){let t={...e,event_id:Ie(),event_date:new Date().toISOString(),sdk_version:A.version,conversation_id:d?.conversationID||"",api_key:d?.apiKey||"",user_id:d?.userID||""};if(B.push(t),!d||(await new Promise(s=>setTimeout(s,5e3)),B.length===0))return;let n=B.slice();B.length=0;try{let s=await fetch(d.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){ke.warn("Failed to submit analytics event:",s),B.push(...n);return}}var v=new g("KnowledgeBase"),Se=8*1024,J=1,K=class d{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>te(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,t){let n=e;return typeof e=="function"&&(t=e,n=`source.${J++}`),this._sources.push({id:n,query:t}),n}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&w().knowledgeBaseSources&&(e=e.concat(w().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(t=>!t.disabled),e}async search(e){v.debug(`Searching knowledge base for: ${e}`);let t=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async i=>{try{let p=Date.now(),m=await i.query(e);return v.debug(`Source '${i.id}' took ${Date.now()-p}ms`),m||[]}catch(p){return v.warn(`Knowledge source '${i.id}' failed:`,p),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&w().knowledgeBase&&(o=o.concat(w().knowledgeBase)),o=o.filter(i=>i&&!i.disabled);let a=new Map;for(let i of o)i.id&&a.set(i.id,(a.get(i.id)||0)+1);for(let[i,p]of a)if(p>1){v.warn(`Duplicate knowledge base item ID detected: '${i}' appears ${p} times. Adding suffixes to make them unique.`);let m=1,f=!0;for(let T of o)if(T.id===i){if(f){f=!1;continue}T.id=`${i}(${m})`,m++}}for(let i=0;i<o.length;i++){let p=o[i];p.id=p.id||`temp.${i}`,p._functionID=p.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let u=new Te({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});u.addAll(o);let c=u.search(e).map(i=>o.find(p=>p.id==i.id)).filter(Boolean),r=0;c=c.filter(i=>{if(i.isContext)return!0;let p=(i.content||"").length;return r+p>Se?!1:(r+=p,!0)});for(let i of o)i.isContext&&(c.find(p=>p.id===i.id)||c.push(i));return this.lastResults=c,b(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),v.debug(`Found results for "${e}":`,c),c}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${J++}`),v.debug(`Registering remote knowledge base source: ${e}`);let n=[],s=[],o=!0,a=async(l,c)=>{v.debug(`Calling remote knowledge base action: ${l.id}`);let r={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let p=await i.json();return u(p.updateItems||[]),p.response},u=l=>{for(let c of l){if(!c.id){v.warn("KB item skipped since it has no ID.",c);continue}let r=n.find(i=>i.id==c.id);if(r){r.name=c.name||r.name||"",r.content=c.content||r.content||"",r.disabled=c.disabled??r.disabled,r.isContext=c.isContext??r.isContext,r.parameters=c.parameters||r.parameters||[],r.tags=c.tags||r.tags,r.type=c.type||r.type;continue}n.push({...c,action:i=>a(c,i)})}};this.registerSource(t,async l=>{if(o&&s.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let i=await r.json();return o=!i.noCache,s.includes(l)||s.push(l),u(i.items),n})}clone(e){let t=new d(e);return t._sources=this._sources.slice(),t._windowSources=this._windowSources.slice(),t.manualEntries=this.manualEntries.slice(),t.allowGlobalConfigSources=this.allowGlobalConfigSources,t.allowWindowSources=this.allowWindowSources,t.allowRagSearch=this.allowRagSearch,t.ensureInternalKnowledge(),t}registerMCPSource(e){e.id||(e.id=`external.${J++}`);let t=new R(e);return this.registerSource(e.id,n=>t.search(n)),t}};function xe(d){let e="",t=[],n=0;for(;n<d.length;){let s=d.indexOf("<[[",n);if(s===-1){e+=d.slice(n);break}e+=d.slice(n,s);let o=d.indexOf("]]>",s+3);if(o===-1)break;let a=d.slice(s,o+3),u=d.slice(s+3,o).trim(),l={raw:a,content:u};try{let c=JSON.parse(u);c&&typeof c=="object"&&!Array.isArray(c)&&(l.action=c)}catch{}t.push(l),n=o+3}return{visibleText:e,actions:t.flatMap(s=>s.action?[s.action]:[]),blocks:t}}function ne(d){return xe(d).visibleText}var N=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>ne(e?.text||""))?.filter(e=>!!e)?.join(`
22
22
 
23
- `)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,t)=>e+(t.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(t=>t.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(t=>t.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(t=>!!t)[0]||null}};import{v4 as ee}from"uuid";var K=class{constructor(e){this.ai=e}async boolean(e){let t=await this.instruct({...e,instruction:`${e.instruction}
23
+ `)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,t)=>e+(t.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(t=>t.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(t=>t.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(t=>!!t)[0]||null}};import{v4 as oe}from"uuid";var Ce=new g("AILogic"),G=class{constructor(e){this.ai=e}async boolean(e){let t=await this.instruct({...e,instruction:`${e.instruction}
24
24
 
25
25
  Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(t.toLowerCase().includes("true"))return!0;if(t.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+t)}async choose(e){let t=await this.instruct({...e,instruction:`${e.instruction}
26
26
 
@@ -37,7 +37,7 @@ Objects should have the following keys:
37
37
  ${e.extractions.map(s=>`- ${s.name} (${s.type}): ${s.description||"No description provided."}`).join(`
38
38
  `)}
39
39
  `,n=await this.instruct({...e,instruction:t});if(n=n.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),e.allowMultiple){let s=n.split(`
40
- `).map(r=>r.trim()).filter(r=>!!r.trim()),o=[];for(let r of s)try{o.push(JSON.parse(r))}catch(c){console.error("Failed to parse line as JSON:",r,c.message)}return o}else return[JSON.parse(n.trim())]}async generateMarkdown(e){return this.instruct({...e,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(e){let t=this.ai.clone();return t.resetConversation(),t.getContextPrefix=async()=>e.instruction,e.callback&&t.addEventListener("output",n=>{e.callback(n.detail.message)}),e.allowKB||(t.knowledgeBase._sources=[]),await t.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(n=>n.text())}};var N=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(t=>t.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,t=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(n,s)=>await this.runQuery(e,n.query)}])}remove(e){this.subagents=this.subagents.filter(t=>t.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,t){let n=e.apiKey||this.ai.apiKey,s=this.cachedSubagents[n];return s||(s=new U,s.userID=this.ai.userID,await s.load(n,e.config),this.cachedSubagents[n]=s),s=s.clone(),s.knowledgeBase.allowGlobalConfigSources=!1,s.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&s.knowledgeBase.reset(),s.knowledgeBase.allowRagSearch=!e.disableRagSearch,e.knowledge&&s.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(s),(await s.sendMessage(t)).text()}};var w=new g("Main"),te=new Set,T=class T extends EventTarget{constructor(){super(...arguments);this.conversationID=ee();this.knowledgeBase=new O(this);this.subAgents=new N(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new K(this);this.userID=F();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:T.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","embedded.suggestion - Add hidden follow-up suggestion buttons in the built-in UI","embedded.emoji - Trigger hidden emoji effects in the built-in UI","search - Search knowledge base"],enabledFlags:this.flags}}async load(t,n){if(this.apiKey=t,!t)throw new Error("API key is required to load the AI.");n?.userID&&(this.userID=n.userID),n?.hubAPI&&(this.hubAPI=n.hubAPI);try{await Promise.all([(async()=>{w.debug("Loading configuration...");let s=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t,userID:this.userID})});if(!s.ok){let o=`${s.status} ${s.statusText}`;try{let r=await s.json();r.error?o=r.error:r.message&&(o=r.message)}catch(r){w.debug("Could not parse error response body:",r)}throw new Error(`Failed to load configuration: ${o}`)}try{this.config=await s.json(),w.debug("Config loaded successfully:",this.config),n&&(this.config={...this.config,...n}),this.config&&w.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){w.error("Failed to parse JSON response:",o);try{let r=await s.clone().text();w.error("Raw response that failed parsing:",r)}catch{w.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(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){w.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);for(let s of this.config.subagents||[])this.subAgents.register(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}catch(s){throw w.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(t){let n=this.models.find(o=>o.id==t);if(!n)throw new Error(`Model with ID "${t}" not found.`);let s={...n.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,r)=>{let c=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(c?.id||o,r)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(s):n.config.providerID==="anthropic"?this.currentModel=new D(s):this.currentModel=new P(s),this.currentModel.id=n.id,this.currentModel.metadata=n}async getContextPrefix(){let t=y().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof t=="function"&&(t=await t()),t}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let t=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let n=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:n}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:A(`
40
+ `).map(a=>a.trim()).filter(a=>!!a.trim()),o=[];for(let a of s)try{o.push(JSON.parse(a))}catch(u){Ce.error("Failed to parse line as JSON:",a,u.message)}return o}else return[JSON.parse(n.trim())]}async generateMarkdown(e){return this.instruct({...e,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(e){let t=this.ai.clone();return t.resetConversation(),t.getContextPrefix=async()=>e.instruction,e.callback&&t.addEventListener("output",n=>{e.callback(n.detail.message)}),e.allowKB||(t.knowledgeBase._sources=[]),await t.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(n=>n.text())}};var U=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(t=>t.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,t=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(n,s)=>await this.runQuery(e,n.query)}])}remove(e){this.subagents=this.subagents.filter(t=>t.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,t){let n=e.apiKey||this.ai.apiKey,s=this.cachedSubagents[n];return s||(s=new $,s.userID=this.ai.userID,await s.load(n,e.config),this.cachedSubagents[n]=s),s=s.clone(),s.knowledgeBase.allowGlobalConfigSources=!1,s.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&s.knowledgeBase.reset(),s.knowledgeBase.allowRagSearch=!e.disableRagSearch,e.knowledge&&s.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(s),(await s.sendMessage(t)).text()}};import{get as _e,set as Ee}from"idb-keyval";import*as E from"iron-webcrypto";var _=new g("InternalUtilities");async function se(d,e,t){let s="IntelliWeave_98"+"JE".toLowerCase()+112+"Ho".toLowerCase(),o=`v1_${e}`,a=await Ae(s,o),u=null;try{let c=await _e(`intelliweave_config_v1_${e}`)||"";c&&(u=await E.unseal(c,a,E.defaults))}catch(c){c?.message?.includes("indexedDB is not defined")||_.warn(`Failed to get cached config for API key ${e}:`,c),u=null}_.debug("Loading configuration...");let l=await fetch(d+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,userID:t,cacheKey:u?.cacheKey,apiVersion:"v1"})});if(l.status===304&&u)return _.debug("Configuration not modified, using cached version"),u;if(l.ok){let c=await l.json();if(c.sealed){let r=await E.unseal(c.sealed,a,E.defaults);try{await Ee(`intelliweave_config_v1_${e}`,c.sealed)}catch(i){i?.message?.includes("indexedDB is not defined")||_.warn(`Failed to save config to cache for API key ${e}:`,i)}return r}else return _.warn("Received old API formatted config"),c}else{let c=`${l.status} ${l.statusText}`;try{let r=await l.json();r.error?c=r.error:r.message&&(c=r.message)}catch(r){_.debug("Could not parse error response body:",r)}throw new Error(`Failed to load configuration: ${c}`)}}async function Ae(d,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(d),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(e));return[...new Uint8Array(n)].map(s=>s.toString(16).padStart(2,"0")).join("")}var I=new g("Main"),ie=new Set,k=class k extends EventTarget{constructor(){super(...arguments);this.conversationID=oe();this.knowledgeBase=new K(this);this.subAgents=new U(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new G(this);this.userID=z();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:k.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","embedded.suggestion - Add hidden follow-up suggestion buttons in the built-in UI","embedded.emoji - Trigger hidden emoji effects in the built-in UI","search - Search knowledge base"],enabledFlags:this.flags}}async load(t,n){if(this.apiKey=t,!t)throw new Error("API key is required to load the AI.");n?.userID&&(this.userID=n.userID),n?.hubAPI&&(this.hubAPI=n.hubAPI);try{await Promise.all([(async()=>{this.config=await se(this.hubAPI,this.apiKey,this.userID),n&&(this.config={...this.config,...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){I.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);for(let s of this.config.subagents||[])this.subAgents.register(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}catch(s){throw I.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(t){let n=this.models.find(o=>o.id==t);if(!n)throw new Error(`Model with ID "${t}" not found.`);let s={...n.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,a)=>{let u=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(u?.id||o,a)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(s):n.config.providerID==="anthropic"?this.currentModel=new O(s):this.currentModel=new W(s),this.currentModel.id=n.id,this.currentModel.metadata=n}async getContextPrefix(){let t=w().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof t=="function"&&(t=await t()),t}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let t=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let n=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:n}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:P(`
41
41
  # RAG search
42
42
  Use the \`search\` tool proactively as much as possible to find missing information or tools.
43
43
  Use the \`search\` tool when you are unsure about specific details or actions to take.
@@ -45,17 +45,17 @@ ${e.extractions.map(s=>`- ${s.name} (${s.type}): ${s.description||"No descriptio
45
45
  If you're about to say "I don't have access..." or "I can't..." use the \`search\` tool first.
46
46
  `)}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,data:`# Knowledge Database${t.length==0?`
47
47
 
48
- (no items found)`:""}`});for(let s of t)if(s.type=="info"||s.type=="tour"||s.type=="input-event"){let o=A(s.content),r=!0;if(s.attachments?.length)for(let c of s.attachments)c.url&&(r&&(o+=`
48
+ (no items found)`:""}`});for(let s of t)if(s.type=="info"||s.type=="tour"||s.type=="input-event"){let o=P(s.content),a=!0;if(s.attachments?.length)for(let u of s.attachments)u.url&&(a&&(o+=`
49
49
 
50
50
  \`\`\`yaml
51
51
  attachments:
52
- `,r=!1),o+=`- name: "${c.name||""}"
53
- mimetype: "${c.mimeType||""}"
54
- url: "${c.url}"
55
- `);r||(o+="```\n"),this.currentModel.contextGroup.add({id:s.id,data:`## ${s.type}: ${s.name}
56
- ${o}`,cannotRemove:s.isContext,sortOrder:101,disabled:typeof s.disabled=="function"?s.disabled(this):s.disabled})}else if(s.type=="action"){let o={name:s._functionID,description:A(s.content),params:q(s.parameters||[{name:"value",type:"string",description:"Input"}]),callback:r=>this.toolRunKBAction(s,r),canRemove:!s.isContext,kbItem:s};this.currentModel.registerTool(o)}else continue;for(let s of this.lastKBItems)!s.isContext||!s.id||t.find(r=>r.id==s.id)||(this.currentModel.contextGroup.remove(s.id),s._functionID&&this.currentModel.toolGroup.remove(s._functionID));this.lastKBItems=t}processIncomingMessage(t,n){if(!n){let s=this.currentModel?.stats?.tokensUsed||0,o=t.reduce((r,c)=>r+(c.usage?.totalTokens||0),0);I(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:s}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:n,messages:t}})),this.onAIMessage?.(t,!!n)}async sendMessage(t,n){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),te.has(this.conversationID)||(te.add(this.conversationID),I(this,{event_type:"session_start"})),I(this,{event_type:"message_send",value_str:"",event_properties:{message_length:t.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:t}})),this.submitAnalyticsEvent({type:"message",role:"user",message:t});let s=Date.now(),o=await this.currentModel.sendMessage(t),r=new R(o);(this._voiceTracker||w.debug.bind(w))(`LLM response took ${Date.now()-s}ms`);let l=this.currentModel.contextGroup.getAllAsString();l+=`
52
+ `,a=!1),o+=`- name: "${u.name||""}"
53
+ mimetype: "${u.mimeType||""}"
54
+ url: "${u.url}"
55
+ `);a||(o+="```\n"),this.currentModel.contextGroup.add({id:s.id,data:`## ${s.type}: ${s.name}
56
+ ${o}`,cannotRemove:s.isContext,sortOrder:101,disabled:typeof s.disabled=="function"?s.disabled(this):s.disabled})}else if(s.type=="action"){let o={name:s._functionID,description:P(s.content),params:V(s.parameters||[{name:"value",type:"string",description:"Input"}]),callback:a=>this.toolRunKBAction(s,a),canRemove:!s.isContext,kbItem:s};this.currentModel.registerTool(o)}else continue;for(let s of this.lastKBItems)!s.isContext||!s.id||t.find(a=>a.id==s.id)||(this.currentModel.contextGroup.remove(s.id),s._functionID&&this.currentModel.toolGroup.remove(s._functionID));this.lastKBItems=t}processIncomingMessage(t,n){if(!n){let s=this.currentModel?.stats?.tokensUsed||0,o=t.reduce((a,u)=>a+(u.usage?.totalTokens||0),0);b(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:s}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:n,messages:t}})),this.onAIMessage?.(t,!!n)}async sendMessage(t,n){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),ie.has(this.conversationID)||(ie.add(this.conversationID),b(this,{event_type:"session_start"})),b(this,{event_type:"message_send",value_str:"",event_properties:{message_length:t.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:t}})),this.submitAnalyticsEvent({type:"message",role:"user",message:t});let s=Date.now(),o=await this.currentModel.sendMessage(t),a=new N(o);(this._voiceTracker||I.debug.bind(I))(`LLM response took ${Date.now()-s}ms`);let l=this.currentModel.contextGroup.getAllAsString();l+=`
57
57
 
58
58
  === TOOLS ===
59
59
 
60
- `+this.currentModel.toolGroup.getAll().map(d=>"- "+d.data?.name).join(`
61
- `),this._lastSystemMsg!=l&&(this._lastSystemMsg=l,this.submitAnalyticsEvent({type:"system-msg",txt:l}));for(let d of o)for(let a of d.sections||[])if(a.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:a.text||""});else if(a.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:a.text||""});else if(a.type=="tool_call"){let i=r.toolResult(a.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:a.toolKbID||"",actionName:a.toolKbName||"",value:a.toolParameters,result:i?.toolErrorResponse||i?.toolSuccessResponse,isError:!!i?.toolErrorResponse})}else a.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return r}finally{this.isProcessing=!1}}async toolRunKBAction(t,n){let s=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:t,input:n,ai:this}}));let o=await t.action(n,this),r=Date.now()-s;return I(this,{event_type:"tool_call",value_str:t.id||"",event_properties:{tool_args:n,execution_time_ms:r,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:t,input:n,ai:this,result:o}})),o}catch(o){let r=Date.now()-s;throw I(this,{event_type:"tool_call",value_str:t.id||"",event_properties:{tool_args:n,execution_time_ms:r,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:t,input:n,ai:this,error:o}})),o}}submitAnalyticsEvent(t){if(y().analytics===!1||this.config?.analytics===!1)return;let n=fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(s=>{process.env.NODE_ENV==="development"?w.warn(`Failed to submit analytics event to ${this.hubAPI+"/analytics/post"}:`,s):w.debug("Failed to submit analytics event:",s)});this.activeAnalyticsPromises.push(n),n.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(s=>s!==n)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=ee(),this._lastSystemMsg="")}insertAssistantMessage(t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(t)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(t?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${t.type}`);this.conversationID=t.conversationID;for(let n of t.messages)this.currentModel.messageGroup.add(n)}clone(){let t=new T;return t.apiKey=this.apiKey,t.config=this.config,t.models=this.models,this.config?.id&&t.setModel(this.config.id),t.audio=this.audio,t.vadModel=this.vadModel,t.userID=this.userID,t.knowledgeBase=this.knowledgeBase.clone(t),t}get messages(){return this.currentModel?.messageGroup.items||[]}};T.version=v.version,T.builtInActionsVersion="1.2.0",w.debug(`Loaded: version=${v.version} builtInActionsVersion=${T.builtInActionsVersion}`);var U=T;export{D as AnthropicChat,z as BufferedWebSocket,_ as ChatBase,P as ChatGPT,V as FixedBufferStream,U as IntelliWeave,R as IntelliWeaveMessageParser,O as KnowledgeBase,g as Logging,W as MCPKnowledgeClient,J as ONNXModel,H as Resampler,b as TokenWindow,G as TokenWindowGroup,C as TokenWindowGroupItemSectionType,Ee as audioToWav,q as convertParamsToJSONSchema,Pe as floatTo16BitPCM,De as floatTo64BitPCM,F as getDefaultUserID,We as int16ToFloat32BitPCM,y as intelliweaveConfig,B as intelliweaveGlobalThis,ke as sseEvents,A as trimWhitespaceInText};
60
+ `+this.currentModel.toolGroup.getAll().map(c=>"- "+c.data?.name).join(`
61
+ `),this._lastSystemMsg!=l&&(this._lastSystemMsg=l,this.submitAnalyticsEvent({type:"system-msg",txt:l}));for(let c of o)for(let r of c.sections||[])if(r.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:r.text||""});else if(r.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:r.text||""});else if(r.type=="tool_call"){let i=a.toolResult(r.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:r.toolKbID||"",actionName:r.toolKbName||"",value:r.toolParameters,result:i?.toolErrorResponse||i?.toolSuccessResponse,isError:!!i?.toolErrorResponse})}else r.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return a}finally{this.isProcessing=!1}}async toolRunKBAction(t,n){let s=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:t,input:n,ai:this}}));let o=await t.action(n,this),a=Date.now()-s;return b(this,{event_type:"tool_call",value_str:t.id||"",event_properties:{tool_args:n,execution_time_ms:a,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:t,input:n,ai:this,result:o}})),o}catch(o){let a=Date.now()-s;throw b(this,{event_type:"tool_call",value_str:t.id||"",event_properties:{tool_args:n,execution_time_ms:a,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:t,input:n,ai:this,error:o}})),o}}submitAnalyticsEvent(t){if(w().analytics===!1||this.config?.analytics===!1)return;let n=fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(s=>{process.env.NODE_ENV==="development"?I.warn(`Failed to submit analytics event to ${this.hubAPI+"/analytics/post"}:`,s):I.debug("Failed to submit analytics event:",s)});this.activeAnalyticsPromises.push(n),n.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(s=>s!==n)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=oe(),this._lastSystemMsg="")}insertAssistantMessage(t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(t)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(t?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${t.type}`);this.conversationID=t.conversationID;for(let n of t.messages)this.currentModel.messageGroup.add(n)}clone(){let t=new k;return t.apiKey=this.apiKey,t.config=this.config,t.models=this.models,this.config?.id&&t.setModel(this.config.id),t.audio=this.audio,t.vadModel=this.vadModel,t.userID=this.userID,t.knowledgeBase=this.knowledgeBase.clone(t),t}get messages(){return this.currentModel?.messageGroup.items||[]}};k.version=A.version,k.builtInActionsVersion="1.2.0",I.debug(`Loaded: version=${A.version} builtInActionsVersion=${k.builtInActionsVersion}`);var $=k;export{O as AnthropicChat,X as BufferedWebSocket,C as ChatBase,W as ChatGPT,Y as FixedBufferStream,$ as IntelliWeave,N as IntelliWeaveMessageParser,K as KnowledgeBase,g as Logging,R as MCPKnowledgeClient,H as ONNXModel,Q as Resampler,y as TokenWindow,j as TokenWindowGroup,x as TokenWindowGroupItemSectionType,Ke as audioToWav,V as convertParamsToJSONSchema,$e as floatTo16BitPCM,je as floatTo64BitPCM,z as getDefaultUserID,Le as int16ToFloat32BitPCM,w as intelliweaveConfig,M as intelliweaveGlobalThis,Me as sseEvents,P as trimWhitespaceInText};
@@ -890,6 +890,10 @@ ConfigFormat extends ChatBaseConfig = ChatBaseConfig> {
890
890
  resetConversation(): void;
891
891
  /** Trim message list */
892
892
  trimMessages(): Promise<void>;
893
+ /** Extract the most useful provider error message from the OpenAI and Anthropic SDK error shapes. */
894
+ protected getProviderErrorMessage(err: any): string;
895
+ /** Wrap raw provider errors in a standard Error while preserving the original cause for debugging. */
896
+ protected createProviderError(providerName: string, err: any): Error;
893
897
  /** Register a tool. */
894
898
  registerTool(tool: ChatBaseToolConfig): TokenWindowGroupItem<ChatBaseToolConfig>;
895
899
  /** Find a tool based on the AI-safe name */
@@ -991,6 +995,8 @@ interface WebWeaverGPTConfig {
991
995
  instructions?: string;
992
996
  /** Introduction message, used in the automatic UI */
993
997
  introductionMessage?: string;
998
+ /** Hidden prompt that the built-in UI runs when the chat opens for the first time */
999
+ autoStartPrompt?: string;
994
1000
  /** URL to the logo image to display in the chat UI */
995
1001
  logo?: string;
996
1002
  /** Background color or gradient or image for the chat UI */
@@ -1049,6 +1055,8 @@ interface WebWeaverGPTConfig {
1049
1055
  onCreateProvider?: (config: ChatBaseConfig) => ChatBase;
1050
1056
  /** Subagents */
1051
1057
  subagents?: SubAgentConfig[];
1058
+ /** Configuration cache key */
1059
+ cacheKey?: string;
1052
1060
  }
1053
1061
  /** Configuration for the IntelliWeave initialization */
1054
1062
  interface IntelliWeaveConfig extends Partial<WebWeaverGPTConfig> {
@@ -1326,6 +1334,8 @@ declare const WebWeaverUI: (props: {
1326
1334
  context?: string;
1327
1335
  /** The introduction message to show when the user first opens the chat. Not needed since it's pulled from the Persona on the hub. */
1328
1336
  introductionMessage?: string;
1337
+ /** Hidden prompt that runs when the user first opens the chat. Not needed since it's pulled from the Persona on the hub. */
1338
+ autoStartPrompt?: string;
1329
1339
  /** Suggestion buttons to show on the first introduction message */
1330
1340
  introductionSuggestions?: string[];
1331
1341
  /** The knowledge base to add to the AI. */