@intelliweave/embedded 1.6.53 → 1.6.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/component/component.d.ts +4 -0
- package/dist/component/component.js +13 -8
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.d.ts +4 -0
- package/dist/node/node.js +3 -3
- package/dist/react/react.d.ts +6 -0
- package/dist/react/react.js +13 -8
- package/dist/script-tag/script-tag.js +12 -7
- package/dist/webpack/index.d.ts +6 -0
- package/dist/webpack/index.js +12 -7
- package/package.json +1 -1
|
@@ -6,7 +6,7 @@ import{b as pr,c as _i,d as Hi}from"./chunk-FSRPMVAS.js";var gs=pr((vw,ms)=>{"us
|
|
|
6
6
|
`);for(let c of l){o=c.indexOf(": ");let u=c.slice(0,o),p=c.slice(o+2);o==-1&&(u=c,p=""),u&&(s[u]!==void 0?s[u]+=`
|
|
7
7
|
`+p:s[u]=p)}yield s}},r=new TextDecoder,i=e.getReader();for(;;){let{done:o,value:a}=await i.read();if(o)break;n+=r.decode(a,{stream:!0}),yield*t()}n+=r.decode()+`
|
|
8
8
|
|
|
9
|
-
`,yield*t()}function Yi(){if(Q().userID)return Q().userID;if(typeof localStorage<"u"){let e=localStorage.getItem("intelliweave.uid")||"";return e||(e=Ue(),localStorage.setItem("intelliweave.uid",e),e)}else return Ue()}var Qt=class Qt{constructor(n){this.module="IntelliWeave";this.module=n}get debugEnabled(){return Qt.debug?!0:typeof window<"u"&&Q().debug}log(...n){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...n)}debug(...n){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...n)}info(...n){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...n)}warn(...n){console.warn(`[IntelliWeave > ${this.module}]`,...n)}error(...n){console.error(`[IntelliWeave > ${this.module}]`,...n)}timer(n,...t){let r=Date.now();return this.debug(`[${n} 0ms] Started`,...t),(...i)=>this.debug(`[${n} ${Math.floor(Date.now()-r)}ms]`,...i)}};Qt.debug=!1;var U=Qt;var Pe=new U("ChatGPT"),qt=class{constructor(n){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...n}}async sendMessage(n){this.messages.push({role:"user",content:n}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let t=this.messages[this.messages.length-1];return t?.role=="assistant"&&t.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),Pe.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let n=this.messages[this.messages.length-1];if(n?.role=="user"||n?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(n?.role=="assistant"&&n?.tool_calls?.length){for(let t of n.tool_calls)await this.processToolCall(t);await this.processMessages()}}async trimMessages(){for(;;){let n=await this.sendToAPI(!0);if(JSON.stringify(n).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){Pe.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(n){let t=0;for(let l=this.messages.length-1;l>=0;l--)if(this.messages[l].role=="assistant"&&this.messages[l].tool_calls){if(t+=1,t>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[l].role=="user")break;Pe.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let r={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let l of this.tools){l.description&&l.description.length>1024&&Pe.warn(`Tool description for "${l.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:l.name,description:(l.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(l.params))for(let u of l.params)c.function.parameters.properties[u.name]={type:u.type,description:u.description};else if(l.params){let u=l.params;for(let p in u)c.function.parameters.properties[p]={type:"string",description:u[p]}}r.tools.push(c)}r.user||delete r.user,r.tools.length||delete r.tools;let i={};if(i["Content-Type"]="application/json",this.config.apiKey&&(i.Authorization=`Bearer ${this.config.apiKey}`),n)return r;let o=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(r)});if(!o.ok){let l=`${o.status} ${o.statusText}`;try{let u=await o.json();l=u.errorText||u.error?.message||u.error||l}catch{}let c=new Error(l);throw c.code=o.status,c}let a=null,s=null;if(this.config.stream)for await(let l of Ki(o.body)){if(l.data=="[DONE]")break;if(!l.data)continue;let c=JSON.parse(l.data);if(s){for(let u in c.choices[0].delta)if(typeof c.choices[0].delta[u]=="string"){if(u=="role"&&s[u]==c.choices[0].delta[u])continue;s[u]=(s[u]||"")+c.choices[0].delta[u]}for(let u of c.choices[0].delta.tool_calls||[]){if(s.tool_calls||(s.tool_calls=[]),!s.tool_calls[u.index]){s.tool_calls[u.index]=u;continue}let p=s.tool_calls[u.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(u.function?.name||""),p.function.arguments=(p.function.arguments||"")+(u.function?.arguments||"")}}else s={chunkID:c.id,...c.choices[0].delta};s?.content&&!s.content.startsWith("{")&&this.config.onAIMessage?.(s.content,!0)}else a=await o.json(),this.stats.tokensUsed+=a.usage?.total_tokens||0,Pe.debug(`Used ${a.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),s=a.choices?.[0]?.message;if(s||(Pe.warn("No response block in API response."),s={role:"assistant",content:""}),s.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(s),this.messages.push(s),s.content&&this.config.onAIMessage?.(s.content,!1)}processIncomingMessage(n){}registerTool(n){this.tools.push(n)}async processToolCall(n){try{let t=this.tools.find(o=>o.name==n.function.name);if(!t)throw new Error(`Tool "${n.function.name}" not found.`);let r=JSON.parse(n.function.arguments);this.config.onAIToolStart?.(n.function.name,r);let i=await t.callback(r);if(typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&t.removeFromMessageHistory){Pe.debug(`Removing tool call history for "${t.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(o=>o.role!="assistant"||!o.tool_calls?.find(a=>a.id==n.id));return}else t.removeFromMessageHistory&&Pe.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${t.name}"`);this.messages.push({role:"tool",content:i,tool_call_id:n.id})}catch(t){Pe.warn(`Unable to process tool call for "${n?.function?.name}"`,t),this.messages.push({role:"tool",content:`Error: ${t.message}`,tool_call_id:n.id})}}resetConversation(){this.messages=[]}};var J=function(){return J=Object.assign||function(n){for(var t,r=1,i=arguments.length;r<i;r++){t=arguments[r];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(n[o]=t[o])}return n},J.apply(this,arguments)};function qs(e,n,t,r){function i(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function s(u){try{c(r.next(u))}catch(p){a(p)}}function l(u){try{c(r.throw(u))}catch(p){a(p)}}function c(u){u.done?o(u.value):i(u.value).then(s,l)}c((r=r.apply(e,n||[])).next())})}function $s(e,n){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,c[0]&&(t=0)),t;)try{if(r=1,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,i=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){t.label=c[1];break}if(c[0]===6&&t.label<o[1]){t.label=o[1],o=c;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(c);break}o[2]&&t.ops.pop(),t.trys.pop();continue}c=n.call(e,t)}catch(u){c=[6,u],i=0}finally{r=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function X(e){var n=typeof Symbol=="function"&&Symbol.iterator,t=n&&e[n],r=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function $(e,n){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var r=t.call(e),i,o=[],a;try{for(;(n===void 0||n-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(s){a={error:s}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o}var el="ENTRIES",$i="KEYS",eo="VALUES",le="",mr=function(){function e(n,t){var r=n._tree,i=Array.from(r.keys());this.set=n,this._type=t,this._path=i.length>0?[{node:r,keys:i}]:[]}return e.prototype.next=function(){var n=this.dive();return this.backtrack(),n},e.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var n=at(this._path),t=n.node,r=n.keys;if(at(r)===le)return{done:!1,value:this.result()};var i=t.get(at(r));return this._path.push({node:i,keys:Array.from(i.keys())}),this.dive()},e.prototype.backtrack=function(){if(this._path.length!==0){var n=at(this._path).keys;n.pop(),!(n.length>0)&&(this._path.pop(),this.backtrack())}},e.prototype.key=function(){return this.set._prefix+this._path.map(function(n){var t=n.keys;return at(t)}).filter(function(n){return n!==le}).join("")},e.prototype.value=function(){return at(this._path).node.get(le)},e.prototype.result=function(){switch(this._type){case eo:return this.value();case $i:return this.key();default:return[this.key(),this.value()]}},e.prototype[Symbol.iterator]=function(){return this},e}(),at=function(e){return e[e.length-1]},tl=function(e,n,t){var r=new Map;if(n===void 0)return r;for(var i=n.length+1,o=i+t,a=new Uint8Array(o*i).fill(t+1),s=0;s<i;++s)a[s]=s;for(var l=1;l<o;++l)a[l*i]=l;return to(e,n,t,r,a,1,i,""),r},to=function(e,n,t,r,i,o,a,s){var l,c,u=o*a;try{e:for(var p=X(e.keys()),d=p.next();!d.done;d=p.next()){var h=d.value;if(h===le){var g=i[u-1];g<=t&&r.set(s,[e.get(h),g])}else{for(var w=o,k=0;k<h.length;++k,++w){for(var y=h[k],I=a*w,v=I-a,z=i[I],P=Math.max(0,w-t-1),x=Math.min(a-1,w+t),A=P;A<x;++A){var F=y!==n[A],R=i[v+A]+ +F,Z=i[v+A+1]+1,D=i[I+A]+1,M=i[I+A+1]=Math.min(R,Z,D);M<z&&(z=M)}if(z>t)continue e}to(e.get(h),n,t,r,i,w,a,s+h)}}}catch(C){l={error:C}}finally{try{d&&!d.done&&(c=p.return)&&c.call(p)}finally{if(l)throw l.error}}},gr=function(){function e(n,t){n===void 0&&(n=new Map),t===void 0&&(t=""),this._size=void 0,this._tree=n,this._prefix=t}return e.prototype.atPrefix=function(n){var t,r;if(!n.startsWith(this._prefix))throw new Error("Mismatched prefix");var i=$(en(this._tree,n.slice(this._prefix.length)),2),o=i[0],a=i[1];if(o===void 0){var s=$(Er(a),2),l=s[0],c=s[1];try{for(var u=X(l.keys()),p=u.next();!p.done;p=u.next()){var d=p.value;if(d!==le&&d.startsWith(c)){var h=new Map;return h.set(d.slice(c.length),l.get(d)),new e(h,n)}}}catch(g){t={error:g}}finally{try{p&&!p.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}}return new e(o,n)},e.prototype.clear=function(){this._size=void 0,this._tree.clear()},e.prototype.delete=function(n){return this._size=void 0,nl(this._tree,n)},e.prototype.entries=function(){return new mr(this,el)},e.prototype.forEach=function(n){var t,r;try{for(var i=X(this),o=i.next();!o.done;o=i.next()){var a=$(o.value,2),s=a[0],l=a[1];n(s,l,this)}}catch(c){t={error:c}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},e.prototype.fuzzyGet=function(n,t){return tl(this._tree,n,t)},e.prototype.get=function(n){var t=vr(this._tree,n);return t!==void 0?t.get(le):void 0},e.prototype.has=function(n){var t=vr(this._tree,n);return t!==void 0&&t.has(le)},e.prototype.keys=function(){return new mr(this,$i)},e.prototype.set=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n);return r.set(le,t),this},Object.defineProperty(e.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var n=this.entries();!n.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),e.prototype.update=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n);return r.set(le,t(r.get(le))),this},e.prototype.fetch=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n),i=r.get(le);return i===void 0&&r.set(le,i=t()),i},e.prototype.values=function(){return new mr(this,eo)},e.prototype[Symbol.iterator]=function(){return this.entries()},e.from=function(n){var t,r,i=new e;try{for(var o=X(n),a=o.next();!a.done;a=o.next()){var s=$(a.value,2),l=s[0],c=s[1];i.set(l,c)}}catch(u){t={error:u}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return i},e.fromObject=function(n){return e.from(Object.entries(n))},e}(),en=function(e,n,t){var r,i;if(t===void 0&&(t=[]),n.length===0||e==null)return[e,t];try{for(var o=X(e.keys()),a=o.next();!a.done;a=o.next()){var s=a.value;if(s!==le&&n.startsWith(s))return t.push([e,s]),en(e.get(s),n.slice(s.length),t)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}return t.push([e,n]),en(void 0,"",t)},vr=function(e,n){var t,r;if(n.length===0||e==null)return e;try{for(var i=X(e.keys()),o=i.next();!o.done;o=i.next()){var a=o.value;if(a!==le&&n.startsWith(a))return vr(e.get(a),n.slice(a.length))}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},yr=function(e,n){var t,r,i=n.length;e:for(var o=0;e&&o<i;){try{for(var a=(t=void 0,X(e.keys())),s=a.next();!s.done;s=a.next()){var l=s.value;if(l!==le&&n[o]===l[0]){for(var c=Math.min(i-o,l.length),u=1;u<c&&n[o+u]===l[u];)++u;var p=e.get(l);if(u===l.length)e=p;else{var d=new Map;d.set(l.slice(u),p),e.set(n.slice(o,o+u),d),e.delete(l),e=d}o+=u;continue e}}}catch(g){t={error:g}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}var h=new Map;return e.set(n.slice(o),h),h}return e},nl=function(e,n){var t=$(en(e,n),2),r=t[0],i=t[1];if(r!==void 0){if(r.delete(le),r.size===0)no(i);else if(r.size===1){var o=$(r.entries().next().value,2),a=o[0],s=o[1];ro(i,a,s)}}},no=function(e){if(e.length!==0){var n=$(Er(e),2),t=n[0],r=n[1];if(t.delete(r),t.size===0)no(e.slice(0,-1));else if(t.size===1){var i=$(t.entries().next().value,2),o=i[0],a=i[1];o!==le&&ro(e.slice(0,-1),o,a)}}},ro=function(e,n,t){if(e.length!==0){var r=$(Er(e),2),i=r[0],o=r[1];i.set(o+n,t),i.delete(o)}},Er=function(e){return e[e.length-1]},kt,Cr="or",io="and",rl="and_not",oo=function(){function e(n){if(n?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');var t=n.autoVacuum==null||n.autoVacuum===!0?wr:n.autoVacuum;this._options=J(J(J({},br),n),{autoVacuum:t,searchOptions:J(J({},ji),n.searchOptions||{}),autoSuggestOptions:J(J({},ll),n.autoSuggestOptions||{})}),this._index=new gr,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Sr,this.addFields(this._options.fields)}return e.prototype.add=function(n){var t,r,i,o,a,s,l=this._options,c=l.extractField,u=l.tokenize,p=l.processTerm,d=l.fields,h=l.idField,g=c(n,h);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(h,'"'));if(this._idToShortId.has(g))throw new Error("MiniSearch: duplicate ID ".concat(g));var w=this.addDocumentId(g);this.saveStoredFields(w,n);try{for(var k=X(d),y=k.next();!y.done;y=k.next()){var I=y.value,v=c(n,I);if(v!=null){var z=u(v.toString(),I),P=this._fieldIds[I],x=new Set(z).size;this.addFieldLength(w,P,this._documentCount-1,x);try{for(var A=(i=void 0,X(z)),F=A.next();!F.done;F=A.next()){var R=F.value,Z=p(R,I);if(Array.isArray(Z))try{for(var D=(a=void 0,X(Z)),M=D.next();!M.done;M=D.next()){var C=M.value;this.addTerm(P,w,C)}}catch(L){a={error:L}}finally{try{M&&!M.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else Z&&this.addTerm(P,w,Z)}}catch(L){i={error:L}}finally{try{F&&!F.done&&(o=A.return)&&o.call(A)}finally{if(i)throw i.error}}}}}catch(L){t={error:L}}finally{try{y&&!y.done&&(r=k.return)&&r.call(k)}finally{if(t)throw t.error}}},e.prototype.addAll=function(n){var t,r;try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;this.add(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},e.prototype.addAllAsync=function(n,t){var r=this;t===void 0&&(t={});var i=t.chunkSize,o=i===void 0?10:i,a={chunk:[],promise:Promise.resolve()},s=n.reduce(function(u,p,d){var h=u.chunk,g=u.promise;return h.push(p),(d+1)%o===0?{chunk:[],promise:g.then(function(){return new Promise(function(w){return setTimeout(w,0)})}).then(function(){return r.addAll(h)})}:{chunk:h,promise:g}},a),l=s.chunk,c=s.promise;return c.then(function(){return r.addAll(l)})},e.prototype.remove=function(n){var t,r,i,o,a,s,l=this._options,c=l.tokenize,u=l.processTerm,p=l.extractField,d=l.fields,h=l.idField,g=p(n,h);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(h,'"'));var w=this._idToShortId.get(g);if(w==null)throw new Error("MiniSearch: cannot remove document with ID ".concat(g,": it is not in the index"));try{for(var k=X(d),y=k.next();!y.done;y=k.next()){var I=y.value,v=p(n,I);if(v!=null){var z=c(v.toString(),I),P=this._fieldIds[I],x=new Set(z).size;this.removeFieldLength(w,P,this._documentCount,x);try{for(var A=(i=void 0,X(z)),F=A.next();!F.done;F=A.next()){var R=F.value,Z=u(R,I);if(Array.isArray(Z))try{for(var D=(a=void 0,X(Z)),M=D.next();!M.done;M=D.next()){var C=M.value;this.removeTerm(P,w,C)}}catch(L){a={error:L}}finally{try{M&&!M.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else Z&&this.removeTerm(P,w,Z)}}catch(L){i={error:L}}finally{try{F&&!F.done&&(o=A.return)&&o.call(A)}finally{if(i)throw i.error}}}}}catch(L){t={error:L}}finally{try{y&&!y.done&&(r=k.return)&&r.call(k)}finally{if(t)throw t.error}}this._storedFields.delete(w),this._documentIds.delete(w),this._idToShortId.delete(g),this._fieldLength.delete(w),this._documentCount-=1},e.prototype.removeAll=function(n){var t,r;if(n)try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;this.remove(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new gr,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},e.prototype.discard=function(n){var t=this,r=this._idToShortId.get(n);if(r==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(n,": it is not in the index"));this._idToShortId.delete(n),this._documentIds.delete(r),this._storedFields.delete(r),(this._fieldLength.get(r)||[]).forEach(function(i,o){t.removeFieldLength(r,o,t._documentCount,i)}),this._fieldLength.delete(r),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},e.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var n=this._options.autoVacuum,t=n.minDirtFactor,r=n.minDirtCount,i=n.batchSize,o=n.batchWait;this.conditionalVacuum({batchSize:i,batchWait:o},{minDirtCount:r,minDirtFactor:t})}},e.prototype.discardAll=function(n){var t,r,i=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var o=X(n),a=o.next();!a.done;a=o.next()){var s=a.value;this.discard(s)}}catch(l){t={error:l}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}}finally{this._options.autoVacuum=i}this.maybeAutoVacuum()},e.prototype.replace=function(n){var t=this._options,r=t.idField,i=t.extractField,o=i(n,r);this.discard(o),this.add(n)},e.prototype.vacuum=function(n){return n===void 0&&(n={}),this.conditionalVacuum(n)},e.prototype.conditionalVacuum=function(n,t){var r=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&t,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var i=r._enqueuedVacuumConditions;return r._enqueuedVacuumConditions=Sr,r.performVacuuming(n,i)}),this._enqueuedVacuum)):this.vacuumConditionsMet(t)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(n),this._currentVacuum)},e.prototype.performVacuuming=function(n,t){return qs(this,void 0,void 0,function(){var r,i,o,a,s,l,c,u,p,d,h,g,w,k,y,I,v,z,P,x,A,F,R,Z,D;return $s(this,function(M){switch(M.label){case 0:if(r=this._dirtCount,!this.vacuumConditionsMet(t))return[3,10];i=n.batchSize||kr.batchSize,o=n.batchWait||kr.batchWait,a=1,M.label=1;case 1:M.trys.push([1,7,8,9]),s=X(this._index),l=s.next(),M.label=2;case 2:if(l.done)return[3,6];c=$(l.value,2),u=c[0],p=c[1];try{for(d=(F=void 0,X(p)),h=d.next();!h.done;h=d.next()){g=$(h.value,2),w=g[0],k=g[1];try{for(y=(Z=void 0,X(k)),I=y.next();!I.done;I=y.next())v=$(I.value,1),z=v[0],!this._documentIds.has(z)&&(k.size<=1?p.delete(w):k.delete(z))}catch(C){Z={error:C}}finally{try{I&&!I.done&&(D=y.return)&&D.call(y)}finally{if(Z)throw Z.error}}}}catch(C){F={error:C}}finally{try{h&&!h.done&&(R=d.return)&&R.call(d)}finally{if(F)throw F.error}}return this._index.get(u).size===0&&this._index.delete(u),a%i!==0?[3,4]:[4,new Promise(function(C){return setTimeout(C,o)})];case 3:M.sent(),M.label=4;case 4:a+=1,M.label=5;case 5:return l=s.next(),[3,2];case 6:return[3,9];case 7:return P=M.sent(),x={error:P},[3,9];case 8:try{l&&!l.done&&(A=s.return)&&A.call(s)}finally{if(x)throw x.error}return[7];case 9:this._dirtCount-=r,M.label=10;case 10:return[4,null];case 11:return M.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},e.prototype.vacuumConditionsMet=function(n){if(n==null)return!0;var t=n.minDirtCount,r=n.minDirtFactor;return t=t||wr.minDirtCount,r=r||wr.minDirtFactor,this.dirtCount>=t&&this.dirtFactor>=r},Object.defineProperty(e.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),e.prototype.has=function(n){return this._idToShortId.has(n)},e.prototype.getStoredFields=function(n){var t=this._idToShortId.get(n);if(t!=null)return this._storedFields.get(t)},e.prototype.search=function(n,t){var r,i;t===void 0&&(t={});var o=this.executeQuery(n,t),a=[];try{for(var s=X(o),l=s.next();!l.done;l=s.next()){var c=$(l.value,2),u=c[0],p=c[1],d=p.score,h=p.terms,g=p.match,w=h.length||1,k={id:this._documentIds.get(u),score:d*w,terms:Object.keys(g),queryTerms:h,match:g};Object.assign(k,this._storedFields.get(u)),(t.filter==null||t.filter(k))&&a.push(k)}}catch(y){r={error:y}}finally{try{l&&!l.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return n===e.wildcard&&t.boostDocument==null&&this._options.searchOptions.boostDocument==null||a.sort(Qi),a},e.prototype.autoSuggest=function(n,t){var r,i,o,a;t===void 0&&(t={}),t=J(J({},this._options.autoSuggestOptions),t);var s=new Map;try{for(var l=X(this.search(n,t)),c=l.next();!c.done;c=l.next()){var u=c.value,p=u.score,d=u.terms,h=d.join(" "),g=s.get(h);g!=null?(g.score+=p,g.count+=1):s.set(h,{score:p,terms:d,count:1})}}catch(P){r={error:P}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(r)throw r.error}}var w=[];try{for(var k=X(s),y=k.next();!y.done;y=k.next()){var I=$(y.value,2),g=I[0],v=I[1],p=v.score,d=v.terms,z=v.count;w.push({suggestion:g,terms:d,score:p/z})}}catch(P){o={error:P}}finally{try{y&&!y.done&&(a=k.return)&&a.call(k)}finally{if(o)throw o.error}}return w.sort(Qi),w},Object.defineProperty(e.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),e.loadJSON=function(n,t){if(t==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(n),t)},e.getDefault=function(n){if(br.hasOwnProperty(n))return xr(br,n);throw new Error('MiniSearch: unknown option "'.concat(n,'"'))},e.loadJS=function(n,t){var r,i,o,a,s,l,c=n.index,u=n.documentCount,p=n.nextId,d=n.documentIds,h=n.fieldIds,g=n.fieldLength,w=n.averageFieldLength,k=n.storedFields,y=n.dirtCount,I=n.serializationVersion;if(I!==1&&I!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var v=new e(t);v._documentCount=u,v._nextId=p,v._documentIds=$t(d),v._idToShortId=new Map,v._fieldIds=h,v._fieldLength=$t(g),v._avgFieldLength=w,v._storedFields=$t(k),v._dirtCount=y||0,v._index=new gr;try{for(var z=X(v._documentIds),P=z.next();!P.done;P=z.next()){var x=$(P.value,2),A=x[0],F=x[1];v._idToShortId.set(F,A)}}catch(ne){r={error:ne}}finally{try{P&&!P.done&&(i=z.return)&&i.call(z)}finally{if(r)throw r.error}}try{for(var R=X(c),Z=R.next();!Z.done;Z=R.next()){var D=$(Z.value,2),M=D[0],C=D[1],L=new Map;try{for(var N=(s=void 0,X(Object.keys(C))),H=N.next();!H.done;H=N.next()){var Y=H.value,re=C[Y];I===1&&(re=re.ds),L.set(parseInt(Y,10),$t(re))}}catch(ne){s={error:ne}}finally{try{H&&!H.done&&(l=N.return)&&l.call(N)}finally{if(s)throw s.error}}v._index.set(M,L)}}catch(ne){o={error:ne}}finally{try{Z&&!Z.done&&(a=R.return)&&a.call(R)}finally{if(o)throw o.error}}return v},e.prototype.executeQuery=function(n,t){var r=this;if(t===void 0&&(t={}),n===e.wildcard)return this.executeWildcardQuery(t);if(typeof n!="string"){var i=J(J(J({},t),n),{queries:void 0}),o=n.queries.map(function(k){return r.executeQuery(k,i)});return this.combineResults(o,i.combineWith)}var a=this._options,s=a.tokenize,l=a.processTerm,c=a.searchOptions,u=J(J({tokenize:s,processTerm:l},c),t),p=u.tokenize,d=u.processTerm,h=p(n).flatMap(function(k){return d(k)}).filter(function(k){return!!k}),g=h.map(sl(u)),w=g.map(function(k){return r.executeQuerySpec(k,u)});return this.combineResults(w,u.combineWith)},e.prototype.executeQuerySpec=function(n,t){var r,i,o,a,s=J(J({},this._options.searchOptions),t),l=(s.fields||this._options.fields).reduce(function(Y,re){var ne;return J(J({},Y),(ne={},ne[re]=xr(s.boost,re)||1,ne))},{}),c=s.boostDocument,u=s.weights,p=s.maxFuzzy,d=s.bm25,h=J(J({},ji.weights),u),g=h.fuzzy,w=h.prefix,k=this._index.get(n.term),y=this.termResults(n.term,n.term,1,k,l,c,d),I,v;if(n.prefix&&(I=this._index.atPrefix(n.term)),n.fuzzy){var z=n.fuzzy===!0?.2:n.fuzzy,P=z<1?Math.min(p,Math.round(n.term.length*z)):z;P&&(v=this._index.fuzzyGet(n.term,P))}if(I)try{for(var x=X(I),A=x.next();!A.done;A=x.next()){var F=$(A.value,2),R=F[0],Z=F[1],D=R.length-n.term.length;if(D){v?.delete(R);var M=w*R.length/(R.length+.3*D);this.termResults(n.term,R,M,Z,l,c,d,y)}}}catch(Y){r={error:Y}}finally{try{A&&!A.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}if(v)try{for(var C=X(v.keys()),L=C.next();!L.done;L=C.next()){var R=L.value,N=$(v.get(R),2),H=N[0],D=N[1];if(D){var M=g*R.length/(R.length+D);this.termResults(n.term,R,M,H,l,c,d,y)}}}catch(Y){o={error:Y}}finally{try{L&&!L.done&&(a=C.return)&&a.call(C)}finally{if(o)throw o.error}}return y},e.prototype.executeWildcardQuery=function(n){var t,r,i=new Map,o=J(J({},this._options.searchOptions),n);try{for(var a=X(this._documentIds),s=a.next();!s.done;s=a.next()){var l=$(s.value,2),c=l[0],u=l[1],p=o.boostDocument?o.boostDocument(u,"",this._storedFields.get(c)):1;i.set(c,{score:p,terms:[],match:{}})}}catch(d){t={error:d}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return i},e.prototype.combineResults=function(n,t){if(t===void 0&&(t=Cr),n.length===0)return new Map;var r=t.toLowerCase();return n.reduce(il[r])||new Map},e.prototype.toJSON=function(){var n,t,r,i,o=[];try{for(var a=X(this._index),s=a.next();!s.done;s=a.next()){var l=$(s.value,2),c=l[0],u=l[1],p={};try{for(var d=(r=void 0,X(u)),h=d.next();!h.done;h=d.next()){var g=$(h.value,2),w=g[0],k=g[1];p[w]=Object.fromEntries(k)}}catch(y){r={error:y}}finally{try{h&&!h.done&&(i=d.return)&&i.call(d)}finally{if(r)throw r.error}}o.push([c,p])}}catch(y){n={error:y}}finally{try{s&&!s.done&&(t=a.return)&&t.call(a)}finally{if(n)throw n.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:o,serializationVersion:2}},e.prototype.termResults=function(n,t,r,i,o,a,s,l){var c,u,p,d,h;if(l===void 0&&(l=new Map),i==null)return l;try{for(var g=X(Object.keys(o)),w=g.next();!w.done;w=g.next()){var k=w.value,y=o[k],I=this._fieldIds[k],v=i.get(I);if(v!=null){var z=v.size,P=this._avgFieldLength[I];try{for(var x=(p=void 0,X(v.keys())),A=x.next();!A.done;A=x.next()){var F=A.value;if(!this._documentIds.has(F)){this.removeTerm(I,F,t),z-=1;continue}var R=a?a(this._documentIds.get(F),t,this._storedFields.get(F)):1;if(R){var Z=v.get(F),D=this._fieldLength.get(F)[I],M=al(Z,z,this._documentCount,D,P,s),C=r*y*R*M,L=l.get(F);if(L){L.score+=C,ul(L.terms,n);var N=xr(L.match,t);N?N.push(k):L.match[t]=[k]}else l.set(F,{score:C,terms:[n],match:(h={},h[t]=[k],h)})}}}catch(H){p={error:H}}finally{try{A&&!A.done&&(d=x.return)&&d.call(x)}finally{if(p)throw p.error}}}}}catch(H){c={error:H}}finally{try{w&&!w.done&&(u=g.return)&&u.call(g)}finally{if(c)throw c.error}}return l},e.prototype.addTerm=function(n,t,r){var i=this._index.fetch(r,qi),o=i.get(n);if(o==null)o=new Map,o.set(t,1),i.set(n,o);else{var a=o.get(t);o.set(t,(a||0)+1)}},e.prototype.removeTerm=function(n,t,r){if(!this._index.has(r)){this.warnDocumentChanged(t,n,r);return}var i=this._index.fetch(r,qi),o=i.get(n);o==null||o.get(t)==null?this.warnDocumentChanged(t,n,r):o.get(t)<=1?o.size<=1?i.delete(n):o.delete(t):o.set(t,o.get(t)-1),this._index.get(r).size===0&&this._index.delete(r)},e.prototype.warnDocumentChanged=function(n,t,r){var i,o;try{for(var a=X(Object.keys(this._fieldIds)),s=a.next();!s.done;s=a.next()){var l=s.value;if(this._fieldIds[l]===t){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(n),' has changed before removal: term "').concat(r,'" was not present in field "').concat(l,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(c){i={error:c}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(i)throw i.error}}},e.prototype.addDocumentId=function(n){var t=this._nextId;return this._idToShortId.set(n,t),this._documentIds.set(t,n),this._documentCount+=1,this._nextId+=1,t},e.prototype.addFields=function(n){for(var t=0;t<n.length;t++)this._fieldIds[n[t]]=t},e.prototype.addFieldLength=function(n,t,r,i){var o=this._fieldLength.get(n);o==null&&this._fieldLength.set(n,o=[]),o[t]=i;var a=this._avgFieldLength[t]||0,s=a*r+i;this._avgFieldLength[t]=s/(r+1)},e.prototype.removeFieldLength=function(n,t,r,i){if(r===1){this._avgFieldLength[t]=0;return}var o=this._avgFieldLength[t]*r-i;this._avgFieldLength[t]=o/(r-1)},e.prototype.saveStoredFields=function(n,t){var r,i,o=this._options,a=o.storeFields,s=o.extractField;if(!(a==null||a.length===0)){var l=this._storedFields.get(n);l==null&&this._storedFields.set(n,l={});try{for(var c=X(a),u=c.next();!u.done;u=c.next()){var p=u.value,d=s(t,p);d!==void 0&&(l[p]=d)}}catch(h){r={error:h}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(r)throw r.error}}}},e.wildcard=Symbol("*"),e}(),xr=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0},il=(kt={},kt[Cr]=function(e,n){var t,r;try{for(var i=X(n.keys()),o=i.next();!o.done;o=i.next()){var a=o.value,s=e.get(a);if(s==null)e.set(a,n.get(a));else{var l=n.get(a),c=l.score,u=l.terms,p=l.match;s.score=s.score+c,s.match=Object.assign(s.match,p),Ji(s.terms,u)}}}catch(d){t={error:d}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return e},kt[io]=function(e,n){var t,r,i=new Map;try{for(var o=X(n.keys()),a=o.next();!a.done;a=o.next()){var s=a.value,l=e.get(s);if(l!=null){var c=n.get(s),u=c.score,p=c.terms,d=c.match;Ji(l.terms,p),i.set(s,{score:l.score+u,terms:l.terms,match:Object.assign(l.match,d)})}}}catch(h){t={error:h}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return i},kt[rl]=function(e,n){var t,r;try{for(var i=X(n.keys()),o=i.next();!o.done;o=i.next()){var a=o.value;e.delete(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return e},kt),ol={k:1.2,b:.7,d:.5},al=function(e,n,t,r,i,o){var a=o.k,s=o.b,l=o.d,c=Math.log(1+(t-n+.5)/(n+.5));return c*(l+e*(a+1)/(e+a*(1-s+s*r/i)))},sl=function(e){return function(n,t,r){var i=typeof e.fuzzy=="function"?e.fuzzy(n,t,r):e.fuzzy||!1,o=typeof e.prefix=="function"?e.prefix(n,t,r):e.prefix===!0;return{term:n,fuzzy:i,prefix:o}}},br={idField:"id",extractField:function(e,n){return e[n]},tokenize:function(e){return e.split(cl)},processTerm:function(e){return e.toLowerCase()},fields:void 0,searchOptions:void 0,storeFields:[],logger:function(e,n){typeof console?.[e]=="function"&&console[e](n)},autoVacuum:!0},ji={combineWith:Cr,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:ol},ll={combineWith:io,prefix:function(e,n,t){return n===t.length-1}},kr={batchSize:1e3,batchWait:10},Sr={minDirtFactor:.1,minDirtCount:20},wr=J(J({},kr),Sr),ul=function(e,n){e.includes(n)||e.push(n)},Ji=function(e,n){var t,r;try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;e.includes(a)||e.push(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},Qi=function(e,n){var t=e.score,r=n.score;return r-t},qi=function(){return new Map},$t=function(e){var n,t,r=new Map;try{for(var i=X(Object.keys(e)),o=i.next();!o.done;o=i.next()){var a=o.value;r.set(parseInt(a,10),e[a])}}catch(s){n={error:s}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(n)throw n.error}}return r},cl=/[\n\r -#%-*,-/:;?@[-\]_{}\u00A0\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]+/u;var ao=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,n)=>{let t=await n.knowledgeBase.search(e.query),r=n;r._lastKBsearch=e.query,r._nextRequestUseKBitems=t,n.submitAnalyticsEvent({type:"kb-search",query:e.query,results:t});let i=t.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=t.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${o}.`}}];var Ke=new U("KnowledgeBase"),so=1,tn=class e{constructor(n){this._sources=[{id:"core.internal",query:async()=>ao}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=n}registerSource(n,t){let r=n;return typeof n=="function"&&(t=n,r=`source.${so++}`),this._sources.push({id:r,query:t}),r}removeSource(n){this._sources=this.sources.filter(t=>t.id!==n&&t.query!==n)}addEntry(n){this.manualEntries.push(n)}removeEntry(n){this.manualEntries=this.manualEntries.filter(t=>t.id!==n)}get sources(){let n=this._sources;return typeof window<"u"&&Q().knowledgeBaseSources&&(n=n.concat(Q().knowledgeBaseSources.map(t=>({id:t.name,query:t})))),n=n.concat(this._windowSources),n=n.filter(t=>!t.disabled),n}async search(n){Ke.debug(`Searching knowledge base for: ${n}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=n,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let i=(await Promise.all(this.sources.map(async l=>{try{let c=Date.now(),u=await l.query(n);return Ke.debug(`Source '${l.id}' took ${Date.now()-c}ms`),u||[]}catch(c){return Ke.warn(`Knowledge source '${l.id}' failed:`,c),[]}}))).flat();i=i.concat(t.entries),i=i.concat(this.manualEntries),Q().knowledgeBase&&(i=i.concat(Q().knowledgeBase)),i=i.filter(l=>l&&!l.disabled);for(let l=0;l<i.length;l++){let c=i[l];if(c.id=c.id||`temp.${l}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!c.action&&c.type=="tour"&&(c.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!c.action&&c.type=="info"&&(c.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),c.parameters&&!Array.isArray(c.parameters)){let u=c.parameters,p=[];for(let d in u)p.push({name:d,type:"string",description:c.parameters[d]});c.parameters=p}}let o=new oo({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let s=o.search(n).map(l=>i.find(c=>c.id==l.id));for(let l of i)l.isContext&&(s.find(c=>c.id===l.id)||s.push(l));return this.lastResults=s,Ke.debug("Found results:",s),s}getCachedEntry(n){return this.lastResults.find(t=>t.id==n||t._functionID==n)}registerSourceFromURL(n,t){t||(t=`external.${so++}`),Ke.debug(`Registering remote knowledge base source: ${n}`);let r=[],i=[],o=!0,a=async(l,c)=>{Ke.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:c},p=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw new Error(`HTTP Error ${p.status} ${p.statusText}`);let d=await p.json();return s(d.updateItems||[]),d.response},s=l=>{for(let c of l){if(!c.id){Ke.warn("KB item skipped since it has no ID.",c);continue}let u=r.find(p=>p.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}r.push({...c,action:p=>a(c,p)})}};this.registerSource(t,async l=>{if(o&&i.includes(l))return r;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:l},u=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return o=!p.noCache,i.includes(l)||i.push(l),s(p.items),r})}clone(){let n=new e(this.ai);return n._sources=this._sources,n._windowSources=this._windowSources,n.manualEntries=this.manualEntries,n}};var lo={name:"@intelliweave/embedded",version:"1.6.53",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var nn=class{constructor(n){this.ai=n}async boolean(n,t){let r=this.ai.clone();r.resetConversation(),r.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let i=await r.sendMessage(n+`
|
|
9
|
+
`,yield*t()}function Yi(){if(Q().userID)return Q().userID;if(typeof localStorage<"u"){let e=localStorage.getItem("intelliweave.uid")||"";return e||(e=Ue(),localStorage.setItem("intelliweave.uid",e),e)}else return Ue()}var Qt=class Qt{constructor(n){this.module="IntelliWeave";this.module=n}get debugEnabled(){return Qt.debug?!0:typeof window<"u"&&Q().debug}log(...n){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...n)}debug(...n){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...n)}info(...n){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...n)}warn(...n){console.warn(`[IntelliWeave > ${this.module}]`,...n)}error(...n){console.error(`[IntelliWeave > ${this.module}]`,...n)}timer(n,...t){let r=Date.now();return this.debug(`[${n} 0ms] Started`,...t),(...i)=>this.debug(`[${n} ${Math.floor(Date.now()-r)}ms]`,...i)}};Qt.debug=!1;var U=Qt;var Pe=new U("ChatGPT"),qt=class{constructor(n){this.id="";this.metadata={};this.config={apiKey:"",endpoint:"",model:"gpt-4-turbo",systemMessage:"",userID:"",stream:!0,maxTokens:4096};this.messages=[];this.tools=[];this.maxToolCallsPerMessage=10;this._hasRemovedToolCallHistorySinceLastMessage=0;this.stats={tokensUsed:0};this.config={...this.config,...n}}async sendMessage(n){this.messages.push({role:"user",content:n}),await this.processMessages(),this._hasRemovedToolCallHistorySinceLastMessage=0;let t=this.messages[this.messages.length-1];return t?.role=="assistant"&&t.content||""}async processMessages(){await this.config.onBeforeMessageProcessing?.(),Pe.debug("Process message state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let n=this.messages[this.messages.length-1];if(n?.role=="user"||n?.role=="tool")await this.trimMessages(),await this.sendToAPI(),await this.processMessages();else if(n?.role=="assistant"&&n?.tool_calls?.length){for(let t of n.tool_calls)await this.processToolCall(t);await this.processMessages()}}async trimMessages(){for(;;){let n=await this.sendToAPI(!0);if(JSON.stringify(n).length/3.8<this.config.maxTokens)break;if(this.messages.length<2){Pe.warn("[ChatGPT] Unable to trim messages, no messages left! Please check the size of the system message and the LLM's context window size.");break}for(this.messages=this.messages.slice(Math.floor(this.messages.length/2));this.messages.length&&this.messages[0].role=="tool";)this.messages.shift()}}async sendToAPI(n){let t=0;for(let l=this.messages.length-1;l>=0;l--)if(this.messages[l].role=="assistant"&&this.messages[l].tool_calls){if(t+=1,t>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(this.messages[l].role=="user")break;Pe.debug("Before LLM state:",{context:this.config.systemMessage,tools:this.tools.slice(),messages:this.messages.slice(),removedToolCallHistory:this._hasRemovedToolCallHistorySinceLastMessage});let r={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,max_tokens:1024,messages:[{role:"system",content:this.config.systemMessage},...this.messages]};for(let l of this.tools){l.description&&l.description.length>1024&&Pe.warn(`Tool description for "${l.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:l.name,description:(l.description||"").substring(0,1024),parameters:{type:"object",properties:{}}}};if(Array.isArray(l.params))for(let u of l.params)c.function.parameters.properties[u.name]={type:u.type,description:u.description};else if(l.params){let u=l.params;for(let p in u)c.function.parameters.properties[p]={type:"string",description:u[p]}}r.tools.push(c)}r.user||delete r.user,r.tools.length||delete r.tools;let i={};if(i["Content-Type"]="application/json",this.config.apiKey&&(i.Authorization=`Bearer ${this.config.apiKey}`),n)return r;let o=await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:i,body:JSON.stringify(r)});if(!o.ok){let l=`${o.status} ${o.statusText}`;try{let u=await o.json();l=u.errorText||u.error?.message||u.error||l}catch{}let c=new Error(l);throw c.code=o.status,c}let a=null,s=null;if(this.config.stream)for await(let l of Ki(o.body)){if(l.data=="[DONE]")break;if(!l.data)continue;let c=JSON.parse(l.data);if(s){for(let u in c.choices[0].delta)if(typeof c.choices[0].delta[u]=="string"){if(u=="role"&&s[u]==c.choices[0].delta[u])continue;s[u]=(s[u]||"")+c.choices[0].delta[u]}for(let u of c.choices[0].delta.tool_calls||[]){if(s.tool_calls||(s.tool_calls=[]),!s.tool_calls[u.index]){s.tool_calls[u.index]=u;continue}let p=s.tool_calls[u.index];p.function=p.function||{},p.function.name=(p.function.name||"")+(u.function?.name||""),p.function.arguments=(p.function.arguments||"")+(u.function?.arguments||"")}}else s={chunkID:c.id,...c.choices[0].delta};s?.content&&!s.content.startsWith("{")&&this.config.onAIMessage?.(s.content,!0)}else a=await o.json(),this.stats.tokensUsed+=a.usage?.total_tokens||0,Pe.debug(`Used ${a.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),s=a.choices?.[0]?.message;if(s||(Pe.warn("No response block in API response."),s={role:"assistant",content:""}),s.role=="user")throw new Error("API returned a user message, which is not allowed.");this.processIncomingMessage(s),this.messages.push(s),s.content&&this.config.onAIMessage?.(s.content,!1)}processIncomingMessage(n){}registerTool(n){this.tools.push(n)}async processToolCall(n){try{let t=this.tools.find(o=>o.name==n.function.name);if(!t)throw new Error(`Tool "${n.function.name}" not found.`);let r=JSON.parse(n.function.arguments);this.config.onAIToolStart?.(n.function.name,r);let i=await t.callback(r);if(typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),this._hasRemovedToolCallHistorySinceLastMessage<3&&t.removeFromMessageHistory){Pe.debug(`Removing tool call history for "${t.name}"`),this._hasRemovedToolCallHistorySinceLastMessage++,this.messages=this.messages.filter(o=>o.role!="assistant"||!o.tool_calls?.find(a=>a.id==n.id));return}else t.removeFromMessageHistory&&Pe.info(`The AI attempted to reuse a tool call that we removed from history. Skipping... "${t.name}"`);this.messages.push({role:"tool",content:i,tool_call_id:n.id})}catch(t){Pe.warn(`Unable to process tool call for "${n?.function?.name}"`,t),this.messages.push({role:"tool",content:`Error: ${t.message}`,tool_call_id:n.id})}}resetConversation(){this.messages=[]}};var J=function(){return J=Object.assign||function(n){for(var t,r=1,i=arguments.length;r<i;r++){t=arguments[r];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(n[o]=t[o])}return n},J.apply(this,arguments)};function qs(e,n,t,r){function i(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function s(u){try{c(r.next(u))}catch(p){a(p)}}function l(u){try{c(r.throw(u))}catch(p){a(p)}}function c(u){u.done?o(u.value):i(u.value).then(s,l)}c((r=r.apply(e,n||[])).next())})}function $s(e,n){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(c){return function(u){return l([c,u])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,c[0]&&(t=0)),t;)try{if(r=1,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,i=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){t.label=c[1];break}if(c[0]===6&&t.label<o[1]){t.label=o[1],o=c;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(c);break}o[2]&&t.ops.pop(),t.trys.pop();continue}c=n.call(e,t)}catch(u){c=[6,u],i=0}finally{r=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function X(e){var n=typeof Symbol=="function"&&Symbol.iterator,t=n&&e[n],r=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function $(e,n){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var r=t.call(e),i,o=[],a;try{for(;(n===void 0||n-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(s){a={error:s}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o}var el="ENTRIES",$i="KEYS",eo="VALUES",le="",mr=function(){function e(n,t){var r=n._tree,i=Array.from(r.keys());this.set=n,this._type=t,this._path=i.length>0?[{node:r,keys:i}]:[]}return e.prototype.next=function(){var n=this.dive();return this.backtrack(),n},e.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var n=at(this._path),t=n.node,r=n.keys;if(at(r)===le)return{done:!1,value:this.result()};var i=t.get(at(r));return this._path.push({node:i,keys:Array.from(i.keys())}),this.dive()},e.prototype.backtrack=function(){if(this._path.length!==0){var n=at(this._path).keys;n.pop(),!(n.length>0)&&(this._path.pop(),this.backtrack())}},e.prototype.key=function(){return this.set._prefix+this._path.map(function(n){var t=n.keys;return at(t)}).filter(function(n){return n!==le}).join("")},e.prototype.value=function(){return at(this._path).node.get(le)},e.prototype.result=function(){switch(this._type){case eo:return this.value();case $i:return this.key();default:return[this.key(),this.value()]}},e.prototype[Symbol.iterator]=function(){return this},e}(),at=function(e){return e[e.length-1]},tl=function(e,n,t){var r=new Map;if(n===void 0)return r;for(var i=n.length+1,o=i+t,a=new Uint8Array(o*i).fill(t+1),s=0;s<i;++s)a[s]=s;for(var l=1;l<o;++l)a[l*i]=l;return to(e,n,t,r,a,1,i,""),r},to=function(e,n,t,r,i,o,a,s){var l,c,u=o*a;try{e:for(var p=X(e.keys()),d=p.next();!d.done;d=p.next()){var h=d.value;if(h===le){var g=i[u-1];g<=t&&r.set(s,[e.get(h),g])}else{for(var w=o,k=0;k<h.length;++k,++w){for(var y=h[k],I=a*w,v=I-a,z=i[I],P=Math.max(0,w-t-1),x=Math.min(a-1,w+t),A=P;A<x;++A){var F=y!==n[A],R=i[v+A]+ +F,Z=i[v+A+1]+1,D=i[I+A]+1,M=i[I+A+1]=Math.min(R,Z,D);M<z&&(z=M)}if(z>t)continue e}to(e.get(h),n,t,r,i,w,a,s+h)}}}catch(C){l={error:C}}finally{try{d&&!d.done&&(c=p.return)&&c.call(p)}finally{if(l)throw l.error}}},gr=function(){function e(n,t){n===void 0&&(n=new Map),t===void 0&&(t=""),this._size=void 0,this._tree=n,this._prefix=t}return e.prototype.atPrefix=function(n){var t,r;if(!n.startsWith(this._prefix))throw new Error("Mismatched prefix");var i=$(en(this._tree,n.slice(this._prefix.length)),2),o=i[0],a=i[1];if(o===void 0){var s=$(Er(a),2),l=s[0],c=s[1];try{for(var u=X(l.keys()),p=u.next();!p.done;p=u.next()){var d=p.value;if(d!==le&&d.startsWith(c)){var h=new Map;return h.set(d.slice(c.length),l.get(d)),new e(h,n)}}}catch(g){t={error:g}}finally{try{p&&!p.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}}return new e(o,n)},e.prototype.clear=function(){this._size=void 0,this._tree.clear()},e.prototype.delete=function(n){return this._size=void 0,nl(this._tree,n)},e.prototype.entries=function(){return new mr(this,el)},e.prototype.forEach=function(n){var t,r;try{for(var i=X(this),o=i.next();!o.done;o=i.next()){var a=$(o.value,2),s=a[0],l=a[1];n(s,l,this)}}catch(c){t={error:c}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},e.prototype.fuzzyGet=function(n,t){return tl(this._tree,n,t)},e.prototype.get=function(n){var t=vr(this._tree,n);return t!==void 0?t.get(le):void 0},e.prototype.has=function(n){var t=vr(this._tree,n);return t!==void 0&&t.has(le)},e.prototype.keys=function(){return new mr(this,$i)},e.prototype.set=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n);return r.set(le,t),this},Object.defineProperty(e.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var n=this.entries();!n.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),e.prototype.update=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n);return r.set(le,t(r.get(le))),this},e.prototype.fetch=function(n,t){if(typeof n!="string")throw new Error("key must be a string");this._size=void 0;var r=yr(this._tree,n),i=r.get(le);return i===void 0&&r.set(le,i=t()),i},e.prototype.values=function(){return new mr(this,eo)},e.prototype[Symbol.iterator]=function(){return this.entries()},e.from=function(n){var t,r,i=new e;try{for(var o=X(n),a=o.next();!a.done;a=o.next()){var s=$(a.value,2),l=s[0],c=s[1];i.set(l,c)}}catch(u){t={error:u}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return i},e.fromObject=function(n){return e.from(Object.entries(n))},e}(),en=function(e,n,t){var r,i;if(t===void 0&&(t=[]),n.length===0||e==null)return[e,t];try{for(var o=X(e.keys()),a=o.next();!a.done;a=o.next()){var s=a.value;if(s!==le&&n.startsWith(s))return t.push([e,s]),en(e.get(s),n.slice(s.length),t)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}return t.push([e,n]),en(void 0,"",t)},vr=function(e,n){var t,r;if(n.length===0||e==null)return e;try{for(var i=X(e.keys()),o=i.next();!o.done;o=i.next()){var a=o.value;if(a!==le&&n.startsWith(a))return vr(e.get(a),n.slice(a.length))}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},yr=function(e,n){var t,r,i=n.length;e:for(var o=0;e&&o<i;){try{for(var a=(t=void 0,X(e.keys())),s=a.next();!s.done;s=a.next()){var l=s.value;if(l!==le&&n[o]===l[0]){for(var c=Math.min(i-o,l.length),u=1;u<c&&n[o+u]===l[u];)++u;var p=e.get(l);if(u===l.length)e=p;else{var d=new Map;d.set(l.slice(u),p),e.set(n.slice(o,o+u),d),e.delete(l),e=d}o+=u;continue e}}}catch(g){t={error:g}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}var h=new Map;return e.set(n.slice(o),h),h}return e},nl=function(e,n){var t=$(en(e,n),2),r=t[0],i=t[1];if(r!==void 0){if(r.delete(le),r.size===0)no(i);else if(r.size===1){var o=$(r.entries().next().value,2),a=o[0],s=o[1];ro(i,a,s)}}},no=function(e){if(e.length!==0){var n=$(Er(e),2),t=n[0],r=n[1];if(t.delete(r),t.size===0)no(e.slice(0,-1));else if(t.size===1){var i=$(t.entries().next().value,2),o=i[0],a=i[1];o!==le&&ro(e.slice(0,-1),o,a)}}},ro=function(e,n,t){if(e.length!==0){var r=$(Er(e),2),i=r[0],o=r[1];i.set(o+n,t),i.delete(o)}},Er=function(e){return e[e.length-1]},kt,Cr="or",io="and",rl="and_not",oo=function(){function e(n){if(n?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');var t=n.autoVacuum==null||n.autoVacuum===!0?wr:n.autoVacuum;this._options=J(J(J({},br),n),{autoVacuum:t,searchOptions:J(J({},ji),n.searchOptions||{}),autoSuggestOptions:J(J({},ll),n.autoSuggestOptions||{})}),this._index=new gr,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Sr,this.addFields(this._options.fields)}return e.prototype.add=function(n){var t,r,i,o,a,s,l=this._options,c=l.extractField,u=l.tokenize,p=l.processTerm,d=l.fields,h=l.idField,g=c(n,h);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(h,'"'));if(this._idToShortId.has(g))throw new Error("MiniSearch: duplicate ID ".concat(g));var w=this.addDocumentId(g);this.saveStoredFields(w,n);try{for(var k=X(d),y=k.next();!y.done;y=k.next()){var I=y.value,v=c(n,I);if(v!=null){var z=u(v.toString(),I),P=this._fieldIds[I],x=new Set(z).size;this.addFieldLength(w,P,this._documentCount-1,x);try{for(var A=(i=void 0,X(z)),F=A.next();!F.done;F=A.next()){var R=F.value,Z=p(R,I);if(Array.isArray(Z))try{for(var D=(a=void 0,X(Z)),M=D.next();!M.done;M=D.next()){var C=M.value;this.addTerm(P,w,C)}}catch(L){a={error:L}}finally{try{M&&!M.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else Z&&this.addTerm(P,w,Z)}}catch(L){i={error:L}}finally{try{F&&!F.done&&(o=A.return)&&o.call(A)}finally{if(i)throw i.error}}}}}catch(L){t={error:L}}finally{try{y&&!y.done&&(r=k.return)&&r.call(k)}finally{if(t)throw t.error}}},e.prototype.addAll=function(n){var t,r;try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;this.add(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},e.prototype.addAllAsync=function(n,t){var r=this;t===void 0&&(t={});var i=t.chunkSize,o=i===void 0?10:i,a={chunk:[],promise:Promise.resolve()},s=n.reduce(function(u,p,d){var h=u.chunk,g=u.promise;return h.push(p),(d+1)%o===0?{chunk:[],promise:g.then(function(){return new Promise(function(w){return setTimeout(w,0)})}).then(function(){return r.addAll(h)})}:{chunk:h,promise:g}},a),l=s.chunk,c=s.promise;return c.then(function(){return r.addAll(l)})},e.prototype.remove=function(n){var t,r,i,o,a,s,l=this._options,c=l.tokenize,u=l.processTerm,p=l.extractField,d=l.fields,h=l.idField,g=p(n,h);if(g==null)throw new Error('MiniSearch: document does not have ID field "'.concat(h,'"'));var w=this._idToShortId.get(g);if(w==null)throw new Error("MiniSearch: cannot remove document with ID ".concat(g,": it is not in the index"));try{for(var k=X(d),y=k.next();!y.done;y=k.next()){var I=y.value,v=p(n,I);if(v!=null){var z=c(v.toString(),I),P=this._fieldIds[I],x=new Set(z).size;this.removeFieldLength(w,P,this._documentCount,x);try{for(var A=(i=void 0,X(z)),F=A.next();!F.done;F=A.next()){var R=F.value,Z=u(R,I);if(Array.isArray(Z))try{for(var D=(a=void 0,X(Z)),M=D.next();!M.done;M=D.next()){var C=M.value;this.removeTerm(P,w,C)}}catch(L){a={error:L}}finally{try{M&&!M.done&&(s=D.return)&&s.call(D)}finally{if(a)throw a.error}}else Z&&this.removeTerm(P,w,Z)}}catch(L){i={error:L}}finally{try{F&&!F.done&&(o=A.return)&&o.call(A)}finally{if(i)throw i.error}}}}}catch(L){t={error:L}}finally{try{y&&!y.done&&(r=k.return)&&r.call(k)}finally{if(t)throw t.error}}this._storedFields.delete(w),this._documentIds.delete(w),this._idToShortId.delete(g),this._fieldLength.delete(w),this._documentCount-=1},e.prototype.removeAll=function(n){var t,r;if(n)try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;this.remove(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new gr,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},e.prototype.discard=function(n){var t=this,r=this._idToShortId.get(n);if(r==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(n,": it is not in the index"));this._idToShortId.delete(n),this._documentIds.delete(r),this._storedFields.delete(r),(this._fieldLength.get(r)||[]).forEach(function(i,o){t.removeFieldLength(r,o,t._documentCount,i)}),this._fieldLength.delete(r),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},e.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var n=this._options.autoVacuum,t=n.minDirtFactor,r=n.minDirtCount,i=n.batchSize,o=n.batchWait;this.conditionalVacuum({batchSize:i,batchWait:o},{minDirtCount:r,minDirtFactor:t})}},e.prototype.discardAll=function(n){var t,r,i=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var o=X(n),a=o.next();!a.done;a=o.next()){var s=a.value;this.discard(s)}}catch(l){t={error:l}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}}finally{this._options.autoVacuum=i}this.maybeAutoVacuum()},e.prototype.replace=function(n){var t=this._options,r=t.idField,i=t.extractField,o=i(n,r);this.discard(o),this.add(n)},e.prototype.vacuum=function(n){return n===void 0&&(n={}),this.conditionalVacuum(n)},e.prototype.conditionalVacuum=function(n,t){var r=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&t,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var i=r._enqueuedVacuumConditions;return r._enqueuedVacuumConditions=Sr,r.performVacuuming(n,i)}),this._enqueuedVacuum)):this.vacuumConditionsMet(t)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(n),this._currentVacuum)},e.prototype.performVacuuming=function(n,t){return qs(this,void 0,void 0,function(){var r,i,o,a,s,l,c,u,p,d,h,g,w,k,y,I,v,z,P,x,A,F,R,Z,D;return $s(this,function(M){switch(M.label){case 0:if(r=this._dirtCount,!this.vacuumConditionsMet(t))return[3,10];i=n.batchSize||kr.batchSize,o=n.batchWait||kr.batchWait,a=1,M.label=1;case 1:M.trys.push([1,7,8,9]),s=X(this._index),l=s.next(),M.label=2;case 2:if(l.done)return[3,6];c=$(l.value,2),u=c[0],p=c[1];try{for(d=(F=void 0,X(p)),h=d.next();!h.done;h=d.next()){g=$(h.value,2),w=g[0],k=g[1];try{for(y=(Z=void 0,X(k)),I=y.next();!I.done;I=y.next())v=$(I.value,1),z=v[0],!this._documentIds.has(z)&&(k.size<=1?p.delete(w):k.delete(z))}catch(C){Z={error:C}}finally{try{I&&!I.done&&(D=y.return)&&D.call(y)}finally{if(Z)throw Z.error}}}}catch(C){F={error:C}}finally{try{h&&!h.done&&(R=d.return)&&R.call(d)}finally{if(F)throw F.error}}return this._index.get(u).size===0&&this._index.delete(u),a%i!==0?[3,4]:[4,new Promise(function(C){return setTimeout(C,o)})];case 3:M.sent(),M.label=4;case 4:a+=1,M.label=5;case 5:return l=s.next(),[3,2];case 6:return[3,9];case 7:return P=M.sent(),x={error:P},[3,9];case 8:try{l&&!l.done&&(A=s.return)&&A.call(s)}finally{if(x)throw x.error}return[7];case 9:this._dirtCount-=r,M.label=10;case 10:return[4,null];case 11:return M.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},e.prototype.vacuumConditionsMet=function(n){if(n==null)return!0;var t=n.minDirtCount,r=n.minDirtFactor;return t=t||wr.minDirtCount,r=r||wr.minDirtFactor,this.dirtCount>=t&&this.dirtFactor>=r},Object.defineProperty(e.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),e.prototype.has=function(n){return this._idToShortId.has(n)},e.prototype.getStoredFields=function(n){var t=this._idToShortId.get(n);if(t!=null)return this._storedFields.get(t)},e.prototype.search=function(n,t){var r,i;t===void 0&&(t={});var o=this.executeQuery(n,t),a=[];try{for(var s=X(o),l=s.next();!l.done;l=s.next()){var c=$(l.value,2),u=c[0],p=c[1],d=p.score,h=p.terms,g=p.match,w=h.length||1,k={id:this._documentIds.get(u),score:d*w,terms:Object.keys(g),queryTerms:h,match:g};Object.assign(k,this._storedFields.get(u)),(t.filter==null||t.filter(k))&&a.push(k)}}catch(y){r={error:y}}finally{try{l&&!l.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return n===e.wildcard&&t.boostDocument==null&&this._options.searchOptions.boostDocument==null||a.sort(Qi),a},e.prototype.autoSuggest=function(n,t){var r,i,o,a;t===void 0&&(t={}),t=J(J({},this._options.autoSuggestOptions),t);var s=new Map;try{for(var l=X(this.search(n,t)),c=l.next();!c.done;c=l.next()){var u=c.value,p=u.score,d=u.terms,h=d.join(" "),g=s.get(h);g!=null?(g.score+=p,g.count+=1):s.set(h,{score:p,terms:d,count:1})}}catch(P){r={error:P}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(r)throw r.error}}var w=[];try{for(var k=X(s),y=k.next();!y.done;y=k.next()){var I=$(y.value,2),g=I[0],v=I[1],p=v.score,d=v.terms,z=v.count;w.push({suggestion:g,terms:d,score:p/z})}}catch(P){o={error:P}}finally{try{y&&!y.done&&(a=k.return)&&a.call(k)}finally{if(o)throw o.error}}return w.sort(Qi),w},Object.defineProperty(e.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),e.loadJSON=function(n,t){if(t==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(n),t)},e.getDefault=function(n){if(br.hasOwnProperty(n))return xr(br,n);throw new Error('MiniSearch: unknown option "'.concat(n,'"'))},e.loadJS=function(n,t){var r,i,o,a,s,l,c=n.index,u=n.documentCount,p=n.nextId,d=n.documentIds,h=n.fieldIds,g=n.fieldLength,w=n.averageFieldLength,k=n.storedFields,y=n.dirtCount,I=n.serializationVersion;if(I!==1&&I!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var v=new e(t);v._documentCount=u,v._nextId=p,v._documentIds=$t(d),v._idToShortId=new Map,v._fieldIds=h,v._fieldLength=$t(g),v._avgFieldLength=w,v._storedFields=$t(k),v._dirtCount=y||0,v._index=new gr;try{for(var z=X(v._documentIds),P=z.next();!P.done;P=z.next()){var x=$(P.value,2),A=x[0],F=x[1];v._idToShortId.set(F,A)}}catch(ne){r={error:ne}}finally{try{P&&!P.done&&(i=z.return)&&i.call(z)}finally{if(r)throw r.error}}try{for(var R=X(c),Z=R.next();!Z.done;Z=R.next()){var D=$(Z.value,2),M=D[0],C=D[1],L=new Map;try{for(var N=(s=void 0,X(Object.keys(C))),H=N.next();!H.done;H=N.next()){var Y=H.value,re=C[Y];I===1&&(re=re.ds),L.set(parseInt(Y,10),$t(re))}}catch(ne){s={error:ne}}finally{try{H&&!H.done&&(l=N.return)&&l.call(N)}finally{if(s)throw s.error}}v._index.set(M,L)}}catch(ne){o={error:ne}}finally{try{Z&&!Z.done&&(a=R.return)&&a.call(R)}finally{if(o)throw o.error}}return v},e.prototype.executeQuery=function(n,t){var r=this;if(t===void 0&&(t={}),n===e.wildcard)return this.executeWildcardQuery(t);if(typeof n!="string"){var i=J(J(J({},t),n),{queries:void 0}),o=n.queries.map(function(k){return r.executeQuery(k,i)});return this.combineResults(o,i.combineWith)}var a=this._options,s=a.tokenize,l=a.processTerm,c=a.searchOptions,u=J(J({tokenize:s,processTerm:l},c),t),p=u.tokenize,d=u.processTerm,h=p(n).flatMap(function(k){return d(k)}).filter(function(k){return!!k}),g=h.map(sl(u)),w=g.map(function(k){return r.executeQuerySpec(k,u)});return this.combineResults(w,u.combineWith)},e.prototype.executeQuerySpec=function(n,t){var r,i,o,a,s=J(J({},this._options.searchOptions),t),l=(s.fields||this._options.fields).reduce(function(Y,re){var ne;return J(J({},Y),(ne={},ne[re]=xr(s.boost,re)||1,ne))},{}),c=s.boostDocument,u=s.weights,p=s.maxFuzzy,d=s.bm25,h=J(J({},ji.weights),u),g=h.fuzzy,w=h.prefix,k=this._index.get(n.term),y=this.termResults(n.term,n.term,1,k,l,c,d),I,v;if(n.prefix&&(I=this._index.atPrefix(n.term)),n.fuzzy){var z=n.fuzzy===!0?.2:n.fuzzy,P=z<1?Math.min(p,Math.round(n.term.length*z)):z;P&&(v=this._index.fuzzyGet(n.term,P))}if(I)try{for(var x=X(I),A=x.next();!A.done;A=x.next()){var F=$(A.value,2),R=F[0],Z=F[1],D=R.length-n.term.length;if(D){v?.delete(R);var M=w*R.length/(R.length+.3*D);this.termResults(n.term,R,M,Z,l,c,d,y)}}}catch(Y){r={error:Y}}finally{try{A&&!A.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}if(v)try{for(var C=X(v.keys()),L=C.next();!L.done;L=C.next()){var R=L.value,N=$(v.get(R),2),H=N[0],D=N[1];if(D){var M=g*R.length/(R.length+D);this.termResults(n.term,R,M,H,l,c,d,y)}}}catch(Y){o={error:Y}}finally{try{L&&!L.done&&(a=C.return)&&a.call(C)}finally{if(o)throw o.error}}return y},e.prototype.executeWildcardQuery=function(n){var t,r,i=new Map,o=J(J({},this._options.searchOptions),n);try{for(var a=X(this._documentIds),s=a.next();!s.done;s=a.next()){var l=$(s.value,2),c=l[0],u=l[1],p=o.boostDocument?o.boostDocument(u,"",this._storedFields.get(c)):1;i.set(c,{score:p,terms:[],match:{}})}}catch(d){t={error:d}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return i},e.prototype.combineResults=function(n,t){if(t===void 0&&(t=Cr),n.length===0)return new Map;var r=t.toLowerCase();return n.reduce(il[r])||new Map},e.prototype.toJSON=function(){var n,t,r,i,o=[];try{for(var a=X(this._index),s=a.next();!s.done;s=a.next()){var l=$(s.value,2),c=l[0],u=l[1],p={};try{for(var d=(r=void 0,X(u)),h=d.next();!h.done;h=d.next()){var g=$(h.value,2),w=g[0],k=g[1];p[w]=Object.fromEntries(k)}}catch(y){r={error:y}}finally{try{h&&!h.done&&(i=d.return)&&i.call(d)}finally{if(r)throw r.error}}o.push([c,p])}}catch(y){n={error:y}}finally{try{s&&!s.done&&(t=a.return)&&t.call(a)}finally{if(n)throw n.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:o,serializationVersion:2}},e.prototype.termResults=function(n,t,r,i,o,a,s,l){var c,u,p,d,h;if(l===void 0&&(l=new Map),i==null)return l;try{for(var g=X(Object.keys(o)),w=g.next();!w.done;w=g.next()){var k=w.value,y=o[k],I=this._fieldIds[k],v=i.get(I);if(v!=null){var z=v.size,P=this._avgFieldLength[I];try{for(var x=(p=void 0,X(v.keys())),A=x.next();!A.done;A=x.next()){var F=A.value;if(!this._documentIds.has(F)){this.removeTerm(I,F,t),z-=1;continue}var R=a?a(this._documentIds.get(F),t,this._storedFields.get(F)):1;if(R){var Z=v.get(F),D=this._fieldLength.get(F)[I],M=al(Z,z,this._documentCount,D,P,s),C=r*y*R*M,L=l.get(F);if(L){L.score+=C,ul(L.terms,n);var N=xr(L.match,t);N?N.push(k):L.match[t]=[k]}else l.set(F,{score:C,terms:[n],match:(h={},h[t]=[k],h)})}}}catch(H){p={error:H}}finally{try{A&&!A.done&&(d=x.return)&&d.call(x)}finally{if(p)throw p.error}}}}}catch(H){c={error:H}}finally{try{w&&!w.done&&(u=g.return)&&u.call(g)}finally{if(c)throw c.error}}return l},e.prototype.addTerm=function(n,t,r){var i=this._index.fetch(r,qi),o=i.get(n);if(o==null)o=new Map,o.set(t,1),i.set(n,o);else{var a=o.get(t);o.set(t,(a||0)+1)}},e.prototype.removeTerm=function(n,t,r){if(!this._index.has(r)){this.warnDocumentChanged(t,n,r);return}var i=this._index.fetch(r,qi),o=i.get(n);o==null||o.get(t)==null?this.warnDocumentChanged(t,n,r):o.get(t)<=1?o.size<=1?i.delete(n):o.delete(t):o.set(t,o.get(t)-1),this._index.get(r).size===0&&this._index.delete(r)},e.prototype.warnDocumentChanged=function(n,t,r){var i,o;try{for(var a=X(Object.keys(this._fieldIds)),s=a.next();!s.done;s=a.next()){var l=s.value;if(this._fieldIds[l]===t){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(n),' has changed before removal: term "').concat(r,'" was not present in field "').concat(l,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(c){i={error:c}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(i)throw i.error}}},e.prototype.addDocumentId=function(n){var t=this._nextId;return this._idToShortId.set(n,t),this._documentIds.set(t,n),this._documentCount+=1,this._nextId+=1,t},e.prototype.addFields=function(n){for(var t=0;t<n.length;t++)this._fieldIds[n[t]]=t},e.prototype.addFieldLength=function(n,t,r,i){var o=this._fieldLength.get(n);o==null&&this._fieldLength.set(n,o=[]),o[t]=i;var a=this._avgFieldLength[t]||0,s=a*r+i;this._avgFieldLength[t]=s/(r+1)},e.prototype.removeFieldLength=function(n,t,r,i){if(r===1){this._avgFieldLength[t]=0;return}var o=this._avgFieldLength[t]*r-i;this._avgFieldLength[t]=o/(r-1)},e.prototype.saveStoredFields=function(n,t){var r,i,o=this._options,a=o.storeFields,s=o.extractField;if(!(a==null||a.length===0)){var l=this._storedFields.get(n);l==null&&this._storedFields.set(n,l={});try{for(var c=X(a),u=c.next();!u.done;u=c.next()){var p=u.value,d=s(t,p);d!==void 0&&(l[p]=d)}}catch(h){r={error:h}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(r)throw r.error}}}},e.wildcard=Symbol("*"),e}(),xr=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0},il=(kt={},kt[Cr]=function(e,n){var t,r;try{for(var i=X(n.keys()),o=i.next();!o.done;o=i.next()){var a=o.value,s=e.get(a);if(s==null)e.set(a,n.get(a));else{var l=n.get(a),c=l.score,u=l.terms,p=l.match;s.score=s.score+c,s.match=Object.assign(s.match,p),Ji(s.terms,u)}}}catch(d){t={error:d}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return e},kt[io]=function(e,n){var t,r,i=new Map;try{for(var o=X(n.keys()),a=o.next();!a.done;a=o.next()){var s=a.value,l=e.get(s);if(l!=null){var c=n.get(s),u=c.score,p=c.terms,d=c.match;Ji(l.terms,p),i.set(s,{score:l.score+u,terms:l.terms,match:Object.assign(l.match,d)})}}}catch(h){t={error:h}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return i},kt[rl]=function(e,n){var t,r;try{for(var i=X(n.keys()),o=i.next();!o.done;o=i.next()){var a=o.value;e.delete(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return e},kt),ol={k:1.2,b:.7,d:.5},al=function(e,n,t,r,i,o){var a=o.k,s=o.b,l=o.d,c=Math.log(1+(t-n+.5)/(n+.5));return c*(l+e*(a+1)/(e+a*(1-s+s*r/i)))},sl=function(e){return function(n,t,r){var i=typeof e.fuzzy=="function"?e.fuzzy(n,t,r):e.fuzzy||!1,o=typeof e.prefix=="function"?e.prefix(n,t,r):e.prefix===!0;return{term:n,fuzzy:i,prefix:o}}},br={idField:"id",extractField:function(e,n){return e[n]},tokenize:function(e){return e.split(cl)},processTerm:function(e){return e.toLowerCase()},fields:void 0,searchOptions:void 0,storeFields:[],logger:function(e,n){typeof console?.[e]=="function"&&console[e](n)},autoVacuum:!0},ji={combineWith:Cr,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:ol},ll={combineWith:io,prefix:function(e,n,t){return n===t.length-1}},kr={batchSize:1e3,batchWait:10},Sr={minDirtFactor:.1,minDirtCount:20},wr=J(J({},kr),Sr),ul=function(e,n){e.includes(n)||e.push(n)},Ji=function(e,n){var t,r;try{for(var i=X(n),o=i.next();!o.done;o=i.next()){var a=o.value;e.includes(a)||e.push(a)}}catch(s){t={error:s}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},Qi=function(e,n){var t=e.score,r=n.score;return r-t},qi=function(){return new Map},$t=function(e){var n,t,r=new Map;try{for(var i=X(Object.keys(e)),o=i.next();!o.done;o=i.next()){var a=o.value;r.set(parseInt(a,10),e[a])}}catch(s){n={error:s}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(n)throw n.error}}return r},cl=/[\n\r -#%-*,-/:;?@[-\]_{}\u00A0\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]+/u;var ao=[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,n)=>{let t=await n.knowledgeBase.search(e.query),r=n;r._lastKBsearch=e.query,r._nextRequestUseKBitems=t,n.submitAnalyticsEvent({type:"kb-search",query:e.query,results:t});let i=t.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=t.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${i}. New tools available: ${o}.`}}];var Ke=new U("KnowledgeBase"),so=1,tn=class e{constructor(n){this._sources=[{id:"core.internal",query:async()=>ao}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=n}registerSource(n,t){let r=n;return typeof n=="function"&&(t=n,r=`source.${so++}`),this._sources.push({id:r,query:t}),r}removeSource(n){this._sources=this.sources.filter(t=>t.id!==n&&t.query!==n)}addEntry(n){this.manualEntries.push(n)}removeEntry(n){this.manualEntries=this.manualEntries.filter(t=>t.id!==n)}get sources(){let n=this._sources;return typeof window<"u"&&Q().knowledgeBaseSources&&(n=n.concat(Q().knowledgeBaseSources.map(t=>({id:t.name,query:t})))),n=n.concat(this._windowSources),n=n.filter(t=>!t.disabled),n}async search(n){Ke.debug(`Searching knowledge base for: ${n}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=n,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let i=(await Promise.all(this.sources.map(async l=>{try{let c=Date.now(),u=await l.query(n);return Ke.debug(`Source '${l.id}' took ${Date.now()-c}ms`),u||[]}catch(c){return Ke.warn(`Knowledge source '${l.id}' failed:`,c),[]}}))).flat();i=i.concat(t.entries),i=i.concat(this.manualEntries),Q().knowledgeBase&&(i=i.concat(Q().knowledgeBase)),i=i.filter(l=>l&&!l.disabled);for(let l=0;l<i.length;l++){let c=i[l];if(c.id=c.id||`temp.${l}`,c._functionID=c.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!c.action&&c.type=="tour"&&(c.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!c.action&&c.type=="info"&&(c.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")}),c.parameters&&!Array.isArray(c.parameters)){let u=c.parameters,p=[];for(let d in u)p.push({name:d,type:"string",description:c.parameters[d]});c.parameters=p}}let o=new oo({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(i);let s=o.search(n).map(l=>i.find(c=>c.id==l.id));for(let l of i)l.isContext&&(s.find(c=>c.id===l.id)||s.push(l));return this.lastResults=s,Ke.debug("Found results:",s),s}getCachedEntry(n){return this.lastResults.find(t=>t.id==n||t._functionID==n)}registerSourceFromURL(n,t){t||(t=`external.${so++}`),Ke.debug(`Registering remote knowledge base source: ${n}`);let r=[],i=[],o=!0,a=async(l,c)=>{Ke.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,extra:this.ai.extra,actionID:l.id,parameters:c},p=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)throw new Error(`HTTP Error ${p.status} ${p.statusText}`);let d=await p.json();return s(d.updateItems||[]),d.response},s=l=>{for(let c of l){if(!c.id){Ke.warn("KB item skipped since it has no ID.",c);continue}let u=r.find(p=>p.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}r.push({...c,action:p=>a(c,p)})}};this.registerSource(t,async l=>{if(o&&i.includes(l))return r;let c={type:"search",userID:this.ai?.userID||"",extra:this.ai?.extra||{},query:l},u=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return o=!p.noCache,i.includes(l)||i.push(l),s(p.items),r})}clone(){let n=new e(this.ai);return n._sources=this._sources,n._windowSources=this._windowSources,n.manualEntries=this.manualEntries,n}};var lo={name:"@intelliweave/embedded",version:"1.6.55",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4",uuid:"^10.0.0"}};var nn=class{constructor(n){this.ai=n}async boolean(n,t){let r=this.ai.clone();r.resetConversation(),r.getContextPrefix=async()=>'You will receive a question and some data. Answer the question by replying only with the word "true" or "false".';let i=await r.sendMessage(n+`
|
|
10
10
|
|
|
11
11
|
`+JSON.stringify(t))||"";if(i.toLowerCase().includes("true"))return!0;if(i.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+i)}async choose(n,t,r){r=r.map(a=>a.trim());let i=this.ai.clone();i.resetConversation(),i.getContextPrefix=async()=>"You will receive a question and some data and options. Answer the question by replying with the option you want to choose. Only say the option you want, no additional text.";let o=await i.sendMessage("question:"+n+`
|
|
12
12
|
|
|
@@ -17,11 +17,11 @@ options:`+r.join(`
|
|
|
17
17
|
|
|
18
18
|
data:`+JSON.stringify(t)+`
|
|
19
19
|
|
|
20
|
-
extractions:`+JSON.stringify(i))||"";a=a.replace(/```json/g,"").replace(/```/g,"").replace(/\n/g,"");let s=a.split(",").map(l=>l.trim()).join(",");return JSON.parse(s)}async generateMarkdown(n,t){return this.instruct("Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step.",n,t)}async instruct(n,t,r){let i=this.ai.clone();return i.resetConversation(),i.getContextPrefix=async()=>n,r&&i.addEventListener("output",a=>{r(a.detail.message)}),await i.sendMessage(t)}};var Ye=new U("Main"),rn=class rn extends EventTarget{constructor(){super(...arguments);this.conversationID=Ue();this.knowledgeBase=new tn(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new nn(this);this.userID=Yi();this.extra=Q().extra||{};this._lastSystemMsg="";this.isProcessing=!1}get loaded(){return!!(this.config&&this.currentModel)}async load(t){if(this.apiKey=t,!t)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{Ye.debug("Loading configuration...");let r=await fetch("
|
|
20
|
+
extractions:`+JSON.stringify(i))||"";a=a.replace(/```json/g,"").replace(/```/g,"").replace(/\n/g,"");let s=a.split(",").map(l=>l.trim()).join(",");return JSON.parse(s)}async generateMarkdown(n,t){return this.instruct("Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step.",n,t)}async instruct(n,t,r){let i=this.ai.clone();return i.resetConversation(),i.getContextPrefix=async()=>n,r&&i.addEventListener("output",a=>{r(a.detail.message)}),await i.sendMessage(t)}};var Ye=new U("Main"),rn=class rn extends EventTarget{constructor(){super(...arguments);this.conversationID=Ue();this.knowledgeBase=new tn(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new nn(this);this.userID=Yi();this.extra=Q().extra||{};this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1}get loaded(){return!!(this.config&&this.currentModel)}async load(t){if(this.apiKey=t,!t)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{Ye.debug("Loading configuration...");let r=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t})});if(!r.ok)throw new Error(`Failed to load configuration: ${r.status} ${r.statusText}`);this.config=await r.json(),Ye.debug("Configuration loaded")})(),(async()=>{try{let r=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!r.ok)throw new Error(`Failed to load VAD model: ${r.status} ${r.statusText}`);this.vadModel=await r.blob()}catch(r){Ye.warn(`Failed to load VAD model, some features will be unavailable. ${r.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let r of this.config.knowledge||[])r.url&&this.knowledgeBase.registerSourceFromURL(r.url);for(let r of this.config.knowledge||[])r.entries?.length&&this.knowledgeBase.registerSource(r.id,()=>r.entries||[]);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this.config}catch(r){throw Ye.warn("Failed to load:",r),this.error=r,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:r}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:r}})),r}}setModel(t){let r=this.models.find(i=>i.id==t);if(!r)throw new Error(`Model with ID "${t}" not found.`);this.currentModel=new qt({...r.config,onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(i,o)=>{let a=this.knowledgeBase.getCachedEntry(i);this.onAIToolStart?.(a?.id||i,o)}}),this.currentModel.id=r.id,this.currentModel.metadata=r}async getContextPrefix(){let t=Q().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 r=await this.getContextPrefix(),i=(this.currentModel.config.maxTokens||4e3)*.5*4,o=0;for(;;){let a=t.slice(),s=0;for(;s<o;){let u=a.findLastIndex(p=>!p.isContext);if(u==-1)throw new Error('Too much context, and no more items to remove. Check the size and number of "isContext: true" knowledge base entries, or use an LLM with a larger context window.');a.splice(u,1)}let l=`${r}
|
|
21
21
|
|
|
22
22
|
You have access to a database of knowledge base items. These include "info" type items which provide information, "tour" type items which contain instructions you should follow (only do the first one from the list!), and "action" type items which become available as tool calls. Current info and tour items:
|
|
23
23
|
`;l+=a.filter(u=>u.type=="info"||u.type=="tour"||u.type=="input-event").map(u=>{let p=fr(typeof u.content=="function"?u.content():u.content);return JSON.stringify({id:u.id,type:u.type,name:u.name,content:p})}).join(`
|
|
24
|
-
`),this.currentModel.config.systemMessage=l,this.currentModel.tools=a.filter(u=>u.type=="action"||u.type=="output-event").map(u=>{let p=fr(typeof u.content=="function"?u.content():u.content);return{name:u._functionID,description:p,params:u.parameters||[{name:"value",type:"string",description:"Input"}],removeFromMessageHistory:!!u.removeFromMessageHistory,callback:d=>this.toolRunKBAction(u,d),kb:u}});let c=this.currentModel.config.systemMessage;if(c+=JSON.stringify(this.currentModel.tools.map(u=>({name:u.name,description:u.description,params:u.params}))),c.length<=i)break;o+=1}this._lastSystemMsg!=this.currentModel.config.systemMessage&&(this._lastSystemMsg=this.currentModel.config.systemMessage,this.submitAnalyticsEvent({type:"system-msg",txt:this.currentModel.config.systemMessage}))}processIncomingMessage(t,r){r||this.submitAnalyticsEvent({type:"message",role:"assistant",message:t});let i="";this._lastOutput===void 0?(i=t,this._lastOutput=t):t.startsWith(this._lastOutput)?(i=t.substring(this._lastOutput.length),this._lastOutput=t):(Ye.warn("Message was changed during chunking. This should not happen.",t,this._lastOutput),i=t,this._lastOutput=t),r||(this._lastOutput=void 0),this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:r,message:t,messageChunk:i}})),this.onAIMessage?.(t,!!r)}async sendMessage(t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)return Ye.warn("Cannot send message while another message is being processed."),null;this.isProcessing=!0;try{return this.submitAnalyticsEvent({type:"message",role:"user",message:t}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:t}})),await this.currentModel.sendMessage(t)}finally{this.isProcessing=!1}}async toolRunKBAction(t,r){try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:t,input:r,ai:this}}));let i=await t.action(r,this);return this.submitAnalyticsEvent({type:"action",action:t.id,value:r,result:i}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:t,input:r,ai:this,result:i}})),i}catch(i){throw this.submitAnalyticsEvent({type:"action",action:t.id,value:r,error:i.message}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:t,input:r,ai:this,error:i}})),i}}submitAnalyticsEvent(t){Q().analytics===!1||this.config?.analytics===!1||fetch("https://intelliweave.ai/api/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID})}).catch(r=>{Ye.debug("Failed to submit analytics event:",r)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this.conversationID=Ue(),this._lastSystemMsg="")}insertAssistantMessage(t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.messages.push({role:"assistant",content:t})}exportState(){return{type:"intelliweave/state/v1",conversationID:this.conversationID,messages:this.currentModel?.messages}}importState(t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(t?.type!="intelliweave/state/v1")throw new Error(`Invalid state type: ${t.type}`);this.conversationID=t.conversationID,this.currentModel.messages=t.messages}clone(){let t=new rn;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.extra=this.extra,t.knowledgeBase=this.knowledgeBase.clone(),t}};rn.version=lo.version;var st=rn;var ye=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(t={},r=""){this.register();let i=document.createElement(this.tagName);for(let o in t)i.setAttribute(o,t[o]);return i.onBeforeCreate(),i.innerHTML=r,i}static add(t={},r=""){return this.register(),`<${this.tagName} ${Object.keys(t).map(i=>`${i}="${(t[i]+"").replaceAll('"',""")}"`).join(" ")}>${r}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(t,r,i){this._shadow&&this.onUpdate()}get attr(){if(this._attrProxy)return this._attrProxy;let t=r=>(on=on||document.createElement("div"),on.innerText=r||"",on.innerHTML);return this._attrProxy=new Proxy({},{get:(r,i)=>t(this.getAttribute(i.toString())||""),set:(r,i,o)=>(this.getAttribute(i.toString())===o||(o?this.setAttribute(i.toString(),o):this.removeAttribute(i.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(t,r)=>this._state[r],set:(t,r,i)=>(this._state[r]=i,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(t){return!!this.root?.getElementById(t)}child(t){let r=this.root?.getElementById(t);if(!r)throw new Error(`Child with ID ${t} not found`);return r}};ye.observedAttributes=[],ye.tagName="",ye._isRegistered=!1;var on;var uo='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var co='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var po='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var an=class extends ye{constructor(){super(...arguments);this.html=()=>`
|
|
24
|
+
`),this.currentModel.config.systemMessage=l,this.currentModel.tools=a.filter(u=>u.type=="action"||u.type=="output-event").map(u=>{let p=fr(typeof u.content=="function"?u.content():u.content);return{name:u._functionID,description:p,params:u.parameters||[{name:"value",type:"string",description:"Input"}],removeFromMessageHistory:!!u.removeFromMessageHistory,callback:d=>this.toolRunKBAction(u,d),kb:u}});let c=this.currentModel.config.systemMessage;if(c+=JSON.stringify(this.currentModel.tools.map(u=>({name:u.name,description:u.description,params:u.params}))),c.length<=i)break;o+=1}this._lastSystemMsg!=this.currentModel.config.systemMessage&&(this._lastSystemMsg=this.currentModel.config.systemMessage,this.submitAnalyticsEvent({type:"system-msg",txt:this.currentModel.config.systemMessage}))}processIncomingMessage(t,r){r||this.submitAnalyticsEvent({type:"message",role:"assistant",message:t});let i="";this._lastOutput===void 0?(i=t,this._lastOutput=t):t.startsWith(this._lastOutput)?(i=t.substring(this._lastOutput.length),this._lastOutput=t):(Ye.warn("Message was changed during chunking. This should not happen.",t,this._lastOutput),i=t,this._lastOutput=t),r||(this._lastOutput=void 0),this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:r,message:t,messageChunk:i}})),this.onAIMessage?.(t,!!r)}async sendMessage(t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)return Ye.warn("Cannot send message while another message is being processed."),null;this.isProcessing=!0;try{return this.submitAnalyticsEvent({type:"message",role:"user",message:t}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:t}})),await this.currentModel.sendMessage(t)}finally{this.isProcessing=!1}}async toolRunKBAction(t,r){try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:t,input:r,ai:this}}));let i=await t.action(r,this);return this.submitAnalyticsEvent({type:"action",action:t.id,value:r,result:i}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:t,input:r,ai:this,result:i}})),i}catch(i){throw this.submitAnalyticsEvent({type:"action",action:t.id,value:r,error:i.message}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:t,input:r,ai:this,error:i}})),i}}submitAnalyticsEvent(t){Q().analytics===!1||this.config?.analytics===!1||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})}).catch(r=>{Ye.debug("Failed to submit analytics event:",r)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this.conversationID=Ue(),this._lastSystemMsg="")}insertAssistantMessage(t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.messages.push({role:"assistant",content:t})}exportState(){return{type:"intelliweave/state/v1",conversationID:this.conversationID,messages:this.currentModel?.messages}}importState(t){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(t?.type!="intelliweave/state/v1")throw new Error(`Invalid state type: ${t.type}`);this.conversationID=t.conversationID,this.currentModel.messages=t.messages}clone(){let t=new rn;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.extra=this.extra,t.knowledgeBase=this.knowledgeBase.clone(),t}};rn.version=lo.version;var st=rn;var ye=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(t={},r=""){this.register();let i=document.createElement(this.tagName);for(let o in t)i.setAttribute(o,t[o]);return i.onBeforeCreate(),i.innerHTML=r,i}static add(t={},r=""){return this.register(),`<${this.tagName} ${Object.keys(t).map(i=>`${i}="${(t[i]+"").replaceAll('"',""")}"`).join(" ")}>${r}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(t,r,i){this._shadow&&this.onUpdate()}get attr(){if(this._attrProxy)return this._attrProxy;let t=r=>(on=on||document.createElement("div"),on.innerText=r||"",on.innerHTML);return this._attrProxy=new Proxy({},{get:(r,i)=>t(this.getAttribute(i.toString())||""),set:(r,i,o)=>(this.getAttribute(i.toString())===o||(o?this.setAttribute(i.toString(),o):this.removeAttribute(i.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(t,r)=>this._state[r],set:(t,r,i)=>(this._state[r]=i,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(t){return!!this.root?.getElementById(t)}child(t){let r=this.root?.getElementById(t);if(!r)throw new Error(`Child with ID ${t} not found`);return r}};ye.observedAttributes=[],ye.tagName="",ye._isRegistered=!1;var on;var uo='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var co='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var po='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var an=class extends ye{constructor(){super(...arguments);this.html=()=>`
|
|
25
25
|
|
|
26
26
|
<!-- Styling -->
|
|
27
27
|
<style>
|
|
@@ -282,25 +282,27 @@ You have access to a database of knowledge base items. These include "info" type
|
|
|
282
282
|
|
|
283
283
|
#root {
|
|
284
284
|
position: fixed;
|
|
285
|
-
display: flex;
|
|
286
|
-
flex-direction: column;
|
|
287
285
|
width: 64px;
|
|
288
286
|
height: 64px;
|
|
289
287
|
z-index: 200000;
|
|
290
288
|
background-color: #20262C;
|
|
291
|
-
border-radius:
|
|
289
|
+
border-radius: 50%;
|
|
292
290
|
box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
|
|
293
291
|
transition: width 0.25s, height 0.25s, border-radius 0.25s;
|
|
294
292
|
overflow: hidden;
|
|
295
293
|
color: white;
|
|
296
294
|
font-family: "Karla", sans-serif;
|
|
295
|
+
overlow: hidden;
|
|
297
296
|
}
|
|
298
297
|
#root.open {
|
|
299
298
|
border-radius: 32px 32px 16px 16px;
|
|
299
|
+
display: flex;
|
|
300
|
+
flex-direction: column;
|
|
300
301
|
width: 400px;
|
|
301
302
|
height: 600px;
|
|
302
303
|
max-width: calc(100vw - 40px);
|
|
303
304
|
max-height: calc(max(50vh, 100vh - 320px));
|
|
305
|
+
overflow: visible;
|
|
304
306
|
}
|
|
305
307
|
|
|
306
308
|
#root #web-weaver-logo {
|
|
@@ -310,6 +312,7 @@ You have access to a database of knowledge base items. These include "info" type
|
|
|
310
312
|
top: 0px;
|
|
311
313
|
left: 0px;
|
|
312
314
|
background-color: #21262c;
|
|
315
|
+
border-radius:50%;
|
|
313
316
|
z-index:999;
|
|
314
317
|
}
|
|
315
318
|
|
|
@@ -328,6 +331,8 @@ You have access to a database of knowledge base items. These include "info" type
|
|
|
328
331
|
overflow: hidden;
|
|
329
332
|
font-size: 9px;
|
|
330
333
|
color: #abacad;
|
|
334
|
+
border-bottom-right-radius: 16px;
|
|
335
|
+
border-bottom-left-radius: 16px;
|
|
331
336
|
}
|
|
332
337
|
|
|
333
338
|
#root .green-accent {
|
|
@@ -449,7 +454,7 @@ You have access to a database of knowledge base items. These include "info" type
|
|
|
449
454
|
|
|
450
455
|
</div>
|
|
451
456
|
|
|
452
|
-
`;this._isProcessing=!1;this.ai=new st,yt.isSupported&&(this.ai.audio=new yt(this.ai))}onCreate(){Q().embed&&Wi.warn("Only one <web-weaver-embed> element should be on the page."),Q().embed=this,this.child("root").addEventListener("click",i=>this.onContainerClick(i)),this.child("web-weaver-logo").addEventListener("click",i=>this.onLogoClick(i)),this.child("interaction-bar").addEventListener("input-message",i=>this.processInput(i.detail)),this.child("interaction-bar").addEventListener("llm-button-click",i=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",i=>this.onLLMModelSelect(i)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.onAIToolStart=this.onAIToolStart.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:i=>(this.suggestions.push(i.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:i.text}),"Suggestion button added")});let r=this.attr.apiKey||Q().apiKey;if(!r)return Wi.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.ai.load(r).then(i=>{this.config=i,Q().introductionMessage=this.config.introductionMessage,Q().analytics=this.config.analytics!==void 0?!!this.config.analytics:Q().analytics,this.state.loading=!1,this.resetConversation()})}onUpdate(){this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("root").className=this.attr.open?"open":"",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("root").style.right=this.attr.offsetX?this.attr.offsetX+"px":"20px",this.child("root").style.bottom=this.attr.offsetY?this.attr.offsetY+"px":"20px",this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1;let t=this.child("web-weaver-logo");t.attr.focusID=this.attr.focusID,t.refreshLayout(),this.child("llm-selector-panel").state.items=this.ai.models.sort((r,i)=>(i.priority||0)-(r.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){Q().embed==this&&(Q().embed=null)}onContainerClick(t){this.attr.open||(t.preventDefault(),this.attr.open=!0)}onLogoClick(t){t.preventDefault(),t.stopPropagation(),this.attr.focusID?this.attr.focusID="":this.attr.open=!this.attr.open}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let t=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;t.children.length>0;)t.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let r=document.createElement("div");r.className="introduction-message",r.innerHTML=Q().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,t.appendChild(r),this.ai.insertAssistantMessage(r.innerText);for(let i of Q().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",a=>this.onSuggestionClick(a,i)),t.appendChild(o)}}async processInput(t){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let r=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let o of Array.from(r.querySelectorAll(".suggestion-button")))o.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=t,r.appendChild(i),r.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"}),await this.ai.sendMessage(t);for(let o of this.suggestions){let a=document.createElement("div");a.className="suggestion-button",a.innerText=o,a.addEventListener("click",s=>this.onSuggestionClick(s,o)),r.appendChild(a)}r.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}catch(i){Wi.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,r.appendChild(o);let a=document.createElement("div");a.className="suggestion-button",a.innerText="Reset conversation",a.addEventListener("click",s=>this.resetConversation()),r.appendChild(a)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(t){let r=await Mi().use(Vn).use(On).use(fn,{target:"_blank",rel:["noopener","noreferrer"]}).use(gn).use(Cn).processSync(t),i=this.child("web-weaver-embed-inner"),o=i.lastElementChild;if(o&&o.classList.contains("output"))o.innerHTML=r.toString("utf-8");else{let a=document.createElement("div");a.className="output",a.innerHTML=r.toString("utf-8"),i.appendChild(a)}for(let a of Array.from(i.querySelectorAll(".tool")))a.remove();i.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}onAIToolStart(t,r){let i=`Running: ${t}`;t=="search"&&(i=`Searching: ${r?.query}`),t=="ui.focusElement"&&(i=`Focusing: #${r?.elementID}`),t=="ui.suggestResponse"&&(i=`Suggested response: ${r?.text}`);let o=this.child("web-weaver-embed-inner"),a=document.createElement("div");a.className="tool",a.innerText=i,o.appendChild(a),o.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}onSuggestionClick(t,r){this.processInput(r)}onLLMModelSelect(t){t.preventDefault(),this.ai.setModel(t.detail),this.state.llmPanelOpen=!1}};nt.tagName="intelliweave-embed",nt.observedAttributes=["logo","focusID","open"];Ce.lib=()=>import("./ort.bundle.min-5QOPZPPI.js");document.body.appendChild(nt.create());
|
|
457
|
+
`;this._isProcessing=!1;this.ai=new st,yt.isSupported&&(this.ai.audio=new yt(this.ai))}onCreate(){Q().embed&&Wi.warn("Only one <web-weaver-embed> element should be on the page."),Q().embed=this,this.child("root").addEventListener("click",i=>this.onContainerClick(i)),this.child("web-weaver-logo").addEventListener("click",i=>this.onLogoClick(i)),this.child("interaction-bar").addEventListener("input-message",i=>this.processInput(i.detail)),this.child("interaction-bar").addEventListener("llm-button-click",i=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",i=>this.onLLMModelSelect(i)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.onAIToolStart=this.onAIToolStart.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:i=>(this.suggestions.push(i.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:i.text}),"Suggestion button added")});let r=this.attr.apiKey||Q().apiKey;if(!r)return Wi.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(r).then(i=>{this.config=i,Q().introductionMessage=this.config.introductionMessage,Q().analytics=this.config.analytics!==void 0?!!this.config.analytics:Q().analytics,this.state.loading=!1,this.resetConversation()})}onUpdate(){this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("root").className=this.attr.open?"open":"",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("root").style.right=this.attr.offsetX?this.attr.offsetX+"px":"20px",this.child("root").style.bottom=this.attr.offsetY?this.attr.offsetY+"px":"20px",this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1;let t=this.child("web-weaver-logo");t.attr.focusID=this.attr.focusID,t.refreshLayout(),this.child("llm-selector-panel").state.items=this.ai.models.sort((r,i)=>(i.priority||0)-(r.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){Q().embed==this&&(Q().embed=null)}onContainerClick(t){this.attr.open||(t.preventDefault(),this.attr.open=!0)}onLogoClick(t){t.preventDefault(),t.stopPropagation(),this.attr.focusID?this.attr.focusID="":this.attr.open=!this.attr.open}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let t=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;t.children.length>0;)t.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let r=document.createElement("div");r.className="introduction-message",r.innerHTML=Q().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,t.appendChild(r),this.ai.insertAssistantMessage(r.innerText);for(let i of Q().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",a=>this.onSuggestionClick(a,i)),t.appendChild(o)}}async processInput(t){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let r=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let o of Array.from(r.querySelectorAll(".suggestion-button")))o.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=t,r.appendChild(i),r.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"}),await this.ai.sendMessage(t);for(let o of this.suggestions){let a=document.createElement("div");a.className="suggestion-button",a.innerText=o,a.addEventListener("click",s=>this.onSuggestionClick(s,o)),r.appendChild(a)}r.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}catch(i){Wi.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,r.appendChild(o);let a=document.createElement("div");a.className="suggestion-button",a.innerText="Reset conversation",a.addEventListener("click",s=>this.resetConversation()),r.appendChild(a)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(t){let r=await Mi().use(Vn).use(On).use(fn,{target:"_blank",rel:["noopener","noreferrer"]}).use(gn).use(Cn).processSync(t),i=this.child("web-weaver-embed-inner"),o=i.lastElementChild;if(o&&o.classList.contains("output"))o.innerHTML=r.toString("utf-8");else{let a=document.createElement("div");a.className="output",a.innerHTML=r.toString("utf-8"),i.appendChild(a)}for(let a of Array.from(i.querySelectorAll(".tool")))a.remove();i.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}onAIToolStart(t,r){let i=`Running: ${t}`;t=="search"&&(i=`Searching: ${r?.query}`),t=="ui.focusElement"&&(i=`Focusing: #${r?.elementID}`),t=="ui.suggestResponse"&&(i=`Suggested response: ${r?.text}`);let o=this.child("web-weaver-embed-inner"),a=document.createElement("div");a.className="tool",a.innerText=i,o.appendChild(a),o.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}onSuggestionClick(t,r){this.processInput(r)}onLLMModelSelect(t){t.preventDefault(),this.ai.setModel(t.detail),this.state.llmPanelOpen=!1}};nt.tagName="intelliweave-embed",nt.observedAttributes=["logo","focusID","open"];Ce.lib=()=>import("./ort.bundle.min-5QOPZPPI.js");document.body.appendChild(nt.create());
|
|
453
458
|
/*! Bundled license information:
|
|
454
459
|
|
|
455
460
|
react/cjs/react.production.min.js:
|
package/dist/webpack/index.d.ts
CHANGED
|
@@ -144,6 +144,8 @@ interface KnowledgeBaseSource {
|
|
|
144
144
|
query?: (query: string) => (KnowledgeBaseItem[] | Promise<KnowledgeBaseItem[]>);
|
|
145
145
|
/** URL query for remote sources */
|
|
146
146
|
url?: string;
|
|
147
|
+
/** Pre-packaged knowledge base entries */
|
|
148
|
+
entries?: KnowledgeBaseItem[];
|
|
147
149
|
}
|
|
148
150
|
/** Knowledge base item */
|
|
149
151
|
interface KnowledgeBaseItem {
|
|
@@ -365,6 +367,8 @@ declare class IntelliWeave extends EventTarget {
|
|
|
365
367
|
userID: string;
|
|
366
368
|
/** Extra data that will be passed to external knowledge base actions. */
|
|
367
369
|
extra: any;
|
|
370
|
+
/** URL of the IntelliWeave Hub API */
|
|
371
|
+
hubAPI: string;
|
|
368
372
|
/** Set model and load data from an API key */
|
|
369
373
|
load(apiKey: string): Promise<WebWeaverGPTConfig>;
|
|
370
374
|
/** Set the current model */
|
|
@@ -1282,6 +1286,8 @@ declare const WebWeaverUI: (props: {
|
|
|
1282
1286
|
offsetY?: number;
|
|
1283
1287
|
/** User ID */
|
|
1284
1288
|
userID?: string;
|
|
1289
|
+
/** (Internal) Use a different address to access the IntelliWeave Hub API */
|
|
1290
|
+
hubAPI?: string;
|
|
1285
1291
|
}) => React.JSX.Element | null;
|
|
1286
1292
|
/** Global typescript definitions */
|
|
1287
1293
|
declare global {
|