@intelliweave/embedded 2.0.72-beta.2 → 2.0.72-beta.4
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.js +15 -15
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.js +14 -14
- package/dist/react/react.js +10 -10
- package/dist/script-tag/script-tag.js +3 -3
- package/dist/webpack/index.js +9 -9
- package/package.json +1 -1
|
@@ -62,7 +62,7 @@ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
|
62
62
|
|
|
63
63
|
Human:`;zt.AI_PROMPT=`
|
|
64
64
|
|
|
65
|
-
Assistant:`;zt.DEFAULT_TIMEOUT=6e5;zt.AnthropicError=pe;zt.APIError=nr;zt.APIConnectionError=ns;zt.APIConnectionTimeoutError=oc;zt.APIUserAbortError=fr;zt.NotFoundError=cc;zt.ConflictError=uc;zt.RateLimitError=fc;zt.BadRequestError=sc;zt.AuthenticationError=ac;zt.InternalServerError=pc;zt.PermissionDeniedError=lc;zt.UnprocessableEntityError=dc;zt.toFile=uh;var Qn=class extends zt{constructor(){super(...arguments),this.completions=new ma(this),this.messages=new as(this),this.models=new ha(this),this.beta=new Ei(this)}};Qn.Completions=ma;Qn.Messages=as;Qn.Models=ha;Qn.Beta=Ei;var{HUMAN_PROMPT:iL,AI_PROMPT:oL}=Qn;var nP=new Ve("AnthropicChat"),Th=class extends ic{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}async sendMessage(e,r){this.addUserMessage(e);let n=new Qn({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),i=!0,o=[];for(;i;){i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),nP.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.data),tools:this.toolGroup.getAll().map(d=>d.data),context:this.contextGroup.getAll().map(d=>d.text)});let s=this.toolGroup.getAll().map(d=>({name:d.data?.name||"",description:d.data?.description||"",input_schema:{...d.data?.params,type:"object"}})),a;if(this.config.stream){let d=n.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(p=>p.data),tools:s,stream:!0});d.on("streamEvent",(p,f)=>{let m=this.parseMessageBlock(f);this.config.onAIMessage?.([...o,m],!0),r?.([...o,m])});try{a=await d.finalMessage()}catch(p){throw p?.error?.error?.message?p.error.error:p}}else try{a=await n.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(d=>d.data),tools:s})}catch(d){throw d?.error?.error?.message?d.error.error:d}nP.debug("Message received",a);let l=this.messageGroup.add(this.parseMessageBlock(a));o.push(l);let c=[],u=[];if(await Promise.all(a.content.map(async d=>{if(d.type!="tool_use")return;let p=this.findToolBySafeName(d.name);try{let f=await this.executeTool(p,d.input);u.push({type:"tool_result",tool_use_id:d.id,content:f}),c.push({type:"tool_result",toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolName:d.name,toolSuccessResponse:f,toolCallInstanceID:d.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI})}catch(f){let m=f?.message||"An unknown error occurred";u.push({type:"tool_result",tool_use_id:d.id,content:`Error performing tool call ${d.name}: ${m}`}),c.push({type:"tool_result",toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolName:d.name,toolErrorResponse:m,toolCallInstanceID:d.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI})}})),u.length>0){let d=this.messageGroup.add({id:"msg-"+dr(),sections:c,data:{role:"user",content:u}});o.push(d),i=!0,this.config.onAIMessage?.(o,!0),r?.(o)}this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return this.config.onAIMessage?.(o,!1),r?.(o),o}parseMessageBlock(e){let r=[];for(let n of e.content)if(n.type=="thinking")r.push({type:"thinking",text:n.thinking||""});else if(n.type=="text")r.push({type:"text",text:n.text||""});else if(n.type=="tool_use"){let i=this.findToolBySafeName(n.name);r.push({type:"tool_call",toolName:n.name,toolKbID:i?.kbItem?.id,toolKbName:i?.kbItem?.name,toolParameters:n.input,toolCallInstanceID:n.id,toolCallHiddenInUI:i?.kbItem?.hideActionInUI})}return{id:e.id,data:{role:e.role,content:e.content},sections:r,source:"assistant",usage:{inputTokens:e.usage?.input_tokens||0,outputTokens:e.usage?.output_tokens||0,cachedInputTokens:e.usage?.cache_read_input_tokens||0,totalTokens:(e.usage?.input_tokens||0)+(e.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};var gt=function(){return gt=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},gt.apply(this,arguments)};function sL(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function a(u){try{c(n.next(u))}catch(d){s(d)}}function l(u){try{c(n.throw(u))}catch(d){s(d)}}function c(u){u.done?o(u.value):i(u.value).then(a,l)}c((n=n.apply(t,e||[])).next())})}function aL(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(r=0)),r;)try{if(n=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 r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){r.label=c[1];break}if(c[0]===6&&r.label<o[1]){r.label=o[1],o=c;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(c);break}o[2]&&r.ops.pop(),r.trys.pop();continue}c=e.call(t,r)}catch(u){c=[6,u],i=0}finally{n=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function Oe(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function jt(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}var lL="ENTRIES",lP="KEYS",cP="VALUES",pr="",hb=function(){function t(e,r){var n=e._tree,i=Array.from(n.keys());this.set=e,this._type=r,this._path=i.length>0?[{node:n,keys:i}]:[]}return t.prototype.next=function(){var e=this.dive();return this.backtrack(),e},t.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var e=xc(this._path),r=e.node,n=e.keys;if(xc(n)===pr)return{done:!1,value:this.result()};var i=r.get(xc(n));return this._path.push({node:i,keys:Array.from(i.keys())}),this.dive()},t.prototype.backtrack=function(){if(this._path.length!==0){var e=xc(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}},t.prototype.key=function(){return this.set._prefix+this._path.map(function(e){var r=e.keys;return xc(r)}).filter(function(e){return e!==pr}).join("")},t.prototype.value=function(){return xc(this._path).node.get(pr)},t.prototype.result=function(){switch(this._type){case cP:return this.value();case lP:return this.key();default:return[this.key(),this.value()]}},t.prototype[Symbol.iterator]=function(){return this},t}(),xc=function(t){return t[t.length-1]},cL=function(t,e,r){var n=new Map;if(e===void 0)return n;for(var i=e.length+1,o=i+r,s=new Uint8Array(o*i).fill(r+1),a=0;a<i;++a)s[a]=a;for(var l=1;l<o;++l)s[l*i]=l;return uP(t,e,r,n,s,1,i,""),n},uP=function(t,e,r,n,i,o,s,a){var l,c,u=o*s;try{e:for(var d=Oe(t.keys()),p=d.next();!p.done;p=d.next()){var f=p.value;if(f===pr){var m=i[u-1];m<=r&&n.set(a,[t.get(f),m])}else{for(var h=o,y=0;y<f.length;++y,++h){for(var g=f[y],_=s*h,b=_-s,E=i[_],I=Math.max(0,h-r-1),P=Math.min(s-1,h+r),M=I;M<P;++M){var V=g!==e[M],R=i[b+M]+ +V,L=i[b+M+1]+1,G=i[_+M]+1,H=i[_+M+1]=Math.min(R,L,G);H<E&&(E=H)}if(E>r)continue e}uP(t.get(f),e,r,n,i,h,s,a+f)}}}catch(W){l={error:W}}finally{try{p&&!p.done&&(c=d.return)&&c.call(d)}finally{if(l)throw l.error}}},gb=function(){function t(e,r){e===void 0&&(e=new Map),r===void 0&&(r=""),this._size=void 0,this._tree=e,this._prefix=r}return t.prototype.atPrefix=function(e){var r,n;if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");var i=jt(zh(this._tree,e.slice(this._prefix.length)),2),o=i[0],s=i[1];if(o===void 0){var a=jt(kb(s),2),l=a[0],c=a[1];try{for(var u=Oe(l.keys()),d=u.next();!d.done;d=u.next()){var p=d.value;if(p!==pr&&p.startsWith(c)){var f=new Map;return f.set(p.slice(c.length),l.get(p)),new t(f,e)}}}catch(m){r={error:m}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}}return new t(o,e)},t.prototype.clear=function(){this._size=void 0,this._tree.clear()},t.prototype.delete=function(e){return this._size=void 0,uL(this._tree,e)},t.prototype.entries=function(){return new hb(this,lL)},t.prototype.forEach=function(e){var r,n;try{for(var i=Oe(this),o=i.next();!o.done;o=i.next()){var s=jt(o.value,2),a=s[0],l=s[1];e(a,l,this)}}catch(c){r={error:c}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.fuzzyGet=function(e,r){return cL(this._tree,e,r)},t.prototype.get=function(e){var r=wb(this._tree,e);return r!==void 0?r.get(pr):void 0},t.prototype.has=function(e){var r=wb(this._tree,e);return r!==void 0&&r.has(pr)},t.prototype.keys=function(){return new hb(this,lP)},t.prototype.set=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=yb(this._tree,e);return n.set(pr,r),this},Object.defineProperty(t.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var e=this.entries();!e.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),t.prototype.update=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=yb(this._tree,e);return n.set(pr,r(n.get(pr))),this},t.prototype.fetch=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=yb(this._tree,e),i=n.get(pr);return i===void 0&&n.set(pr,i=r()),i},t.prototype.values=function(){return new hb(this,cP)},t.prototype[Symbol.iterator]=function(){return this.entries()},t.from=function(e){var r,n,i=new t;try{for(var o=Oe(e),s=o.next();!s.done;s=o.next()){var a=jt(s.value,2),l=a[0],c=a[1];i.set(l,c)}}catch(u){r={error:u}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i},t.fromObject=function(e){return t.from(Object.entries(e))},t}(),zh=function(t,e,r){var n,i;if(r===void 0&&(r=[]),e.length===0||t==null)return[t,r];try{for(var o=Oe(t.keys()),s=o.next();!s.done;s=o.next()){var a=s.value;if(a!==pr&&e.startsWith(a))return r.push([t,a]),zh(t.get(a),e.slice(a.length),r)}}catch(l){n={error:l}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return r.push([t,e]),zh(void 0,"",r)},wb=function(t,e){var r,n;if(e.length===0||t==null)return t;try{for(var i=Oe(t.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;if(s!==pr&&e.startsWith(s))return wb(t.get(s),e.slice(s.length))}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},yb=function(t,e){var r,n,i=e.length;e:for(var o=0;t&&o<i;){try{for(var s=(r=void 0,Oe(t.keys())),a=s.next();!a.done;a=s.next()){var l=a.value;if(l!==pr&&e[o]===l[0]){for(var c=Math.min(i-o,l.length),u=1;u<c&&e[o+u]===l[u];)++u;var d=t.get(l);if(u===l.length)t=d;else{var p=new Map;p.set(l.slice(u),d),t.set(e.slice(o,o+u),p),t.delete(l),t=p}o+=u;continue e}}}catch(m){r={error:m}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}var f=new Map;return t.set(e.slice(o),f),f}return t},uL=function(t,e){var r=jt(zh(t,e),2),n=r[0],i=r[1];if(n!==void 0){if(n.delete(pr),n.size===0)dP(i);else if(n.size===1){var o=jt(n.entries().next().value,2),s=o[0],a=o[1];fP(i,s,a)}}},dP=function(t){if(t.length!==0){var e=jt(kb(t),2),r=e[0],n=e[1];if(r.delete(n),r.size===0)dP(t.slice(0,-1));else if(r.size===1){var i=jt(r.entries().next().value,2),o=i[0],s=i[1];o!==pr&&fP(t.slice(0,-1),o,s)}}},fP=function(t,e,r){if(t.length!==0){var n=jt(kb(t),2),i=n[0],o=n[1];i.set(o+e,r),i.delete(o)}},kb=function(t){return t[t.length-1]},Ud,Sb="or",pP="and",dL="and_not",mP=function(){function t(e){if(e?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');var r=e.autoVacuum==null||e.autoVacuum===!0?bb:e.autoVacuum;this._options=gt(gt(gt({},_b),e),{autoVacuum:r,searchOptions:gt(gt({},iP),e.searchOptions||{}),autoSuggestOptions:gt(gt({},gL),e.autoSuggestOptions||{})}),this._index=new gb,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=$b,this.addFields(this._options.fields)}return t.prototype.add=function(e){var r,n,i,o,s,a,l=this._options,c=l.extractField,u=l.tokenize,d=l.processTerm,p=l.fields,f=l.idField,m=c(e,f);if(m==null)throw new Error('MiniSearch: document does not have ID field "'.concat(f,'"'));if(this._idToShortId.has(m))throw new Error("MiniSearch: duplicate ID ".concat(m));var h=this.addDocumentId(m);this.saveStoredFields(h,e);try{for(var y=Oe(p),g=y.next();!g.done;g=y.next()){var _=g.value,b=c(e,_);if(b!=null){var E=u(b.toString(),_),I=this._fieldIds[_],P=new Set(E).size;this.addFieldLength(h,I,this._documentCount-1,P);try{for(var M=(i=void 0,Oe(E)),V=M.next();!V.done;V=M.next()){var R=V.value,L=d(R,_);if(Array.isArray(L))try{for(var G=(s=void 0,Oe(L)),H=G.next();!H.done;H=G.next()){var W=H.value;this.addTerm(I,h,W)}}catch(Y){s={error:Y}}finally{try{H&&!H.done&&(a=G.return)&&a.call(G)}finally{if(s)throw s.error}}else L&&this.addTerm(I,h,L)}}catch(Y){i={error:Y}}finally{try{V&&!V.done&&(o=M.return)&&o.call(M)}finally{if(i)throw i.error}}}}}catch(Y){r={error:Y}}finally{try{g&&!g.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}},t.prototype.addAll=function(e){var r,n;try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;this.add(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.addAllAsync=function(e,r){var n=this;r===void 0&&(r={});var i=r.chunkSize,o=i===void 0?10:i,s={chunk:[],promise:Promise.resolve()},a=e.reduce(function(u,d,p){var f=u.chunk,m=u.promise;return f.push(d),(p+1)%o===0?{chunk:[],promise:m.then(function(){return new Promise(function(h){return setTimeout(h,0)})}).then(function(){return n.addAll(f)})}:{chunk:f,promise:m}},s),l=a.chunk,c=a.promise;return c.then(function(){return n.addAll(l)})},t.prototype.remove=function(e){var r,n,i,o,s,a,l=this._options,c=l.tokenize,u=l.processTerm,d=l.extractField,p=l.fields,f=l.idField,m=d(e,f);if(m==null)throw new Error('MiniSearch: document does not have ID field "'.concat(f,'"'));var h=this._idToShortId.get(m);if(h==null)throw new Error("MiniSearch: cannot remove document with ID ".concat(m,": it is not in the index"));try{for(var y=Oe(p),g=y.next();!g.done;g=y.next()){var _=g.value,b=d(e,_);if(b!=null){var E=c(b.toString(),_),I=this._fieldIds[_],P=new Set(E).size;this.removeFieldLength(h,I,this._documentCount,P);try{for(var M=(i=void 0,Oe(E)),V=M.next();!V.done;V=M.next()){var R=V.value,L=u(R,_);if(Array.isArray(L))try{for(var G=(s=void 0,Oe(L)),H=G.next();!H.done;H=G.next()){var W=H.value;this.removeTerm(I,h,W)}}catch(Y){s={error:Y}}finally{try{H&&!H.done&&(a=G.return)&&a.call(G)}finally{if(s)throw s.error}}else L&&this.removeTerm(I,h,L)}}catch(Y){i={error:Y}}finally{try{V&&!V.done&&(o=M.return)&&o.call(M)}finally{if(i)throw i.error}}}}}catch(Y){r={error:Y}}finally{try{g&&!g.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}this._storedFields.delete(h),this._documentIds.delete(h),this._idToShortId.delete(m),this._fieldLength.delete(h),this._documentCount-=1},t.prototype.removeAll=function(e){var r,n;if(e)try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;this.remove(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new gb,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},t.prototype.discard=function(e){var r=this,n=this._idToShortId.get(e);if(n==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(e,": it is not in the index"));this._idToShortId.delete(e),this._documentIds.delete(n),this._storedFields.delete(n),(this._fieldLength.get(n)||[]).forEach(function(i,o){r.removeFieldLength(n,o,r._documentCount,i)}),this._fieldLength.delete(n),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},t.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var e=this._options.autoVacuum,r=e.minDirtFactor,n=e.minDirtCount,i=e.batchSize,o=e.batchWait;this.conditionalVacuum({batchSize:i,batchWait:o},{minDirtCount:n,minDirtFactor:r})}},t.prototype.discardAll=function(e){var r,n,i=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var o=Oe(e),s=o.next();!s.done;s=o.next()){var a=s.value;this.discard(a)}}catch(l){r={error:l}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}}finally{this._options.autoVacuum=i}this.maybeAutoVacuum()},t.prototype.replace=function(e){var r=this._options,n=r.idField,i=r.extractField,o=i(e,n);this.discard(o),this.add(e)},t.prototype.vacuum=function(e){return e===void 0&&(e={}),this.conditionalVacuum(e)},t.prototype.conditionalVacuum=function(e,r){var n=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&r,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var i=n._enqueuedVacuumConditions;return n._enqueuedVacuumConditions=$b,n.performVacuuming(e,i)}),this._enqueuedVacuum)):this.vacuumConditionsMet(r)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)},t.prototype.performVacuuming=function(e,r){return sL(this,void 0,void 0,function(){var n,i,o,s,a,l,c,u,d,p,f,m,h,y,g,_,b,E,I,P,M,V,R,L,G;return aL(this,function(H){switch(H.label){case 0:if(n=this._dirtCount,!this.vacuumConditionsMet(r))return[3,10];i=e.batchSize||xb.batchSize,o=e.batchWait||xb.batchWait,s=1,H.label=1;case 1:H.trys.push([1,7,8,9]),a=Oe(this._index),l=a.next(),H.label=2;case 2:if(l.done)return[3,6];c=jt(l.value,2),u=c[0],d=c[1];try{for(p=(V=void 0,Oe(d)),f=p.next();!f.done;f=p.next()){m=jt(f.value,2),h=m[0],y=m[1];try{for(g=(L=void 0,Oe(y)),_=g.next();!_.done;_=g.next())b=jt(_.value,1),E=b[0],!this._documentIds.has(E)&&(y.size<=1?d.delete(h):y.delete(E))}catch(W){L={error:W}}finally{try{_&&!_.done&&(G=g.return)&&G.call(g)}finally{if(L)throw L.error}}}}catch(W){V={error:W}}finally{try{f&&!f.done&&(R=p.return)&&R.call(p)}finally{if(V)throw V.error}}return this._index.get(u).size===0&&this._index.delete(u),s%i!==0?[3,4]:[4,new Promise(function(W){return setTimeout(W,o)})];case 3:H.sent(),H.label=4;case 4:s+=1,H.label=5;case 5:return l=a.next(),[3,2];case 6:return[3,9];case 7:return I=H.sent(),P={error:I},[3,9];case 8:try{l&&!l.done&&(M=a.return)&&M.call(a)}finally{if(P)throw P.error}return[7];case 9:this._dirtCount-=n,H.label=10;case 10:return[4,null];case 11:return H.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},t.prototype.vacuumConditionsMet=function(e){if(e==null)return!0;var r=e.minDirtCount,n=e.minDirtFactor;return r=r||bb.minDirtCount,n=n||bb.minDirtFactor,this.dirtCount>=r&&this.dirtFactor>=n},Object.defineProperty(t.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),t.prototype.has=function(e){return this._idToShortId.has(e)},t.prototype.getStoredFields=function(e){var r=this._idToShortId.get(e);if(r!=null)return this._storedFields.get(r)},t.prototype.search=function(e,r){var n,i;r===void 0&&(r={});var o=this.executeQuery(e,r),s=[];try{for(var a=Oe(o),l=a.next();!l.done;l=a.next()){var c=jt(l.value,2),u=c[0],d=c[1],p=d.score,f=d.terms,m=d.match,h=f.length||1,y={id:this._documentIds.get(u),score:p*h,terms:Object.keys(m),queryTerms:f,match:m};Object.assign(y,this._storedFields.get(u)),(r.filter==null||r.filter(y))&&s.push(y)}}catch(g){n={error:g}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}return e===t.wildcard&&r.boostDocument==null&&this._options.searchOptions.boostDocument==null||s.sort(sP),s},t.prototype.autoSuggest=function(e,r){var n,i,o,s;r===void 0&&(r={}),r=gt(gt({},this._options.autoSuggestOptions),r);var a=new Map;try{for(var l=Oe(this.search(e,r)),c=l.next();!c.done;c=l.next()){var u=c.value,d=u.score,p=u.terms,f=p.join(" "),m=a.get(f);m!=null?(m.score+=d,m.count+=1):a.set(f,{score:d,terms:p,count:1})}}catch(I){n={error:I}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}var h=[];try{for(var y=Oe(a),g=y.next();!g.done;g=y.next()){var _=jt(g.value,2),m=_[0],b=_[1],d=b.score,p=b.terms,E=b.count;h.push({suggestion:m,terms:p,score:d/E})}}catch(I){o={error:I}}finally{try{g&&!g.done&&(s=y.return)&&s.call(y)}finally{if(o)throw o.error}}return h.sort(sP),h},Object.defineProperty(t.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),t.loadJSON=function(e,r){if(r==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(e),r)},t.getDefault=function(e){if(_b.hasOwnProperty(e))return vb(_b,e);throw new Error('MiniSearch: unknown option "'.concat(e,'"'))},t.loadJS=function(e,r){var n,i,o,s,a,l,c=e.index,u=e.documentCount,d=e.nextId,p=e.documentIds,f=e.fieldIds,m=e.fieldLength,h=e.averageFieldLength,y=e.storedFields,g=e.dirtCount,_=e.serializationVersion;if(_!==1&&_!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var b=new t(r);b._documentCount=u,b._nextId=d,b._documentIds=Ah(p),b._idToShortId=new Map,b._fieldIds=f,b._fieldLength=Ah(m),b._avgFieldLength=h,b._storedFields=Ah(y),b._dirtCount=g||0,b._index=new gb;try{for(var E=Oe(b._documentIds),I=E.next();!I.done;I=E.next()){var P=jt(I.value,2),M=P[0],V=P[1];b._idToShortId.set(V,M)}}catch(Pt){n={error:Pt}}finally{try{I&&!I.done&&(i=E.return)&&i.call(E)}finally{if(n)throw n.error}}try{for(var R=Oe(c),L=R.next();!L.done;L=R.next()){var G=jt(L.value,2),H=G[0],W=G[1],Y=new Map;try{for(var ie=(a=void 0,Oe(Object.keys(W))),Fe=ie.next();!Fe.done;Fe=ie.next()){var it=Fe.value,Ot=W[it];_===1&&(Ot=Ot.ds),Y.set(parseInt(it,10),Ah(Ot))}}catch(Pt){a={error:Pt}}finally{try{Fe&&!Fe.done&&(l=ie.return)&&l.call(ie)}finally{if(a)throw a.error}}b._index.set(H,Y)}}catch(Pt){o={error:Pt}}finally{try{L&&!L.done&&(s=R.return)&&s.call(R)}finally{if(o)throw o.error}}return b},t.prototype.executeQuery=function(e,r){var n=this;if(r===void 0&&(r={}),e===t.wildcard)return this.executeWildcardQuery(r);if(typeof e!="string"){var i=gt(gt(gt({},r),e),{queries:void 0}),o=e.queries.map(function(y){return n.executeQuery(y,i)});return this.combineResults(o,i.combineWith)}var s=this._options,a=s.tokenize,l=s.processTerm,c=s.searchOptions,u=gt(gt({tokenize:a,processTerm:l},c),r),d=u.tokenize,p=u.processTerm,f=d(e).flatMap(function(y){return p(y)}).filter(function(y){return!!y}),m=f.map(hL(u)),h=m.map(function(y){return n.executeQuerySpec(y,u)});return this.combineResults(h,u.combineWith)},t.prototype.executeQuerySpec=function(e,r){var n,i,o,s,a=gt(gt({},this._options.searchOptions),r),l=(a.fields||this._options.fields).reduce(function(it,Ot){var Pt;return gt(gt({},it),(Pt={},Pt[Ot]=vb(a.boost,Ot)||1,Pt))},{}),c=a.boostDocument,u=a.weights,d=a.maxFuzzy,p=a.bm25,f=gt(gt({},iP.weights),u),m=f.fuzzy,h=f.prefix,y=this._index.get(e.term),g=this.termResults(e.term,e.term,1,y,l,c,p),_,b;if(e.prefix&&(_=this._index.atPrefix(e.term)),e.fuzzy){var E=e.fuzzy===!0?.2:e.fuzzy,I=E<1?Math.min(d,Math.round(e.term.length*E)):E;I&&(b=this._index.fuzzyGet(e.term,I))}if(_)try{for(var P=Oe(_),M=P.next();!M.done;M=P.next()){var V=jt(M.value,2),R=V[0],L=V[1],G=R.length-e.term.length;if(G){b?.delete(R);var H=h*R.length/(R.length+.3*G);this.termResults(e.term,R,H,L,l,c,p,g)}}}catch(it){n={error:it}}finally{try{M&&!M.done&&(i=P.return)&&i.call(P)}finally{if(n)throw n.error}}if(b)try{for(var W=Oe(b.keys()),Y=W.next();!Y.done;Y=W.next()){var R=Y.value,ie=jt(b.get(R),2),Fe=ie[0],G=ie[1];if(G){var H=m*R.length/(R.length+G);this.termResults(e.term,R,H,Fe,l,c,p,g)}}}catch(it){o={error:it}}finally{try{Y&&!Y.done&&(s=W.return)&&s.call(W)}finally{if(o)throw o.error}}return g},t.prototype.executeWildcardQuery=function(e){var r,n,i=new Map,o=gt(gt({},this._options.searchOptions),e);try{for(var s=Oe(this._documentIds),a=s.next();!a.done;a=s.next()){var l=jt(a.value,2),c=l[0],u=l[1],d=o.boostDocument?o.boostDocument(u,"",this._storedFields.get(c)):1;i.set(c,{score:d,terms:[],match:{}})}}catch(p){r={error:p}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i},t.prototype.combineResults=function(e,r){if(r===void 0&&(r=Sb),e.length===0)return new Map;var n=r.toLowerCase();return e.reduce(fL[n])||new Map},t.prototype.toJSON=function(){var e,r,n,i,o=[];try{for(var s=Oe(this._index),a=s.next();!a.done;a=s.next()){var l=jt(a.value,2),c=l[0],u=l[1],d={};try{for(var p=(n=void 0,Oe(u)),f=p.next();!f.done;f=p.next()){var m=jt(f.value,2),h=m[0],y=m[1];d[h]=Object.fromEntries(y)}}catch(g){n={error:g}}finally{try{f&&!f.done&&(i=p.return)&&i.call(p)}finally{if(n)throw n.error}}o.push([c,d])}}catch(g){e={error:g}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.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}},t.prototype.termResults=function(e,r,n,i,o,s,a,l){var c,u,d,p,f;if(l===void 0&&(l=new Map),i==null)return l;try{for(var m=Oe(Object.keys(o)),h=m.next();!h.done;h=m.next()){var y=h.value,g=o[y],_=this._fieldIds[y],b=i.get(_);if(b!=null){var E=b.size,I=this._avgFieldLength[_];try{for(var P=(d=void 0,Oe(b.keys())),M=P.next();!M.done;M=P.next()){var V=M.value;if(!this._documentIds.has(V)){this.removeTerm(_,V,r),E-=1;continue}var R=s?s(this._documentIds.get(V),r,this._storedFields.get(V)):1;if(R){var L=b.get(V),G=this._fieldLength.get(V)[_],H=mL(L,E,this._documentCount,G,I,a),W=n*g*R*H,Y=l.get(V);if(Y){Y.score+=W,yL(Y.terms,e);var ie=vb(Y.match,r);ie?ie.push(y):Y.match[r]=[y]}else l.set(V,{score:W,terms:[e],match:(f={},f[r]=[y],f)})}}}catch(Fe){d={error:Fe}}finally{try{M&&!M.done&&(p=P.return)&&p.call(P)}finally{if(d)throw d.error}}}}}catch(Fe){c={error:Fe}}finally{try{h&&!h.done&&(u=m.return)&&u.call(m)}finally{if(c)throw c.error}}return l},t.prototype.addTerm=function(e,r,n){var i=this._index.fetch(n,aP),o=i.get(e);if(o==null)o=new Map,o.set(r,1),i.set(e,o);else{var s=o.get(r);o.set(r,(s||0)+1)}},t.prototype.removeTerm=function(e,r,n){if(!this._index.has(n)){this.warnDocumentChanged(r,e,n);return}var i=this._index.fetch(n,aP),o=i.get(e);o==null||o.get(r)==null?this.warnDocumentChanged(r,e,n):o.get(r)<=1?o.size<=1?i.delete(e):o.delete(r):o.set(r,o.get(r)-1),this._index.get(n).size===0&&this._index.delete(n)},t.prototype.warnDocumentChanged=function(e,r,n){var i,o;try{for(var s=Oe(Object.keys(this._fieldIds)),a=s.next();!a.done;a=s.next()){var l=a.value;if(this._fieldIds[l]===r){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(e),' has changed before removal: term "').concat(n,'" 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{a&&!a.done&&(o=s.return)&&o.call(s)}finally{if(i)throw i.error}}},t.prototype.addDocumentId=function(e){var r=this._nextId;return this._idToShortId.set(e,r),this._documentIds.set(r,e),this._documentCount+=1,this._nextId+=1,r},t.prototype.addFields=function(e){for(var r=0;r<e.length;r++)this._fieldIds[e[r]]=r},t.prototype.addFieldLength=function(e,r,n,i){var o=this._fieldLength.get(e);o==null&&this._fieldLength.set(e,o=[]),o[r]=i;var s=this._avgFieldLength[r]||0,a=s*n+i;this._avgFieldLength[r]=a/(n+1)},t.prototype.removeFieldLength=function(e,r,n,i){if(n===1){this._avgFieldLength[r]=0;return}var o=this._avgFieldLength[r]*n-i;this._avgFieldLength[r]=o/(n-1)},t.prototype.saveStoredFields=function(e,r){var n,i,o=this._options,s=o.storeFields,a=o.extractField;if(!(s==null||s.length===0)){var l=this._storedFields.get(e);l==null&&this._storedFields.set(e,l={});try{for(var c=Oe(s),u=c.next();!u.done;u=c.next()){var d=u.value,p=a(r,d);p!==void 0&&(l[d]=p)}}catch(f){n={error:f}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}}},t.wildcard=Symbol("*"),t}(),vb=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0},fL=(Ud={},Ud[Sb]=function(t,e){var r,n;try{for(var i=Oe(e.keys()),o=i.next();!o.done;o=i.next()){var s=o.value,a=t.get(s);if(a==null)t.set(s,e.get(s));else{var l=e.get(s),c=l.score,u=l.terms,d=l.match;a.score=a.score+c,a.match=Object.assign(a.match,d),oP(a.terms,u)}}}catch(p){r={error:p}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return t},Ud[pP]=function(t,e){var r,n,i=new Map;try{for(var o=Oe(e.keys()),s=o.next();!s.done;s=o.next()){var a=s.value,l=t.get(a);if(l!=null){var c=e.get(a),u=c.score,d=c.terms,p=c.match;oP(l.terms,d),i.set(a,{score:l.score+u,terms:l.terms,match:Object.assign(l.match,p)})}}}catch(f){r={error:f}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i},Ud[dL]=function(t,e){var r,n;try{for(var i=Oe(e.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;t.delete(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return t},Ud),pL={k:1.2,b:.7,d:.5},mL=function(t,e,r,n,i,o){var s=o.k,a=o.b,l=o.d,c=Math.log(1+(r-e+.5)/(e+.5));return c*(l+t*(s+1)/(t+s*(1-a+a*n/i)))},hL=function(t){return function(e,r,n){var i=typeof t.fuzzy=="function"?t.fuzzy(e,r,n):t.fuzzy||!1,o=typeof t.prefix=="function"?t.prefix(e,r,n):t.prefix===!0;return{term:e,fuzzy:i,prefix:o}}},_b={idField:"id",extractField:function(t,e){return t[e]},tokenize:function(t){return t.split(vL)},processTerm:function(t){return t.toLowerCase()},fields:void 0,searchOptions:void 0,storeFields:[],logger:function(t,e){typeof console?.[t]=="function"&&console[t](e)},autoVacuum:!0},iP={combineWith:Sb,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:pL},gL={combineWith:pP,prefix:function(t,e,r){return e===r.length-1}},xb={batchSize:1e3,batchWait:10},$b={minDirtFactor:.1,minDirtCount:20},bb=gt(gt({},xb),$b),yL=function(t,e){t.includes(e)||t.push(e)},oP=function(t,e){var r,n;try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;t.includes(s)||t.push(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},sP=function(t,e){var r=t.score,n=e.score;return n-r},aP=function(){return new Map},Ah=function(t){var e,r,n=new Map;try{for(var i=Oe(Object.keys(t)),o=i.next();!o.done;o=i.next()){var s=o.value;n.set(parseInt(s,10),t[s])}}catch(a){e={error:a}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n},vL=/[\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 hP=t=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,hideActionInUI:"after-complete",parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,r)=>{let n=await r.knowledgeBase.search(e.query),i=r;i._lastKBsearch=e.query,i._nextRequestUseKBitems=n;let o=n.filter(a=>a.type!="action").map(a=>"- "+a.name).join(`
|
|
65
|
+
Assistant:`;zt.DEFAULT_TIMEOUT=6e5;zt.AnthropicError=pe;zt.APIError=nr;zt.APIConnectionError=ns;zt.APIConnectionTimeoutError=oc;zt.APIUserAbortError=fr;zt.NotFoundError=cc;zt.ConflictError=uc;zt.RateLimitError=fc;zt.BadRequestError=sc;zt.AuthenticationError=ac;zt.InternalServerError=pc;zt.PermissionDeniedError=lc;zt.UnprocessableEntityError=dc;zt.toFile=uh;var Qn=class extends zt{constructor(){super(...arguments),this.completions=new ma(this),this.messages=new as(this),this.models=new ha(this),this.beta=new Ei(this)}};Qn.Completions=ma;Qn.Messages=as;Qn.Models=ha;Qn.Beta=Ei;var{HUMAN_PROMPT:iL,AI_PROMPT:oL}=Qn;var nP=new Ve("AnthropicChat"),Th=class extends ic{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}async sendMessage(e,r){this.addUserMessage(e);let n=new Qn({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),i=!0,o=[];for(;i;){i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),nP.debug("Before processing state",{messages:this.messageGroup.getAll().map(u=>u.data),tools:this.toolGroup.getAll().map(u=>u.data),context:this.contextGroup.getAll().map(u=>u.text)});let s=this.toolGroup.getAll().map(u=>({name:u.data?.name||"",description:u.data?.description||"",input_schema:{...u.data?.params,type:"object"}})),a;if(this.config.stream){let u=n.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(d=>d.data),tools:s,stream:!0});u.on("streamEvent",(d,p)=>{let f=this.parseMessageBlock(p);this.config.onAIMessage?.([...o,f],!0),r?.([...o,f])});try{a=await u.finalMessage()}catch(d){throw d?.error?.error?.message?d.error.error:d}}else try{a=await n.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(u=>u.data),tools:s})}catch(u){throw u?.error?.error?.message?u.error.error:u}if(nP.debug("Message received",a),a.content?.length){let u=this.messageGroup.add(this.parseMessageBlock(a));o.push(u)}let l=[],c=[];if(await Promise.all(a.content.map(async u=>{if(u.type!="tool_use")return;let d=this.findToolBySafeName(u.name);try{let p=await this.executeTool(d,u.input);c.push({type:"tool_result",tool_use_id:u.id,content:p}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolSuccessResponse:p,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}catch(p){let f=p?.message||"An unknown error occurred";c.push({type:"tool_result",tool_use_id:u.id,content:`Error performing tool call ${u.name}: ${f}`}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolErrorResponse:f,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}})),c.length>0){let u=this.messageGroup.add({id:"msg-"+dr(),sections:l,data:{role:"user",content:c}});o.push(u),i=!0,this.config.onAIMessage?.(o,!0),r?.(o)}this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return this.config.onAIMessage?.(o,!1),r?.(o),o}parseMessageBlock(e){let r=[];for(let n of e.content)if(n.type=="thinking")r.push({type:"thinking",text:n.thinking||""});else if(n.type=="text")r.push({type:"text",text:n.text||""});else if(n.type=="tool_use"){let i=this.findToolBySafeName(n.name);r.push({type:"tool_call",toolName:n.name,toolKbID:i?.kbItem?.id,toolKbName:i?.kbItem?.name,toolParameters:n.input,toolCallInstanceID:n.id,toolCallHiddenInUI:i?.kbItem?.hideActionInUI})}return{id:e.id,data:{role:e.role,content:e.content},sections:r,source:"assistant",usage:{inputTokens:e.usage?.input_tokens||0,outputTokens:e.usage?.output_tokens||0,cachedInputTokens:e.usage?.cache_read_input_tokens||0,totalTokens:(e.usage?.input_tokens||0)+(e.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};var gt=function(){return gt=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},gt.apply(this,arguments)};function sL(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function a(u){try{c(n.next(u))}catch(d){s(d)}}function l(u){try{c(n.throw(u))}catch(d){s(d)}}function c(u){u.done?o(u.value):i(u.value).then(a,l)}c((n=n.apply(t,e||[])).next())})}function aL(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(r=0)),r;)try{if(n=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 r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){r.label=c[1];break}if(c[0]===6&&r.label<o[1]){r.label=o[1],o=c;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(c);break}o[2]&&r.ops.pop(),r.trys.pop();continue}c=e.call(t,r)}catch(u){c=[6,u],i=0}finally{n=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function Oe(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function jt(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}var lL="ENTRIES",lP="KEYS",cP="VALUES",pr="",hb=function(){function t(e,r){var n=e._tree,i=Array.from(n.keys());this.set=e,this._type=r,this._path=i.length>0?[{node:n,keys:i}]:[]}return t.prototype.next=function(){var e=this.dive();return this.backtrack(),e},t.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var e=xc(this._path),r=e.node,n=e.keys;if(xc(n)===pr)return{done:!1,value:this.result()};var i=r.get(xc(n));return this._path.push({node:i,keys:Array.from(i.keys())}),this.dive()},t.prototype.backtrack=function(){if(this._path.length!==0){var e=xc(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}},t.prototype.key=function(){return this.set._prefix+this._path.map(function(e){var r=e.keys;return xc(r)}).filter(function(e){return e!==pr}).join("")},t.prototype.value=function(){return xc(this._path).node.get(pr)},t.prototype.result=function(){switch(this._type){case cP:return this.value();case lP:return this.key();default:return[this.key(),this.value()]}},t.prototype[Symbol.iterator]=function(){return this},t}(),xc=function(t){return t[t.length-1]},cL=function(t,e,r){var n=new Map;if(e===void 0)return n;for(var i=e.length+1,o=i+r,s=new Uint8Array(o*i).fill(r+1),a=0;a<i;++a)s[a]=a;for(var l=1;l<o;++l)s[l*i]=l;return uP(t,e,r,n,s,1,i,""),n},uP=function(t,e,r,n,i,o,s,a){var l,c,u=o*s;try{e:for(var d=Oe(t.keys()),p=d.next();!p.done;p=d.next()){var f=p.value;if(f===pr){var m=i[u-1];m<=r&&n.set(a,[t.get(f),m])}else{for(var h=o,y=0;y<f.length;++y,++h){for(var g=f[y],_=s*h,b=_-s,E=i[_],I=Math.max(0,h-r-1),P=Math.min(s-1,h+r),M=I;M<P;++M){var V=g!==e[M],R=i[b+M]+ +V,L=i[b+M+1]+1,G=i[_+M]+1,H=i[_+M+1]=Math.min(R,L,G);H<E&&(E=H)}if(E>r)continue e}uP(t.get(f),e,r,n,i,h,s,a+f)}}}catch(W){l={error:W}}finally{try{p&&!p.done&&(c=d.return)&&c.call(d)}finally{if(l)throw l.error}}},gb=function(){function t(e,r){e===void 0&&(e=new Map),r===void 0&&(r=""),this._size=void 0,this._tree=e,this._prefix=r}return t.prototype.atPrefix=function(e){var r,n;if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");var i=jt(zh(this._tree,e.slice(this._prefix.length)),2),o=i[0],s=i[1];if(o===void 0){var a=jt(kb(s),2),l=a[0],c=a[1];try{for(var u=Oe(l.keys()),d=u.next();!d.done;d=u.next()){var p=d.value;if(p!==pr&&p.startsWith(c)){var f=new Map;return f.set(p.slice(c.length),l.get(p)),new t(f,e)}}}catch(m){r={error:m}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}}return new t(o,e)},t.prototype.clear=function(){this._size=void 0,this._tree.clear()},t.prototype.delete=function(e){return this._size=void 0,uL(this._tree,e)},t.prototype.entries=function(){return new hb(this,lL)},t.prototype.forEach=function(e){var r,n;try{for(var i=Oe(this),o=i.next();!o.done;o=i.next()){var s=jt(o.value,2),a=s[0],l=s[1];e(a,l,this)}}catch(c){r={error:c}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.fuzzyGet=function(e,r){return cL(this._tree,e,r)},t.prototype.get=function(e){var r=wb(this._tree,e);return r!==void 0?r.get(pr):void 0},t.prototype.has=function(e){var r=wb(this._tree,e);return r!==void 0&&r.has(pr)},t.prototype.keys=function(){return new hb(this,lP)},t.prototype.set=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=yb(this._tree,e);return n.set(pr,r),this},Object.defineProperty(t.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var e=this.entries();!e.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),t.prototype.update=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=yb(this._tree,e);return n.set(pr,r(n.get(pr))),this},t.prototype.fetch=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=yb(this._tree,e),i=n.get(pr);return i===void 0&&n.set(pr,i=r()),i},t.prototype.values=function(){return new hb(this,cP)},t.prototype[Symbol.iterator]=function(){return this.entries()},t.from=function(e){var r,n,i=new t;try{for(var o=Oe(e),s=o.next();!s.done;s=o.next()){var a=jt(s.value,2),l=a[0],c=a[1];i.set(l,c)}}catch(u){r={error:u}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i},t.fromObject=function(e){return t.from(Object.entries(e))},t}(),zh=function(t,e,r){var n,i;if(r===void 0&&(r=[]),e.length===0||t==null)return[t,r];try{for(var o=Oe(t.keys()),s=o.next();!s.done;s=o.next()){var a=s.value;if(a!==pr&&e.startsWith(a))return r.push([t,a]),zh(t.get(a),e.slice(a.length),r)}}catch(l){n={error:l}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return r.push([t,e]),zh(void 0,"",r)},wb=function(t,e){var r,n;if(e.length===0||t==null)return t;try{for(var i=Oe(t.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;if(s!==pr&&e.startsWith(s))return wb(t.get(s),e.slice(s.length))}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},yb=function(t,e){var r,n,i=e.length;e:for(var o=0;t&&o<i;){try{for(var s=(r=void 0,Oe(t.keys())),a=s.next();!a.done;a=s.next()){var l=a.value;if(l!==pr&&e[o]===l[0]){for(var c=Math.min(i-o,l.length),u=1;u<c&&e[o+u]===l[u];)++u;var d=t.get(l);if(u===l.length)t=d;else{var p=new Map;p.set(l.slice(u),d),t.set(e.slice(o,o+u),p),t.delete(l),t=p}o+=u;continue e}}}catch(m){r={error:m}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}var f=new Map;return t.set(e.slice(o),f),f}return t},uL=function(t,e){var r=jt(zh(t,e),2),n=r[0],i=r[1];if(n!==void 0){if(n.delete(pr),n.size===0)dP(i);else if(n.size===1){var o=jt(n.entries().next().value,2),s=o[0],a=o[1];fP(i,s,a)}}},dP=function(t){if(t.length!==0){var e=jt(kb(t),2),r=e[0],n=e[1];if(r.delete(n),r.size===0)dP(t.slice(0,-1));else if(r.size===1){var i=jt(r.entries().next().value,2),o=i[0],s=i[1];o!==pr&&fP(t.slice(0,-1),o,s)}}},fP=function(t,e,r){if(t.length!==0){var n=jt(kb(t),2),i=n[0],o=n[1];i.set(o+e,r),i.delete(o)}},kb=function(t){return t[t.length-1]},Ud,Sb="or",pP="and",dL="and_not",mP=function(){function t(e){if(e?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');var r=e.autoVacuum==null||e.autoVacuum===!0?bb:e.autoVacuum;this._options=gt(gt(gt({},_b),e),{autoVacuum:r,searchOptions:gt(gt({},iP),e.searchOptions||{}),autoSuggestOptions:gt(gt({},gL),e.autoSuggestOptions||{})}),this._index=new gb,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=$b,this.addFields(this._options.fields)}return t.prototype.add=function(e){var r,n,i,o,s,a,l=this._options,c=l.extractField,u=l.tokenize,d=l.processTerm,p=l.fields,f=l.idField,m=c(e,f);if(m==null)throw new Error('MiniSearch: document does not have ID field "'.concat(f,'"'));if(this._idToShortId.has(m))throw new Error("MiniSearch: duplicate ID ".concat(m));var h=this.addDocumentId(m);this.saveStoredFields(h,e);try{for(var y=Oe(p),g=y.next();!g.done;g=y.next()){var _=g.value,b=c(e,_);if(b!=null){var E=u(b.toString(),_),I=this._fieldIds[_],P=new Set(E).size;this.addFieldLength(h,I,this._documentCount-1,P);try{for(var M=(i=void 0,Oe(E)),V=M.next();!V.done;V=M.next()){var R=V.value,L=d(R,_);if(Array.isArray(L))try{for(var G=(s=void 0,Oe(L)),H=G.next();!H.done;H=G.next()){var W=H.value;this.addTerm(I,h,W)}}catch(Y){s={error:Y}}finally{try{H&&!H.done&&(a=G.return)&&a.call(G)}finally{if(s)throw s.error}}else L&&this.addTerm(I,h,L)}}catch(Y){i={error:Y}}finally{try{V&&!V.done&&(o=M.return)&&o.call(M)}finally{if(i)throw i.error}}}}}catch(Y){r={error:Y}}finally{try{g&&!g.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}},t.prototype.addAll=function(e){var r,n;try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;this.add(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.addAllAsync=function(e,r){var n=this;r===void 0&&(r={});var i=r.chunkSize,o=i===void 0?10:i,s={chunk:[],promise:Promise.resolve()},a=e.reduce(function(u,d,p){var f=u.chunk,m=u.promise;return f.push(d),(p+1)%o===0?{chunk:[],promise:m.then(function(){return new Promise(function(h){return setTimeout(h,0)})}).then(function(){return n.addAll(f)})}:{chunk:f,promise:m}},s),l=a.chunk,c=a.promise;return c.then(function(){return n.addAll(l)})},t.prototype.remove=function(e){var r,n,i,o,s,a,l=this._options,c=l.tokenize,u=l.processTerm,d=l.extractField,p=l.fields,f=l.idField,m=d(e,f);if(m==null)throw new Error('MiniSearch: document does not have ID field "'.concat(f,'"'));var h=this._idToShortId.get(m);if(h==null)throw new Error("MiniSearch: cannot remove document with ID ".concat(m,": it is not in the index"));try{for(var y=Oe(p),g=y.next();!g.done;g=y.next()){var _=g.value,b=d(e,_);if(b!=null){var E=c(b.toString(),_),I=this._fieldIds[_],P=new Set(E).size;this.removeFieldLength(h,I,this._documentCount,P);try{for(var M=(i=void 0,Oe(E)),V=M.next();!V.done;V=M.next()){var R=V.value,L=u(R,_);if(Array.isArray(L))try{for(var G=(s=void 0,Oe(L)),H=G.next();!H.done;H=G.next()){var W=H.value;this.removeTerm(I,h,W)}}catch(Y){s={error:Y}}finally{try{H&&!H.done&&(a=G.return)&&a.call(G)}finally{if(s)throw s.error}}else L&&this.removeTerm(I,h,L)}}catch(Y){i={error:Y}}finally{try{V&&!V.done&&(o=M.return)&&o.call(M)}finally{if(i)throw i.error}}}}}catch(Y){r={error:Y}}finally{try{g&&!g.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}this._storedFields.delete(h),this._documentIds.delete(h),this._idToShortId.delete(m),this._fieldLength.delete(h),this._documentCount-=1},t.prototype.removeAll=function(e){var r,n;if(e)try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;this.remove(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new gb,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},t.prototype.discard=function(e){var r=this,n=this._idToShortId.get(e);if(n==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(e,": it is not in the index"));this._idToShortId.delete(e),this._documentIds.delete(n),this._storedFields.delete(n),(this._fieldLength.get(n)||[]).forEach(function(i,o){r.removeFieldLength(n,o,r._documentCount,i)}),this._fieldLength.delete(n),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},t.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var e=this._options.autoVacuum,r=e.minDirtFactor,n=e.minDirtCount,i=e.batchSize,o=e.batchWait;this.conditionalVacuum({batchSize:i,batchWait:o},{minDirtCount:n,minDirtFactor:r})}},t.prototype.discardAll=function(e){var r,n,i=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var o=Oe(e),s=o.next();!s.done;s=o.next()){var a=s.value;this.discard(a)}}catch(l){r={error:l}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}}finally{this._options.autoVacuum=i}this.maybeAutoVacuum()},t.prototype.replace=function(e){var r=this._options,n=r.idField,i=r.extractField,o=i(e,n);this.discard(o),this.add(e)},t.prototype.vacuum=function(e){return e===void 0&&(e={}),this.conditionalVacuum(e)},t.prototype.conditionalVacuum=function(e,r){var n=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&r,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var i=n._enqueuedVacuumConditions;return n._enqueuedVacuumConditions=$b,n.performVacuuming(e,i)}),this._enqueuedVacuum)):this.vacuumConditionsMet(r)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)},t.prototype.performVacuuming=function(e,r){return sL(this,void 0,void 0,function(){var n,i,o,s,a,l,c,u,d,p,f,m,h,y,g,_,b,E,I,P,M,V,R,L,G;return aL(this,function(H){switch(H.label){case 0:if(n=this._dirtCount,!this.vacuumConditionsMet(r))return[3,10];i=e.batchSize||xb.batchSize,o=e.batchWait||xb.batchWait,s=1,H.label=1;case 1:H.trys.push([1,7,8,9]),a=Oe(this._index),l=a.next(),H.label=2;case 2:if(l.done)return[3,6];c=jt(l.value,2),u=c[0],d=c[1];try{for(p=(V=void 0,Oe(d)),f=p.next();!f.done;f=p.next()){m=jt(f.value,2),h=m[0],y=m[1];try{for(g=(L=void 0,Oe(y)),_=g.next();!_.done;_=g.next())b=jt(_.value,1),E=b[0],!this._documentIds.has(E)&&(y.size<=1?d.delete(h):y.delete(E))}catch(W){L={error:W}}finally{try{_&&!_.done&&(G=g.return)&&G.call(g)}finally{if(L)throw L.error}}}}catch(W){V={error:W}}finally{try{f&&!f.done&&(R=p.return)&&R.call(p)}finally{if(V)throw V.error}}return this._index.get(u).size===0&&this._index.delete(u),s%i!==0?[3,4]:[4,new Promise(function(W){return setTimeout(W,o)})];case 3:H.sent(),H.label=4;case 4:s+=1,H.label=5;case 5:return l=a.next(),[3,2];case 6:return[3,9];case 7:return I=H.sent(),P={error:I},[3,9];case 8:try{l&&!l.done&&(M=a.return)&&M.call(a)}finally{if(P)throw P.error}return[7];case 9:this._dirtCount-=n,H.label=10;case 10:return[4,null];case 11:return H.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},t.prototype.vacuumConditionsMet=function(e){if(e==null)return!0;var r=e.minDirtCount,n=e.minDirtFactor;return r=r||bb.minDirtCount,n=n||bb.minDirtFactor,this.dirtCount>=r&&this.dirtFactor>=n},Object.defineProperty(t.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),t.prototype.has=function(e){return this._idToShortId.has(e)},t.prototype.getStoredFields=function(e){var r=this._idToShortId.get(e);if(r!=null)return this._storedFields.get(r)},t.prototype.search=function(e,r){var n,i;r===void 0&&(r={});var o=this.executeQuery(e,r),s=[];try{for(var a=Oe(o),l=a.next();!l.done;l=a.next()){var c=jt(l.value,2),u=c[0],d=c[1],p=d.score,f=d.terms,m=d.match,h=f.length||1,y={id:this._documentIds.get(u),score:p*h,terms:Object.keys(m),queryTerms:f,match:m};Object.assign(y,this._storedFields.get(u)),(r.filter==null||r.filter(y))&&s.push(y)}}catch(g){n={error:g}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}return e===t.wildcard&&r.boostDocument==null&&this._options.searchOptions.boostDocument==null||s.sort(sP),s},t.prototype.autoSuggest=function(e,r){var n,i,o,s;r===void 0&&(r={}),r=gt(gt({},this._options.autoSuggestOptions),r);var a=new Map;try{for(var l=Oe(this.search(e,r)),c=l.next();!c.done;c=l.next()){var u=c.value,d=u.score,p=u.terms,f=p.join(" "),m=a.get(f);m!=null?(m.score+=d,m.count+=1):a.set(f,{score:d,terms:p,count:1})}}catch(I){n={error:I}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}var h=[];try{for(var y=Oe(a),g=y.next();!g.done;g=y.next()){var _=jt(g.value,2),m=_[0],b=_[1],d=b.score,p=b.terms,E=b.count;h.push({suggestion:m,terms:p,score:d/E})}}catch(I){o={error:I}}finally{try{g&&!g.done&&(s=y.return)&&s.call(y)}finally{if(o)throw o.error}}return h.sort(sP),h},Object.defineProperty(t.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),t.loadJSON=function(e,r){if(r==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(e),r)},t.getDefault=function(e){if(_b.hasOwnProperty(e))return vb(_b,e);throw new Error('MiniSearch: unknown option "'.concat(e,'"'))},t.loadJS=function(e,r){var n,i,o,s,a,l,c=e.index,u=e.documentCount,d=e.nextId,p=e.documentIds,f=e.fieldIds,m=e.fieldLength,h=e.averageFieldLength,y=e.storedFields,g=e.dirtCount,_=e.serializationVersion;if(_!==1&&_!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var b=new t(r);b._documentCount=u,b._nextId=d,b._documentIds=Ah(p),b._idToShortId=new Map,b._fieldIds=f,b._fieldLength=Ah(m),b._avgFieldLength=h,b._storedFields=Ah(y),b._dirtCount=g||0,b._index=new gb;try{for(var E=Oe(b._documentIds),I=E.next();!I.done;I=E.next()){var P=jt(I.value,2),M=P[0],V=P[1];b._idToShortId.set(V,M)}}catch(Pt){n={error:Pt}}finally{try{I&&!I.done&&(i=E.return)&&i.call(E)}finally{if(n)throw n.error}}try{for(var R=Oe(c),L=R.next();!L.done;L=R.next()){var G=jt(L.value,2),H=G[0],W=G[1],Y=new Map;try{for(var ie=(a=void 0,Oe(Object.keys(W))),Fe=ie.next();!Fe.done;Fe=ie.next()){var it=Fe.value,Ot=W[it];_===1&&(Ot=Ot.ds),Y.set(parseInt(it,10),Ah(Ot))}}catch(Pt){a={error:Pt}}finally{try{Fe&&!Fe.done&&(l=ie.return)&&l.call(ie)}finally{if(a)throw a.error}}b._index.set(H,Y)}}catch(Pt){o={error:Pt}}finally{try{L&&!L.done&&(s=R.return)&&s.call(R)}finally{if(o)throw o.error}}return b},t.prototype.executeQuery=function(e,r){var n=this;if(r===void 0&&(r={}),e===t.wildcard)return this.executeWildcardQuery(r);if(typeof e!="string"){var i=gt(gt(gt({},r),e),{queries:void 0}),o=e.queries.map(function(y){return n.executeQuery(y,i)});return this.combineResults(o,i.combineWith)}var s=this._options,a=s.tokenize,l=s.processTerm,c=s.searchOptions,u=gt(gt({tokenize:a,processTerm:l},c),r),d=u.tokenize,p=u.processTerm,f=d(e).flatMap(function(y){return p(y)}).filter(function(y){return!!y}),m=f.map(hL(u)),h=m.map(function(y){return n.executeQuerySpec(y,u)});return this.combineResults(h,u.combineWith)},t.prototype.executeQuerySpec=function(e,r){var n,i,o,s,a=gt(gt({},this._options.searchOptions),r),l=(a.fields||this._options.fields).reduce(function(it,Ot){var Pt;return gt(gt({},it),(Pt={},Pt[Ot]=vb(a.boost,Ot)||1,Pt))},{}),c=a.boostDocument,u=a.weights,d=a.maxFuzzy,p=a.bm25,f=gt(gt({},iP.weights),u),m=f.fuzzy,h=f.prefix,y=this._index.get(e.term),g=this.termResults(e.term,e.term,1,y,l,c,p),_,b;if(e.prefix&&(_=this._index.atPrefix(e.term)),e.fuzzy){var E=e.fuzzy===!0?.2:e.fuzzy,I=E<1?Math.min(d,Math.round(e.term.length*E)):E;I&&(b=this._index.fuzzyGet(e.term,I))}if(_)try{for(var P=Oe(_),M=P.next();!M.done;M=P.next()){var V=jt(M.value,2),R=V[0],L=V[1],G=R.length-e.term.length;if(G){b?.delete(R);var H=h*R.length/(R.length+.3*G);this.termResults(e.term,R,H,L,l,c,p,g)}}}catch(it){n={error:it}}finally{try{M&&!M.done&&(i=P.return)&&i.call(P)}finally{if(n)throw n.error}}if(b)try{for(var W=Oe(b.keys()),Y=W.next();!Y.done;Y=W.next()){var R=Y.value,ie=jt(b.get(R),2),Fe=ie[0],G=ie[1];if(G){var H=m*R.length/(R.length+G);this.termResults(e.term,R,H,Fe,l,c,p,g)}}}catch(it){o={error:it}}finally{try{Y&&!Y.done&&(s=W.return)&&s.call(W)}finally{if(o)throw o.error}}return g},t.prototype.executeWildcardQuery=function(e){var r,n,i=new Map,o=gt(gt({},this._options.searchOptions),e);try{for(var s=Oe(this._documentIds),a=s.next();!a.done;a=s.next()){var l=jt(a.value,2),c=l[0],u=l[1],d=o.boostDocument?o.boostDocument(u,"",this._storedFields.get(c)):1;i.set(c,{score:d,terms:[],match:{}})}}catch(p){r={error:p}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i},t.prototype.combineResults=function(e,r){if(r===void 0&&(r=Sb),e.length===0)return new Map;var n=r.toLowerCase();return e.reduce(fL[n])||new Map},t.prototype.toJSON=function(){var e,r,n,i,o=[];try{for(var s=Oe(this._index),a=s.next();!a.done;a=s.next()){var l=jt(a.value,2),c=l[0],u=l[1],d={};try{for(var p=(n=void 0,Oe(u)),f=p.next();!f.done;f=p.next()){var m=jt(f.value,2),h=m[0],y=m[1];d[h]=Object.fromEntries(y)}}catch(g){n={error:g}}finally{try{f&&!f.done&&(i=p.return)&&i.call(p)}finally{if(n)throw n.error}}o.push([c,d])}}catch(g){e={error:g}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.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}},t.prototype.termResults=function(e,r,n,i,o,s,a,l){var c,u,d,p,f;if(l===void 0&&(l=new Map),i==null)return l;try{for(var m=Oe(Object.keys(o)),h=m.next();!h.done;h=m.next()){var y=h.value,g=o[y],_=this._fieldIds[y],b=i.get(_);if(b!=null){var E=b.size,I=this._avgFieldLength[_];try{for(var P=(d=void 0,Oe(b.keys())),M=P.next();!M.done;M=P.next()){var V=M.value;if(!this._documentIds.has(V)){this.removeTerm(_,V,r),E-=1;continue}var R=s?s(this._documentIds.get(V),r,this._storedFields.get(V)):1;if(R){var L=b.get(V),G=this._fieldLength.get(V)[_],H=mL(L,E,this._documentCount,G,I,a),W=n*g*R*H,Y=l.get(V);if(Y){Y.score+=W,yL(Y.terms,e);var ie=vb(Y.match,r);ie?ie.push(y):Y.match[r]=[y]}else l.set(V,{score:W,terms:[e],match:(f={},f[r]=[y],f)})}}}catch(Fe){d={error:Fe}}finally{try{M&&!M.done&&(p=P.return)&&p.call(P)}finally{if(d)throw d.error}}}}}catch(Fe){c={error:Fe}}finally{try{h&&!h.done&&(u=m.return)&&u.call(m)}finally{if(c)throw c.error}}return l},t.prototype.addTerm=function(e,r,n){var i=this._index.fetch(n,aP),o=i.get(e);if(o==null)o=new Map,o.set(r,1),i.set(e,o);else{var s=o.get(r);o.set(r,(s||0)+1)}},t.prototype.removeTerm=function(e,r,n){if(!this._index.has(n)){this.warnDocumentChanged(r,e,n);return}var i=this._index.fetch(n,aP),o=i.get(e);o==null||o.get(r)==null?this.warnDocumentChanged(r,e,n):o.get(r)<=1?o.size<=1?i.delete(e):o.delete(r):o.set(r,o.get(r)-1),this._index.get(n).size===0&&this._index.delete(n)},t.prototype.warnDocumentChanged=function(e,r,n){var i,o;try{for(var s=Oe(Object.keys(this._fieldIds)),a=s.next();!a.done;a=s.next()){var l=a.value;if(this._fieldIds[l]===r){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(e),' has changed before removal: term "').concat(n,'" 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{a&&!a.done&&(o=s.return)&&o.call(s)}finally{if(i)throw i.error}}},t.prototype.addDocumentId=function(e){var r=this._nextId;return this._idToShortId.set(e,r),this._documentIds.set(r,e),this._documentCount+=1,this._nextId+=1,r},t.prototype.addFields=function(e){for(var r=0;r<e.length;r++)this._fieldIds[e[r]]=r},t.prototype.addFieldLength=function(e,r,n,i){var o=this._fieldLength.get(e);o==null&&this._fieldLength.set(e,o=[]),o[r]=i;var s=this._avgFieldLength[r]||0,a=s*n+i;this._avgFieldLength[r]=a/(n+1)},t.prototype.removeFieldLength=function(e,r,n,i){if(n===1){this._avgFieldLength[r]=0;return}var o=this._avgFieldLength[r]*n-i;this._avgFieldLength[r]=o/(n-1)},t.prototype.saveStoredFields=function(e,r){var n,i,o=this._options,s=o.storeFields,a=o.extractField;if(!(s==null||s.length===0)){var l=this._storedFields.get(e);l==null&&this._storedFields.set(e,l={});try{for(var c=Oe(s),u=c.next();!u.done;u=c.next()){var d=u.value,p=a(r,d);p!==void 0&&(l[d]=p)}}catch(f){n={error:f}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}}},t.wildcard=Symbol("*"),t}(),vb=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0},fL=(Ud={},Ud[Sb]=function(t,e){var r,n;try{for(var i=Oe(e.keys()),o=i.next();!o.done;o=i.next()){var s=o.value,a=t.get(s);if(a==null)t.set(s,e.get(s));else{var l=e.get(s),c=l.score,u=l.terms,d=l.match;a.score=a.score+c,a.match=Object.assign(a.match,d),oP(a.terms,u)}}}catch(p){r={error:p}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return t},Ud[pP]=function(t,e){var r,n,i=new Map;try{for(var o=Oe(e.keys()),s=o.next();!s.done;s=o.next()){var a=s.value,l=t.get(a);if(l!=null){var c=e.get(a),u=c.score,d=c.terms,p=c.match;oP(l.terms,d),i.set(a,{score:l.score+u,terms:l.terms,match:Object.assign(l.match,p)})}}}catch(f){r={error:f}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i},Ud[dL]=function(t,e){var r,n;try{for(var i=Oe(e.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;t.delete(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return t},Ud),pL={k:1.2,b:.7,d:.5},mL=function(t,e,r,n,i,o){var s=o.k,a=o.b,l=o.d,c=Math.log(1+(r-e+.5)/(e+.5));return c*(l+t*(s+1)/(t+s*(1-a+a*n/i)))},hL=function(t){return function(e,r,n){var i=typeof t.fuzzy=="function"?t.fuzzy(e,r,n):t.fuzzy||!1,o=typeof t.prefix=="function"?t.prefix(e,r,n):t.prefix===!0;return{term:e,fuzzy:i,prefix:o}}},_b={idField:"id",extractField:function(t,e){return t[e]},tokenize:function(t){return t.split(vL)},processTerm:function(t){return t.toLowerCase()},fields:void 0,searchOptions:void 0,storeFields:[],logger:function(t,e){typeof console?.[t]=="function"&&console[t](e)},autoVacuum:!0},iP={combineWith:Sb,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:pL},gL={combineWith:pP,prefix:function(t,e,r){return e===r.length-1}},xb={batchSize:1e3,batchWait:10},$b={minDirtFactor:.1,minDirtCount:20},bb=gt(gt({},xb),$b),yL=function(t,e){t.includes(e)||t.push(e)},oP=function(t,e){var r,n;try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;t.includes(s)||t.push(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},sP=function(t,e){var r=t.score,n=e.score;return n-r},aP=function(){return new Map},Ah=function(t){var e,r,n=new Map;try{for(var i=Oe(Object.keys(t)),o=i.next();!o.done;o=i.next()){var s=o.value;n.set(parseInt(s,10),t[s])}}catch(a){e={error:a}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n},vL=/[\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 hP=t=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,hideActionInUI:"after-complete",parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,r)=>{let n=await r.knowledgeBase.search(e.query),i=r;i._lastKBsearch=e.query,i._nextRequestUseKBitems=n;let o=n.filter(a=>a.type!="action").map(a=>"- "+a.name).join(`
|
|
66
66
|
`)||"- (none)",s=n.filter(a=>a.type=="action").map(a=>"- "+a._functionID).join(`
|
|
67
67
|
`)||"- (none)";return`Search complete, context has been updated.
|
|
68
68
|
New information found:
|
|
@@ -92,7 +92,7 @@ ${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"ope
|
|
|
92
92
|
`;break;case"id":a=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new qy(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:g}));break;default:r(new qy(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:y,line:g}));break}}function f(){l.length>0&&e({id:a,event:c||void 0,data:l.endsWith(`
|
|
93
93
|
`)?l.slice(0,-1):l}),a=void 0,l="",c=""}function m(h={}){o&&h.consume&&d(o),s=!0,a=void 0,l="",c="",o=""}return{feed:u,reset:m}}function n8(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
|
|
94
94
|
`,n),s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?s=i:o!==-1&&(s=o),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
|
|
95
|
-
`&&n++}}return[e,r]}var By=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=Wy({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var i8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},As=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Gy=class{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Vy(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:i8}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i,o;let{resumptionToken:s}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);let l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new As(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{var u,d,p,f;try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new By({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:_}=await m.read();if(_)break;if(g.id&&(s=g.id,a=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let b=Gc.parse(JSON.parse(g.data));ka(b)&&(l=!0,o!==void 0&&(b.id=o)),(u=this.onmessage)===null||u===void 0||u.call(this,b)}catch(b){(d=this.onerror)===null||d===void 0||d.call(this,b)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(m){if((p=this.onerror)===null||p===void 0||p.call(this,new Error(`SSE stream disconnected: ${m}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(g){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s,a,l,c;try{let{resumptionToken:u,onresumptiontoken:d}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:df(e)?e.id:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let p=await this._commonHeaders();p.set("content-type","application/json"),p.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:p,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},m=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,f),h=m.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!m.ok){let b=await m.text().catch(()=>null);if(m.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new As(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:I}=Su(m);if(this._resourceMetadataUrl=E,this._scope=I,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this._hasCompletedAuthFlow=!0,this.send(e)}if(m.status===403&&this._authProvider){let{resourceMetadataUrl:E,scope:I,error:P}=Su(m);if(P==="insufficient_scope"){let M=m.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new As(403,"Server returned 403 after trying upscoping");if(I&&(this._scope=I),E&&(this._resourceMetadataUrl=E),this._lastUpscopingHeader=M??void 0,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Br;return this.send(e)}}throw new As(m.status,`Error POSTing to endpoint: ${b}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,m.status===202){await((o=m.body)===null||o===void 0?void 0:o.cancel()),WA(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let g=(Array.isArray(e)?e:[e]).filter(b=>"method"in b&&"id"in b&&b.id!==void 0).length>0,_=m.headers.get("content-type");if(g)if(_?.includes("text/event-stream"))this._handleSseStream(m.body,{onresumptiontoken:d},!1);else if(_?.includes("application/json")){let b=await m.json(),E=Array.isArray(b)?b.map(I=>Gc.parse(I)):[Gc.parse(b)];for(let I of E)(s=this.onmessage)===null||s===void 0||s.call(this,I)}else throw await((a=m.body)===null||a===void 0?void 0:a.cancel()),new As(-1,`Unexpected content type: ${_}`);else await((l=m.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n,i;if(this._sessionId)try{let o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(await((n=a.body)===null||n===void 0?void 0:n.cancel()),!a.ok&&a.status!==405)throw new As(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Xy=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(vM(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(vM(this),r)}};function o8(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function BS(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(BS).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${BS(t.cause)}`:t.message:`${t}`}function vM(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var bM=t=>{throw TypeError(t)},eI=(t,e,r)=>e.has(t)||bM("Cannot "+r),Ze=(t,e,r)=>(eI(t,e,"read from private field"),r?r.call(t):e.get(t)),er=(t,e,r)=>e.has(t)?bM("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Et=(t,e,r,n)=>(eI(t,e,"write to private field"),e.set(t,r),r),Co=(t,e,r)=>(eI(t,e,"access private method"),r),ln,Ja,Iu,Hy,Ky,jp,Tu,Dp,zs,Eu,Au,Pu,Rp,hi,GS,HS,XS,_M,KS,JS,Mp,YS,QS,Ya=class extends EventTarget{constructor(e,r){var n,i;super(),er(this,hi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,er(this,ln),er(this,Ja),er(this,Iu),er(this,Hy),er(this,Ky),er(this,jp),er(this,Tu),er(this,Dp,null),er(this,zs),er(this,Eu),er(this,Au,null),er(this,Pu,null),er(this,Rp,null),er(this,HS,async o=>{var s;Ze(this,Eu).reset();let{body:a,redirected:l,status:c,headers:u}=o;if(c===204){Co(this,hi,Mp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Et(this,Iu,new URL(o.url)):Et(this,Iu,void 0),c!==200){Co(this,hi,Mp).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Co(this,hi,Mp).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.OPEN);let d=new Event("open");if((s=Ze(this,Rp))==null||s.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){Co(this,hi,Mp).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let p=new TextDecoder,f=a.getReader(),m=!0;do{let{done:h,value:y}=await f.read();y&&Ze(this,Eu).feed(p.decode(y,{stream:!h})),h&&(m=!1,Ze(this,Eu).reset(),Co(this,hi,YS).call(this))}while(m)}),er(this,XS,o=>{Et(this,zs,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Co(this,hi,YS).call(this,BS(o))}),er(this,KS,o=>{typeof o.id=="string"&&Et(this,Dp,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Ze(this,Iu)?Ze(this,Iu).origin:Ze(this,Ja).origin,lastEventId:o.id||""});Ze(this,Pu)&&(!o.event||o.event==="message")&&Ze(this,Pu).call(this,s),this.dispatchEvent(s)}),er(this,JS,o=>{Et(this,jp,o)}),er(this,QS,()=>{Et(this,Tu,void 0),Ze(this,ln)===this.CONNECTING&&Co(this,hi,GS).call(this)});try{if(e instanceof URL)Et(this,Ja,e);else if(typeof e=="string")Et(this,Ja,new URL(e,s8()));else throw new Error("Invalid URL")}catch{throw o8("An invalid or illegal string was specified")}Et(this,Eu,Wy({onEvent:Ze(this,KS),onRetry:Ze(this,JS)})),Et(this,ln,this.CONNECTING),Et(this,jp,3e3),Et(this,Ky,(n=r?.fetch)!=null?n:globalThis.fetch),Et(this,Hy,(i=r?.withCredentials)!=null?i:!1),Co(this,hi,GS).call(this)}get readyState(){return Ze(this,ln)}get url(){return Ze(this,Ja).href}get withCredentials(){return Ze(this,Hy)}get onerror(){return Ze(this,Au)}set onerror(e){Et(this,Au,e)}get onmessage(){return Ze(this,Pu)}set onmessage(e){Et(this,Pu,e)}get onopen(){return Ze(this,Rp)}set onopen(e){Et(this,Rp,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Ze(this,Tu)&&clearTimeout(Ze(this,Tu)),Ze(this,ln)!==this.CLOSED&&(Ze(this,zs)&&Ze(this,zs).abort(),Et(this,ln,this.CLOSED),Et(this,zs,void 0))}};ln=new WeakMap,Ja=new WeakMap,Iu=new WeakMap,Hy=new WeakMap,Ky=new WeakMap,jp=new WeakMap,Tu=new WeakMap,Dp=new WeakMap,zs=new WeakMap,Eu=new WeakMap,Au=new WeakMap,Pu=new WeakMap,Rp=new WeakMap,hi=new WeakSet,GS=function(){Et(this,ln,this.CONNECTING),Et(this,zs,new AbortController),Ze(this,Ky)(Ze(this,Ja),Co(this,hi,_M).call(this)).then(Ze(this,HS)).catch(Ze(this,XS))},HS=new WeakMap,XS=new WeakMap,_M=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ze(this,Dp)?{"Last-Event-ID":Ze(this,Dp)}:void 0},cache:"no-store",signal:(t=Ze(this,zs))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},KS=new WeakMap,JS=new WeakMap,Mp=function(t,e){var r;Ze(this,ln)!==this.CLOSED&&Et(this,ln,this.CLOSED);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n)},YS=function(t,e){var r;if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.CONNECTING);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n),Et(this,Tu,setTimeout(Ze(this,QS),Ze(this,jp)))},QS=new WeakMap,Ya.CONNECTING=0,Ya.OPEN=1,Ya.CLOSED=2;function s8(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var tI=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Jy=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Vy(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new Ya(this._url.href,{...this._eventSourceInit,fetch:async(a,l)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let u=await i(a,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:p}=Su(u);this._resourceMetadataUrl=d,this._scope=p}return u}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var l;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let c=new tI(a.code,a.message,a);s(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var l;let c=a;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){s(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}o()}),this._eventSource.onmessage=a=>{var l,c;let u=a,d;try{d=Gc.parse(JSON.parse(u.data))}catch(p){(l=this.onerror)===null||l===void 0||l.call(this,p);return}(c=this.onmessage)===null||c===void 0||c.call(this,d)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i,o;if(!this._endpoint)throw new Error("Not connected");try{let s=await this._commonHeaders();s.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!l.ok){let c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Su(l);if(this._resourceMetadataUrl=u,this._scope=d,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((i=l.body)===null||i===void 0?void 0:i.cancel())}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}};var Fi={name:"@intelliweave/embedded",version:"2.0.72-beta.2",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var tr=new Ve("MCPKnowledgeClient"),Yy=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){tr.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new xp({name:Fi.name,version:Fi.version}),n=new Gy(new URL(this.config.baseURL));return await r.connect(n),tr.debug("Connected with HTTP streaming mode"),r}).catch(async r=>{let n=new xp({name:Fi.name,version:Fi.version}),i=new Jy(new URL(this.config.baseURL));return await n.connect(i),tr.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=r=>{tr.error(`MCP client error: ${r.message}`)},e.onclose=()=>{tr.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(ax,r=>{r.params.level=="critical"?tr.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?tr.error(`[Server] ${r.params.data}`):r.params.level=="error"?tr.error(`[Server] ${r.params.data}`):r.params.level=="warning"?tr.warn(`[Server] ${r.params.data}`):r.params.level=="info"?tr.info(`[Server] ${r.params.data}`):r.params.level=="debug"?tr.debug(`[Server] ${r.params.data}`):tr.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(sx,r=>{tr.debug("Tool list changed",r),this.fetchTools()}),tr.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let i=await this.client.listTools({cursor:r});r=i.nextCursor;for(let o of i.tools||[])e.push(o);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let o=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:s=>this.performToolCall(i.name,s),disabled:o})}tr.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,tr.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return tr.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else r.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return r}async performToolCall(e,r){await this.connect(),tr.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw tr.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var l8=new Ve("Statistics"),Lp=[];async function Gr(t,e){let r={...e,event_id:dr(),event_date:new Date().toISOString(),sdk_version:Fi.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Lp.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Lp.length===0))return;let n=Lp.slice();Lp.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){l8.warn("Failed to submit analytics event:",i),Lp.push(...n);return}}var Qa=new Ve("KnowledgeBase"),rI=1,Qy=class t{constructor(e){this._sources=[{id:"core.internal",query:async()=>hP(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${rI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return St().knowledgeBaseSources&&(e=e.concat(St().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(r=>!r.disabled),e}async search(e){let r=Date.now();Qa.debug(`Searching knowledge base for: ${e}`);let n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],typeof document<"u"&&document.dispatchEvent(n),this._windowSources=n.sources;let o=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),d=await c.query(e);return Qa.debug(`Source '${c.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Qa.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),St().knowledgeBase&&(o=o.concat(St().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);for(let c=0;c<o.length;c++){let u=o[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new mP({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(e).map(c=>o.find(u=>u.id==c.id));for(let c of o)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Gr(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Qa.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${rI++}`),Qa.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Qa.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let p=await d.json();return a(p.updateItems||[]),p.response},a=l=>{for(let c of l){if(!c.id){Qa.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.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}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(){let e=new t(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${rI++}`);let r=new Yy(e);return this.registerSource(e.id,n=>r.search(n)),r}};var ev=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
95
|
+
`&&n++}}return[e,r]}var By=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=Wy({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var i8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},As=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Gy=class{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Vy(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:i8}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i,o;let{resumptionToken:s}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);let l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new As(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{var u,d,p,f;try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new By({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:_}=await m.read();if(_)break;if(g.id&&(s=g.id,a=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let b=Gc.parse(JSON.parse(g.data));ka(b)&&(l=!0,o!==void 0&&(b.id=o)),(u=this.onmessage)===null||u===void 0||u.call(this,b)}catch(b){(d=this.onerror)===null||d===void 0||d.call(this,b)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(m){if((p=this.onerror)===null||p===void 0||p.call(this,new Error(`SSE stream disconnected: ${m}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(g){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s,a,l,c;try{let{resumptionToken:u,onresumptiontoken:d}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:df(e)?e.id:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let p=await this._commonHeaders();p.set("content-type","application/json"),p.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:p,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},m=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,f),h=m.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!m.ok){let b=await m.text().catch(()=>null);if(m.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new As(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:I}=Su(m);if(this._resourceMetadataUrl=E,this._scope=I,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this._hasCompletedAuthFlow=!0,this.send(e)}if(m.status===403&&this._authProvider){let{resourceMetadataUrl:E,scope:I,error:P}=Su(m);if(P==="insufficient_scope"){let M=m.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new As(403,"Server returned 403 after trying upscoping");if(I&&(this._scope=I),E&&(this._resourceMetadataUrl=E),this._lastUpscopingHeader=M??void 0,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Br;return this.send(e)}}throw new As(m.status,`Error POSTing to endpoint: ${b}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,m.status===202){await((o=m.body)===null||o===void 0?void 0:o.cancel()),WA(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let g=(Array.isArray(e)?e:[e]).filter(b=>"method"in b&&"id"in b&&b.id!==void 0).length>0,_=m.headers.get("content-type");if(g)if(_?.includes("text/event-stream"))this._handleSseStream(m.body,{onresumptiontoken:d},!1);else if(_?.includes("application/json")){let b=await m.json(),E=Array.isArray(b)?b.map(I=>Gc.parse(I)):[Gc.parse(b)];for(let I of E)(s=this.onmessage)===null||s===void 0||s.call(this,I)}else throw await((a=m.body)===null||a===void 0?void 0:a.cancel()),new As(-1,`Unexpected content type: ${_}`);else await((l=m.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n,i;if(this._sessionId)try{let o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(await((n=a.body)===null||n===void 0?void 0:n.cancel()),!a.ok&&a.status!==405)throw new As(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Xy=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(vM(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(vM(this),r)}};function o8(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function BS(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(BS).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${BS(t.cause)}`:t.message:`${t}`}function vM(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var bM=t=>{throw TypeError(t)},eI=(t,e,r)=>e.has(t)||bM("Cannot "+r),Ze=(t,e,r)=>(eI(t,e,"read from private field"),r?r.call(t):e.get(t)),er=(t,e,r)=>e.has(t)?bM("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Et=(t,e,r,n)=>(eI(t,e,"write to private field"),e.set(t,r),r),Co=(t,e,r)=>(eI(t,e,"access private method"),r),ln,Ja,Iu,Hy,Ky,jp,Tu,Dp,zs,Eu,Au,Pu,Rp,hi,GS,HS,XS,_M,KS,JS,Mp,YS,QS,Ya=class extends EventTarget{constructor(e,r){var n,i;super(),er(this,hi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,er(this,ln),er(this,Ja),er(this,Iu),er(this,Hy),er(this,Ky),er(this,jp),er(this,Tu),er(this,Dp,null),er(this,zs),er(this,Eu),er(this,Au,null),er(this,Pu,null),er(this,Rp,null),er(this,HS,async o=>{var s;Ze(this,Eu).reset();let{body:a,redirected:l,status:c,headers:u}=o;if(c===204){Co(this,hi,Mp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Et(this,Iu,new URL(o.url)):Et(this,Iu,void 0),c!==200){Co(this,hi,Mp).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Co(this,hi,Mp).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.OPEN);let d=new Event("open");if((s=Ze(this,Rp))==null||s.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){Co(this,hi,Mp).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let p=new TextDecoder,f=a.getReader(),m=!0;do{let{done:h,value:y}=await f.read();y&&Ze(this,Eu).feed(p.decode(y,{stream:!h})),h&&(m=!1,Ze(this,Eu).reset(),Co(this,hi,YS).call(this))}while(m)}),er(this,XS,o=>{Et(this,zs,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Co(this,hi,YS).call(this,BS(o))}),er(this,KS,o=>{typeof o.id=="string"&&Et(this,Dp,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Ze(this,Iu)?Ze(this,Iu).origin:Ze(this,Ja).origin,lastEventId:o.id||""});Ze(this,Pu)&&(!o.event||o.event==="message")&&Ze(this,Pu).call(this,s),this.dispatchEvent(s)}),er(this,JS,o=>{Et(this,jp,o)}),er(this,QS,()=>{Et(this,Tu,void 0),Ze(this,ln)===this.CONNECTING&&Co(this,hi,GS).call(this)});try{if(e instanceof URL)Et(this,Ja,e);else if(typeof e=="string")Et(this,Ja,new URL(e,s8()));else throw new Error("Invalid URL")}catch{throw o8("An invalid or illegal string was specified")}Et(this,Eu,Wy({onEvent:Ze(this,KS),onRetry:Ze(this,JS)})),Et(this,ln,this.CONNECTING),Et(this,jp,3e3),Et(this,Ky,(n=r?.fetch)!=null?n:globalThis.fetch),Et(this,Hy,(i=r?.withCredentials)!=null?i:!1),Co(this,hi,GS).call(this)}get readyState(){return Ze(this,ln)}get url(){return Ze(this,Ja).href}get withCredentials(){return Ze(this,Hy)}get onerror(){return Ze(this,Au)}set onerror(e){Et(this,Au,e)}get onmessage(){return Ze(this,Pu)}set onmessage(e){Et(this,Pu,e)}get onopen(){return Ze(this,Rp)}set onopen(e){Et(this,Rp,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Ze(this,Tu)&&clearTimeout(Ze(this,Tu)),Ze(this,ln)!==this.CLOSED&&(Ze(this,zs)&&Ze(this,zs).abort(),Et(this,ln,this.CLOSED),Et(this,zs,void 0))}};ln=new WeakMap,Ja=new WeakMap,Iu=new WeakMap,Hy=new WeakMap,Ky=new WeakMap,jp=new WeakMap,Tu=new WeakMap,Dp=new WeakMap,zs=new WeakMap,Eu=new WeakMap,Au=new WeakMap,Pu=new WeakMap,Rp=new WeakMap,hi=new WeakSet,GS=function(){Et(this,ln,this.CONNECTING),Et(this,zs,new AbortController),Ze(this,Ky)(Ze(this,Ja),Co(this,hi,_M).call(this)).then(Ze(this,HS)).catch(Ze(this,XS))},HS=new WeakMap,XS=new WeakMap,_M=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ze(this,Dp)?{"Last-Event-ID":Ze(this,Dp)}:void 0},cache:"no-store",signal:(t=Ze(this,zs))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},KS=new WeakMap,JS=new WeakMap,Mp=function(t,e){var r;Ze(this,ln)!==this.CLOSED&&Et(this,ln,this.CLOSED);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n)},YS=function(t,e){var r;if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.CONNECTING);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n),Et(this,Tu,setTimeout(Ze(this,QS),Ze(this,jp)))},QS=new WeakMap,Ya.CONNECTING=0,Ya.OPEN=1,Ya.CLOSED=2;function s8(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var tI=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Jy=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Vy(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new Ya(this._url.href,{...this._eventSourceInit,fetch:async(a,l)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let u=await i(a,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:p}=Su(u);this._resourceMetadataUrl=d,this._scope=p}return u}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var l;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let c=new tI(a.code,a.message,a);s(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var l;let c=a;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){s(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}o()}),this._eventSource.onmessage=a=>{var l,c;let u=a,d;try{d=Gc.parse(JSON.parse(u.data))}catch(p){(l=this.onerror)===null||l===void 0||l.call(this,p);return}(c=this.onmessage)===null||c===void 0||c.call(this,d)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i,o;if(!this._endpoint)throw new Error("Not connected");try{let s=await this._commonHeaders();s.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!l.ok){let c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Su(l);if(this._resourceMetadataUrl=u,this._scope=d,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((i=l.body)===null||i===void 0?void 0:i.cancel())}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}};var Fi={name:"@intelliweave/embedded",version:"2.0.72-beta.4",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var tr=new Ve("MCPKnowledgeClient"),Yy=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){tr.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new xp({name:Fi.name,version:Fi.version}),n=new Gy(new URL(this.config.baseURL));return await r.connect(n),tr.debug("Connected with HTTP streaming mode"),r}).catch(async r=>{let n=new xp({name:Fi.name,version:Fi.version}),i=new Jy(new URL(this.config.baseURL));return await n.connect(i),tr.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=r=>{tr.error(`MCP client error: ${r.message}`)},e.onclose=()=>{tr.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(ax,r=>{r.params.level=="critical"?tr.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?tr.error(`[Server] ${r.params.data}`):r.params.level=="error"?tr.error(`[Server] ${r.params.data}`):r.params.level=="warning"?tr.warn(`[Server] ${r.params.data}`):r.params.level=="info"?tr.info(`[Server] ${r.params.data}`):r.params.level=="debug"?tr.debug(`[Server] ${r.params.data}`):tr.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(sx,r=>{tr.debug("Tool list changed",r),this.fetchTools()}),tr.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let i=await this.client.listTools({cursor:r});r=i.nextCursor;for(let o of i.tools||[])e.push(o);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let o=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:s=>this.performToolCall(i.name,s),disabled:o})}tr.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,tr.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return tr.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else r.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return r}async performToolCall(e,r){await this.connect(),tr.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw tr.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var l8=new Ve("Statistics"),Lp=[];async function Gr(t,e){let r={...e,event_id:dr(),event_date:new Date().toISOString(),sdk_version:Fi.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Lp.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Lp.length===0))return;let n=Lp.slice();Lp.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){l8.warn("Failed to submit analytics event:",i),Lp.push(...n);return}}var Qa=new Ve("KnowledgeBase"),rI=1,Qy=class t{constructor(e){this._sources=[{id:"core.internal",query:async()=>hP(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${rI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return St().knowledgeBaseSources&&(e=e.concat(St().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(r=>!r.disabled),e}async search(e){let r=Date.now();Qa.debug(`Searching knowledge base for: ${e}`);let n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],typeof document<"u"&&document.dispatchEvent(n),this._windowSources=n.sources;let o=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),d=await c.query(e);return Qa.debug(`Source '${c.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Qa.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),St().knowledgeBase&&(o=o.concat(St().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);for(let c=0;c<o.length;c++){let u=o[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new mP({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(e).map(c=>o.find(u=>u.id==c.id));for(let c of o)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Gr(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Qa.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${rI++}`),Qa.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Qa.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let p=await d.json();return a(p.updateItems||[]),p.response},a=l=>{for(let c of l){if(!c.id){Qa.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.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}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(){let e=new t(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${rI++}`);let r=new Yy(e);return this.registerSource(e.id,n=>r.search(n)),r}};var ev=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
96
96
|
|
|
97
97
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(r.toLowerCase().includes("true"))return!0;if(r.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+r)}async choose(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
98
98
|
|
|
@@ -765,7 +765,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
|
|
|
765
765
|
|
|
766
766
|
</div>
|
|
767
767
|
|
|
768
|
-
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new tv,gm.isSupported&&(this.ai.audio=new gm(this.ai))}onCreate(){St().embed&&un.warn("Only one <web-weaver-embed> element should be on the page."),St().embed=this;let r=St();un.debug("[WebWeaverEmbed] Client config:",r),r.displayMode&&!this.attr.displayMode&&(un.debug("[WebWeaverEmbed] Setting displayMode from client config:",r.displayMode),this.attr.displayMode=r.displayMode),r.layout&&!this.attr.layout&&(un.debug("[WebWeaverEmbed] Setting layout from client config:",r.layout),this.attr.layout=r.layout),r.positioningMode&&!this.attr.positioningMode&&(un.debug("[WebWeaverEmbed] Setting positioningMode from client config:",r.positioningMode),this.attr.positioningMode=r.positioningMode),r.positionX&&!this.attr.positionX&&(un.debug("[WebWeaverEmbed] Setting positionX from client config:",r.positionX),this.attr.positionX=r.positionX),r.positionY&&!this.attr.positionY&&(un.debug("[WebWeaverEmbed] Setting positionY from client config:",r.positionY),this.attr.positionY=r.positionY),r.offsetX!==void 0&&!this.attr.offsetX&&(un.debug("[WebWeaverEmbed] Setting offsetX from client config:",r.offsetX),this.attr.offsetX=String(r.offsetX)),r.offsetY!==void 0&&!this.attr.offsetY&&(un.debug("[WebWeaverEmbed] Setting offsetY from client config:",r.offsetY),this.attr.offsetY=String(r.offsetY)),un.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",o=>this.onContainerClick(o)),this.child("web-weaver-logo").addEventListener("click",o=>this.onLogoClick(o)),this.child("interaction-bar").addEventListener("input-message",o=>this.processInput(o.detail)),this.child("interaction-bar").addEventListener("llm-button-click",o=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",o=>this.onLLMModelSelect(o)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:o=>(this.suggestions.push(o.text),"Suggestion button added")});let i=this.attr.apiKey||St().apiKey;if(!i)return un.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(i).then(o=>{this.config=o,St().introductionMessage=this.config.introductionMessage,St().analytics=this.config.analytics!==void 0?!!this.config.analytics:St().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(o=>{un.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(r,n){if(!n){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.removeProperty("--intelliweave-interaction-bg");return}let i=this.parseColorToRGB(n);if(!i){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.setProperty("--intelliweave-interaction-bg",n);return}let{r:o,g:s,b:a}=i;r.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${a}, 0.65)`),r.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),r.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${a}, 0.9)`)}parseColorToRGB(r){if(!r)return null;let n=r.trim();if(n.startsWith("#")){let i=n.slice(1);if(i.length===3){let o=parseInt(i[0]+i[0],16),s=parseInt(i[1]+i[1],16),a=parseInt(i[2]+i[2],16);return{r:o,g:s,b:a}}if(i.length===6){let o=parseInt(i.slice(0,2),16),s=parseInt(i.slice(2,4),16),a=parseInt(i.slice(4,6),16);return{r:o,g:s,b:a}}return null}if(n.startsWith("rgb")){let i=n.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return i?{r:Math.max(0,Math.min(255,Math.round(Number(i[1])))),g:Math.max(0,Math.min(255,Math.round(Number(i[2])))),b:Math.max(0,Math.min(255,Math.round(Number(i[3]))))}:null}return null}applyConfigStylesAndAttributes(){let r=this.config,n=this.child("root");if(!n)return;let i=!1,s=this.attr.logo||r.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,i=!0;let ie=this.child("web-weaver-logo");ie&&ie.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),c=r.name||"";c!==this._lastPersonaName&&(this._lastPersonaName=c,l&&(l.textContent=c),i=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),i=!0);let u=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(u){let ie=d==="hidden"||d==="none"||d==="false";u.style.display=!ie&&(s||c)?"":"none"}let f=this.attr.background||r.background;f!==this._lastBackground&&(this._lastBackground=f,i=!0,f?(n.style.background=f,n.style.setProperty("--intelliweave-persona-bg",f),this.applyPersonaColorVariants(n,f)):(n.style.background="",n.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(n,void 0)));let h=this.attr.textColor||r.textColor,y=this.child("interaction-bar");h!==this._lastTextColor&&(this._lastTextColor=h,i=!0,h?(n.style.color=h,n.style.setProperty("--intelliweave-user-bubble-text",h),n.style.setProperty("--intelliweave-assistant-bubble-text",h),y&&y.setAttribute("textColor",h)):(n.style.color="",n.style.removeProperty("--intelliweave-user-bubble-text"),n.style.removeProperty("--intelliweave-assistant-bubble-text"),y&&y.removeAttribute("textColor")));let _=this.attr.displayMode||r.displayMode||"closed";_!==this._lastDisplayMode&&(this._lastDisplayMode=_,i=!0,_==="open"&&!this.attr.open&&(this.attr.open=!0));let E=this.attr.layout||r.layout||"widget";E!==this._lastLayout&&(this._lastLayout=E,i=!0);let P=this.attr.positioningMode||r.positioningMode||"fixed";P!==this._lastPositioningMode&&(this._lastPositioningMode=P,i=!0);let V=this.attr.positionX||r.positionX||"right";V!==this._lastPositionX&&(this._lastPositionX=V,i=!0);let L=this.attr.positionY||r.positionY||"bottom";L!==this._lastPositionY&&(this._lastPositionY=L,i=!0);let G=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,H=G!==void 0?G:r.offsetX!==void 0?r.offsetX:20;H!==this._lastOffsetX&&(this._lastOffsetX=H,i=!0);let W=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,Y=W!==void 0?W:r.offsetY!==void 0?r.offsetY:20;Y!==this._lastOffsetY&&(this._lastOffsetY=Y,i=!0),i&&un.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:n.style.background,finalTextColor:n.style.color,finalDisplayMode:_,finalLayout:E,finalPositioningMode:P,finalPositionX:V,finalPositionY:L,finalOffsetX:H,finalOffsetY:Y})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),Gr(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let c=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;Gr(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:c}})}this._previousOpenState=this.attr.open;let r=this.child("root");this.attr.open?r.classList.add("open"):r.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(r.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):r.classList.remove("layout-fullscreen");let i=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;i==="container"?(r.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):r.classList.remove("container-mode"),i!=="container"&&(r.style.left="",r.style.right="",r.style.top="",r.style.bottom="",o==="left"?r.style.left=a+"px":r.style.right=a+"px",s==="top"?r.style.top=l+"px":r.style.bottom=l+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((c,u)=>(u.priority||0)-(c.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){St().embed==this&&(St().embed=void 0)}onContainerClick(r){let n=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&n!=="open"&&(this.attr.open||(r.preventDefault(),this.attr.open=!0))}onLogoClick(r){if(r.preventDefault(),r.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let n=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||n==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let r=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;r.children.length>0;)r.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let n=document.createElement("div");n.className="introduction-message",n.innerHTML=St().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,r.appendChild(n),this.ai.insertAssistantMessage(n.innerText);for(let i of St().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",s=>this.onSuggestionClick(s,i)),r.appendChild(o)}}async processInput(r){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let n=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let a of Array.from(n.querySelectorAll(".suggestion-button")))a.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=r,n.appendChild(i);let o=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",n.appendChild(this.currentOutputElement);let s=Math.ceil(n.clientHeight-300);s<0&&(s=0),s>600&&(s=600),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"}),await this.ai.sendMessage(r);for(let a of this.suggestions){let l=document.createElement("div");l.className="suggestion-button",l.innerText=a,l.addEventListener("click",c=>this.onSuggestionClick(c,a)),this.currentOutputElement.appendChild(l)}}catch(i){un.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,n.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),n.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(r,n){let i=[];for(let o of r)for(let s=0;s<(o.sections?.length||0);s++){let a=o.sections[s],l=`msgelem-${o.id||""}_${s}_${a.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let c=a.text||"";c.includes(`
|
|
768
|
+
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new tv,gm.isSupported&&(this.ai.audio=new gm(this.ai))}onCreate(){St().embed&&un.warn("Only one <web-weaver-embed> element should be on the page."),St().embed=this;let r=St();un.debug("[WebWeaverEmbed] Client config:",r),r.displayMode&&!this.attr.displayMode&&(un.debug("[WebWeaverEmbed] Setting displayMode from client config:",r.displayMode),this.attr.displayMode=r.displayMode),r.layout&&!this.attr.layout&&(un.debug("[WebWeaverEmbed] Setting layout from client config:",r.layout),this.attr.layout=r.layout),r.positioningMode&&!this.attr.positioningMode&&(un.debug("[WebWeaverEmbed] Setting positioningMode from client config:",r.positioningMode),this.attr.positioningMode=r.positioningMode),r.positionX&&!this.attr.positionX&&(un.debug("[WebWeaverEmbed] Setting positionX from client config:",r.positionX),this.attr.positionX=r.positionX),r.positionY&&!this.attr.positionY&&(un.debug("[WebWeaverEmbed] Setting positionY from client config:",r.positionY),this.attr.positionY=r.positionY),r.offsetX!==void 0&&!this.attr.offsetX&&(un.debug("[WebWeaverEmbed] Setting offsetX from client config:",r.offsetX),this.attr.offsetX=String(r.offsetX)),r.offsetY!==void 0&&!this.attr.offsetY&&(un.debug("[WebWeaverEmbed] Setting offsetY from client config:",r.offsetY),this.attr.offsetY=String(r.offsetY)),un.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",o=>this.onContainerClick(o)),this.child("web-weaver-logo").addEventListener("click",o=>this.onLogoClick(o)),this.child("interaction-bar").addEventListener("input-message",o=>this.processInput(o.detail)),this.child("interaction-bar").addEventListener("llm-button-click",o=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",o=>this.onLLMModelSelect(o)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:o=>(this.suggestions.push(o.text),"Suggestion button added")});let i=this.attr.apiKey||St().apiKey;if(!i)return un.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(i).then(o=>{this.config=o.config,St().introductionMessage=this.config.introductionMessage,St().analytics=this.config.analytics!==void 0?!!this.config.analytics:St().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(o=>{un.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(r,n){if(!n){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.removeProperty("--intelliweave-interaction-bg");return}let i=this.parseColorToRGB(n);if(!i){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.setProperty("--intelliweave-interaction-bg",n);return}let{r:o,g:s,b:a}=i;r.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${a}, 0.65)`),r.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),r.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${a}, 0.9)`)}parseColorToRGB(r){if(!r)return null;let n=r.trim();if(n.startsWith("#")){let i=n.slice(1);if(i.length===3){let o=parseInt(i[0]+i[0],16),s=parseInt(i[1]+i[1],16),a=parseInt(i[2]+i[2],16);return{r:o,g:s,b:a}}if(i.length===6){let o=parseInt(i.slice(0,2),16),s=parseInt(i.slice(2,4),16),a=parseInt(i.slice(4,6),16);return{r:o,g:s,b:a}}return null}if(n.startsWith("rgb")){let i=n.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return i?{r:Math.max(0,Math.min(255,Math.round(Number(i[1])))),g:Math.max(0,Math.min(255,Math.round(Number(i[2])))),b:Math.max(0,Math.min(255,Math.round(Number(i[3]))))}:null}return null}applyConfigStylesAndAttributes(){let r=this.config,n=this.child("root");if(!n)return;let i=!1,s=this.attr.logo||r.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,i=!0;let ie=this.child("web-weaver-logo");ie&&ie.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),c=r.name||"";c!==this._lastPersonaName&&(this._lastPersonaName=c,l&&(l.textContent=c),i=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),i=!0);let u=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(u){let ie=d==="hidden"||d==="none"||d==="false";u.style.display=!ie&&(s||c)?"":"none"}let f=this.attr.background||r.background;f!==this._lastBackground&&(this._lastBackground=f,i=!0,f?(n.style.background=f,n.style.setProperty("--intelliweave-persona-bg",f),this.applyPersonaColorVariants(n,f)):(n.style.background="",n.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(n,void 0)));let h=this.attr.textColor||r.textColor,y=this.child("interaction-bar");h!==this._lastTextColor&&(this._lastTextColor=h,i=!0,h?(n.style.color=h,n.style.setProperty("--intelliweave-user-bubble-text",h),n.style.setProperty("--intelliweave-assistant-bubble-text",h),y&&y.setAttribute("textColor",h)):(n.style.color="",n.style.removeProperty("--intelliweave-user-bubble-text"),n.style.removeProperty("--intelliweave-assistant-bubble-text"),y&&y.removeAttribute("textColor")));let _=this.attr.displayMode||r.displayMode||"closed";_!==this._lastDisplayMode&&(this._lastDisplayMode=_,i=!0,_==="open"&&!this.attr.open&&(this.attr.open=!0));let E=this.attr.layout||r.layout||"widget";E!==this._lastLayout&&(this._lastLayout=E,i=!0);let P=this.attr.positioningMode||r.positioningMode||"fixed";P!==this._lastPositioningMode&&(this._lastPositioningMode=P,i=!0);let V=this.attr.positionX||r.positionX||"right";V!==this._lastPositionX&&(this._lastPositionX=V,i=!0);let L=this.attr.positionY||r.positionY||"bottom";L!==this._lastPositionY&&(this._lastPositionY=L,i=!0);let G=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,H=G!==void 0?G:r.offsetX!==void 0?r.offsetX:20;H!==this._lastOffsetX&&(this._lastOffsetX=H,i=!0);let W=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,Y=W!==void 0?W:r.offsetY!==void 0?r.offsetY:20;Y!==this._lastOffsetY&&(this._lastOffsetY=Y,i=!0),i&&un.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:n.style.background,finalTextColor:n.style.color,finalDisplayMode:_,finalLayout:E,finalPositioningMode:P,finalPositionX:V,finalPositionY:L,finalOffsetX:H,finalOffsetY:Y})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),Gr(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let c=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;Gr(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:c}})}this._previousOpenState=this.attr.open;let r=this.child("root");this.attr.open?r.classList.add("open"):r.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(r.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):r.classList.remove("layout-fullscreen");let i=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;i==="container"?(r.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):r.classList.remove("container-mode"),i!=="container"&&(r.style.left="",r.style.right="",r.style.top="",r.style.bottom="",o==="left"?r.style.left=a+"px":r.style.right=a+"px",s==="top"?r.style.top=l+"px":r.style.bottom=l+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((c,u)=>(u.priority||0)-(c.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){St().embed==this&&(St().embed=void 0)}onContainerClick(r){let n=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&n!=="open"&&(this.attr.open||(r.preventDefault(),this.attr.open=!0))}onLogoClick(r){if(r.preventDefault(),r.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let n=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||n==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let r=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;r.children.length>0;)r.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let n=document.createElement("div");n.className="introduction-message",n.innerHTML=St().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,r.appendChild(n),this.ai.insertAssistantMessage(n.innerText);for(let i of St().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",s=>this.onSuggestionClick(s,i)),r.appendChild(o)}}async processInput(r){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let n=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let c of Array.from(n.querySelectorAll(".suggestion-button")))c.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=r,n.appendChild(i);let o=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",n.appendChild(this.currentOutputElement);let s=Math.ceil(n.clientHeight-300);s<0&&(s=0),s>600&&(s=600),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"});let a=await this.ai.sendMessage(r);for(let c of this.suggestions){let u=document.createElement("div");u.className="suggestion-button",u.innerText=c,u.addEventListener("click",d=>this.onSuggestionClick(d,c)),this.currentOutputElement.appendChild(u)}let l=a.text()||"";this.ai.audio?.speechRecognition?.isRunning&&this.ai.audio.speechOutput.speak(l)}catch(i){un.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,n.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),n.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(r,n){let i=[];for(let o of r)for(let s=0;s<(o.sections?.length||0);s++){let a=o.sections[s],l=`msgelem-${o.id||""}_${s}_${a.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let c=a.text||"";c.includes(`
|
|
769
769
|
`)&&(c=c.split(`
|
|
770
770
|
`)[0]),this.updateInfoElement(l,c,"thinking-icon"),i.push(l)}else if(a.type=="tool_call"){let u=new zu(r).toolResult(a.toolCallInstanceID||"");if(a.toolCallHiddenInUI!="always"){if(u?.toolErrorResponse)this.updateInfoElement(l,"**Error:** "+u.toolErrorResponse||"","tool-icon"),i.push(l);else if(!(a.toolCallHiddenInUI=="after-complete"&&u))if(a.toolKbID=="search"){let d=a.toolParameters?.query?`**Search:** ${a.toolParameters.query}`:"**Search**";this.updateInfoElement(l,d,"tool-icon"),i.push(l)}else this.updateInfoElement(l,a.toolKbName||"","tool-icon"),i.push(l)}}else if(a.type!="tool_result"){if(!a.text)continue;this.updateTextElement(l,a.text||""),i.push(l)}}for(let o of Array.from(this.currentOutputElement.children))i.includes(o.id)||o.remove()}updateTextElement(r,n){let i=this.currentOutputElement.querySelector(`#${r}`);i||(i=document.createElement("div"),i.id=r,i.className="output",this.currentOutputElement.appendChild(i));let o=jv().use(lm).use(cm).use(Kp,{target:"_blank",rel:["noopener","noreferrer"]}).use(Jp).use(tm).processSync(n||"");i.innerHTML=o.toString("utf-8")}updateInfoElement(r,n,i){let o=this.currentOutputElement.querySelector(`#${r}`);o||(o=document.createElement("div"),o.id=r,o.className="info-block",o.innerHTML=`
|
|
771
771
|
<div class='info-block-icon'></div>
|