@intelliweave/embedded 2.0.72-beta.10 → 2.0.72-beta.11

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.
@@ -461,6 +461,8 @@ declare class KnowledgeBase {
461
461
  allowWindowSources: boolean;
462
462
  /** If true, allows using knowledge specified in the global configuration object */
463
463
  allowGlobalConfigSources: boolean;
464
+ /** If true, allows the AI to search the knowledge base. If false, essentially disables RAG lookup. */
465
+ allowRagSearch: boolean;
464
466
  /** Constructor */
465
467
  constructor(ai: IntelliWeave);
466
468
  /** Ensures the internal knowledge is set correctly */
@@ -489,7 +491,7 @@ declare class KnowledgeBase {
489
491
  /** Create and register an external knowledge base source from a URL */
490
492
  registerSourceFromURL(url: string, id?: string): void;
491
493
  /** Clone this instance */
492
- clone(): KnowledgeBase;
494
+ clone(newIW: IntelliWeave): KnowledgeBase;
493
495
  /** Registers an MCP server as a knowledge base source */
494
496
  registerMCPSource(config: MCPKnowledgeClient['config']): MCPKnowledgeClient;
495
497
  }
@@ -1079,6 +1081,8 @@ interface SubAgentConfig {
1079
1081
  usageInstructions?: string;
1080
1082
  /** If true, will remove all Persona knowledge entries */
1081
1083
  clearExistingKnowledge?: boolean;
1084
+ /** Disable RAG search for subagents. If true, only KB entries with isContext=true will be used. */
1085
+ disableRagSearch?: boolean;
1082
1086
  /** Extra knowledge base sources for the sub-agent */
1083
1087
  knowledge?: KnowledgeFetcher;
1084
1088
  /** Optional extra configuration for the subagent instance */
@@ -80,7 +80,7 @@ If you understand the risks and have appropriate mitigations in place,
80
80
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
81
81
 
82
82
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
83
- `);this.baseURL=o.baseURL,this.timeout=o.timeout??Iv.DEFAULT_TIMEOUT,this.logger=o.logger??console;let s="warn";this.logLevel=s,this.logLevel=nv(o.logLevel,"ClientOptions.logLevel",this)??nv(qd("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??s,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??L1(),B(this,jh,Z1,"f"),this._options=o,this.apiKey=typeof r=="string"?r:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return ve([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return ve([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return ve([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new ee(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Yo}`}defaultIdempotencyKey(){return`stainless-node-retry-${Yb()}`}makeStatusError(e,r,n,i){return Jt.generate(e,r,n,i)}buildURL(e,r,n){let i=!E(this,Sv,"m",hP).call(this)&&n||this.baseURL,o=T1(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return A1(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new ee("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new la(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,o=i.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(i);let{req:s,url:a,timeout:c}=await this.buildRequest(i,{retryCount:o-r});await this.prepareRequest(s,{url:a,options:i});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Yt(this).debug(`[${l}] sending request`,no({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:s.headers})),i.signal?.aborted)throw new ar;let f=new AbortController,p=await this.fetchWithTimeout(a,s,c,f).catch(vd),h=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new ar;let b=to(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Yt(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${y}`),Yt(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${y})`,no({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),this.retryRequest(i,r,n??l);throw Yt(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),Yt(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,no({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),b?new cl:new Jo({cause:p})}let m=[...p.headers.entries()].filter(([y])=>y==="request-id").map(([y,b])=>", "+y+": "+JSON.stringify(b)).join(""),g=`[${l}${u}${m}] ${s.method} ${a} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${h-d}ms`;if(!p.ok){let y=await this.shouldRetry(p);if(r&&y){let F=`retrying, ${r} attempts remaining`;return await U1(p.body),Yt(this).info(`${g} - ${F}`),Yt(this).debug(`[${l}] response error (${F})`,no({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),this.retryRequest(i,r,n??l,p.headers)}let b=y?"error; no more retries left":"error; not retryable";Yt(this).info(`${g} - ${b}`);let $=await p.text().catch(F=>vd(F).message),R=uh($),T=R?void 0:$;throw Yt(this).debug(`[${l}] response error (${b})`,no({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:T,durationMs:Date.now()-d})),this.makeStatusError(p.status,R,T,p.headers)}return Yt(this).info(g),Yt(this).debug(`[${l}] response start`,no({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),{response:p,options:i,controller:f,requestLogID:l,retryOfRequestLogID:n,startTime:d}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Id(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:o,method:s,...a}=r||{},c=this._makeAbort(i);o&&o.addEventListener("abort",c,{once:!0});let l=setTimeout(c,n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...a};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let o,s=i?.get("retry-after-ms");if(s){let c=parseFloat(s);Number.isNaN(c)||(o=c)}let a=i?.get("retry-after");if(a&&!o){let c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(!(o&&0<=o&&o<60*1e3)){let c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,c)}return await C1(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}calculateNonstreamingTimeout(e,r){if(36e5*e/128e3>6e5||r!=null&&e>r)throw new ee("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:o,query:s,defaultBaseURL:a}=n,c=this.buildURL(o,s,a);"timeout"in n&&N1("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:l,retryCount:r});return{req:{method:i,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let s=ve([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...D1(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=ve([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:dh(e)}:E(this,jh,"f").call(this,{body:e,headers:n})}};Iv=Pt,jh=new WeakMap,Sv=new WeakSet,hP=function(){return this.baseURL!=="https://api.anthropic.com"};Pt.Anthropic=Iv;Pt.HUMAN_PROMPT=gP;Pt.AI_PROMPT=yP;Pt.DEFAULT_TIMEOUT=6e5;Pt.AnthropicError=ee;Pt.APIError=Jt;Pt.APIConnectionError=Jo;Pt.APIConnectionTimeoutError=cl;Pt.APIUserAbortError=ar;Pt.NotFoundError=pl;Pt.ConflictError=fl;Pt.RateLimitError=hl;Pt.BadRequestError=ll;Pt.AuthenticationError=ul;Pt.InternalServerError=gl;Pt.PermissionDeniedError=dl;Pt.UnprocessableEntityError=ml;Pt.toFile=yh;var ki=class extends Pt{constructor(){super(...arguments),this.completions=new ha(this),this.messages=new rs(this),this.models=new ya(this),this.beta=new Kn(this)}};ki.Completions=ha;ki.Messages=rs;ki.Models=ya;ki.Beta=Kn;var _P=new Ce("AnthropicChat"),Dh=class extends sl{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 ki({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),i=!0,o=[];for(;i;){i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),_P.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,f)=>{let p=this.parseMessageBlock(f,!0);this.config.onAIMessage?.([...o,p],!0),r?.([...o,p])});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(_P.debug("Message received",a),a.content?.length){let u=this.messageGroup.add(this.parseMessageBlock(a,!1));o.push(u)}let c=[],l=[];if(await Promise.all(a.content.map(async u=>{if(u.type!="tool_use")return;let d=this.findToolBySafeName(u.name);try{let f=await this.executeTool(d,u.input);l.push({type:"tool_result",tool_use_id:u.id,content:f}),c.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolSuccessResponse:f,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}catch(f){let p=f?.message||"An unknown error occurred";l.push({type:"tool_result",tool_use_id:u.id,content:`Error performing tool call ${u.name}: ${p}`}),c.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolErrorResponse:p,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}})),l.length>0){let u=this.messageGroup.add({id:"msg-"+sr(),sections:c,data:{role:"user",content:l}});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,r){let n=[];for(let i of e.content)if(i.type=="thinking")n.push({type:"thinking",text:i.thinking||""});else if(i.type=="text")n.push({type:"text",text:i.text||""});else if(i.type=="tool_use"){let o=this.findToolBySafeName(i.name);n.push({type:"tool_call",toolName:i.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:i.input,toolCallInstanceID:i.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:e.id,data:{role:e.role,content:e.content},sections:n,source:"assistant",streamingInProgress:r,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 AL="ENTRIES",kP="KEYS",$P="VALUES";var Bd=class{constructor(e,r){let n=e._tree,i=Array.from(n.keys());this.set=e,this._type=r,this._path=i.length>0?[{node:n,keys:i}]:[]}next(){let e=this.dive();return this.backtrack(),e}dive(){if(this._path.length===0)return{done:!0,value:void 0};let{node:e,keys:r}=Al(this._path);if(Al(r)==="")return{done:!1,value:this.result()};let n=e.get(Al(r));return this._path.push({node:n,keys:Array.from(n.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;let e=Al(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}key(){return this.set._prefix+this._path.map(({keys:e})=>Al(e)).filter(e=>e!=="").join("")}value(){return Al(this._path).node.get("")}result(){switch(this._type){case $P:return this.value();case kP:return this.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){return this}},Al=t=>t[t.length-1],zL=(t,e,r)=>{let n=new Map;if(e===void 0)return n;let i=e.length+1,o=i+r,s=new Uint8Array(o*i).fill(r+1);for(let a=0;a<i;++a)s[a]=a;for(let a=1;a<o;++a)s[a*i]=a;return SP(t,e,r,n,s,1,i,""),n},SP=(t,e,r,n,i,o,s,a)=>{let c=o*s;e:for(let l of t.keys())if(l===""){let u=i[c-1];u<=r&&n.set(a,[t.get(l),u])}else{let u=o;for(let d=0;d<l.length;++d,++u){let f=l[d],p=s*u,h=p-s,m=i[p],g=Math.max(0,u-r-1),y=Math.min(s-1,u+r);for(let b=g;b<y;++b){let $=f!==e[b],R=i[h+b]+ +$,T=i[h+b+1]+1,P=i[p+b]+1,F=i[p+b+1]=Math.min(R,T,P);F<m&&(m=F)}if(m>r)continue e}SP(t.get(l),e,r,n,i,u,s,a+l)}},Wd=class t{constructor(e=new Map,r=""){this._size=void 0,this._tree=e,this._prefix=r}atPrefix(e){if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");let[r,n]=Zh(this._tree,e.slice(this._prefix.length));if(r===void 0){let[i,o]=Ov(n);for(let s of i.keys())if(s!==""&&s.startsWith(o)){let a=new Map;return a.set(s.slice(o.length),i.get(s)),new t(a,e)}}return new t(r,e)}clear(){this._size=void 0,this._tree.clear()}delete(e){return this._size=void 0,NL(this._tree,e)}entries(){return new Bd(this,AL)}forEach(e){for(let[r,n]of this)e(r,n,this)}fuzzyGet(e,r){return zL(this._tree,e,r)}get(e){let r=zv(this._tree,e);return r!==void 0?r.get(""):void 0}has(e){let r=zv(this._tree,e);return r!==void 0&&r.has("")}keys(){return new Bd(this,kP)}set(e,r){if(typeof e!="string")throw new Error("key must be a string");return this._size=void 0,Ev(this._tree,e).set("",r),this}get size(){if(this._size)return this._size;this._size=0;let e=this.entries();for(;!e.next().done;)this._size+=1;return this._size}update(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;let n=Ev(this._tree,e);return n.set("",r(n.get(""))),this}fetch(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;let n=Ev(this._tree,e),i=n.get("");return i===void 0&&n.set("",i=r()),i}values(){return new Bd(this,$P)}[Symbol.iterator](){return this.entries()}static from(e){let r=new t;for(let[n,i]of e)r.set(n,i);return r}static fromObject(e){return t.from(Object.entries(e))}},Zh=(t,e,r=[])=>{if(e.length===0||t==null)return[t,r];for(let n of t.keys())if(n!==""&&e.startsWith(n))return r.push([t,n]),Zh(t.get(n),e.slice(n.length),r);return r.push([t,e]),Zh(void 0,"",r)},zv=(t,e)=>{if(e.length===0||t==null)return t;for(let r of t.keys())if(r!==""&&e.startsWith(r))return zv(t.get(r),e.slice(r.length))},Ev=(t,e)=>{let r=e.length;e:for(let n=0;t&&n<r;){for(let o of t.keys())if(o!==""&&e[n]===o[0]){let s=Math.min(r-n,o.length),a=1;for(;a<s&&e[n+a]===o[a];)++a;let c=t.get(o);if(a===o.length)t=c;else{let l=new Map;l.set(o.slice(a),c),t.set(e.slice(n,n+a),l),t.delete(o),t=l}n+=a;continue e}let i=new Map;return t.set(e.slice(n),i),i}return t},NL=(t,e)=>{let[r,n]=Zh(t,e);if(r!==void 0){if(r.delete(""),r.size===0)IP(n);else if(r.size===1){let[i,o]=r.entries().next().value;EP(n,i,o)}}},IP=t=>{if(t.length===0)return;let[e,r]=Ov(t);if(e.delete(r),e.size===0)IP(t.slice(0,-1));else if(e.size===1){let[n,i]=e.entries().next().value;n!==""&&EP(t.slice(0,-1),n,i)}},EP=(t,e,r)=>{if(t.length===0)return;let[n,i]=Ov(t);n.set(i+e,r),n.delete(i)},Ov=t=>t[t.length-1],Rv="or",PP="and",CL="and_not",Gd=class t{constructor(e){if(e?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');let r=e.autoVacuum==null||e.autoVacuum===!0?Av:e.autoVacuum;this._options={...Tv,...e,autoVacuum:r,searchOptions:{...bP,...e.searchOptions||{}},autoSuggestOptions:{...DL,...e.autoSuggestOptions||{}}},this._index=new Wd,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=Cv,this.addFields(this._options.fields)}add(e){let{extractField:r,stringifyField:n,tokenize:i,processTerm:o,fields:s,idField:a}=this._options,c=r(e,a);if(c==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);if(this._idToShortId.has(c))throw new Error(`MiniSearch: duplicate ID ${c}`);let l=this.addDocumentId(c);this.saveStoredFields(l,e);for(let u of s){let d=r(e,u);if(d==null)continue;let f=i(n(d,u),u),p=this._fieldIds[u],h=new Set(f).size;this.addFieldLength(l,p,this._documentCount-1,h);for(let m of f){let g=o(m,u);if(Array.isArray(g))for(let y of g)this.addTerm(p,l,y);else g&&this.addTerm(p,l,g)}}}addAll(e){for(let r of e)this.add(r)}addAllAsync(e,r={}){let{chunkSize:n=10}=r,i={chunk:[],promise:Promise.resolve()},{chunk:o,promise:s}=e.reduce(({chunk:a,promise:c},l,u)=>(a.push(l),(u+1)%n===0?{chunk:[],promise:c.then(()=>new Promise(d=>setTimeout(d,0))).then(()=>this.addAll(a))}:{chunk:a,promise:c}),i);return s.then(()=>this.addAll(o))}remove(e){let{tokenize:r,processTerm:n,extractField:i,stringifyField:o,fields:s,idField:a}=this._options,c=i(e,a);if(c==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);let l=this._idToShortId.get(c);if(l==null)throw new Error(`MiniSearch: cannot remove document with ID ${c}: it is not in the index`);for(let u of s){let d=i(e,u);if(d==null)continue;let f=r(o(d,u),u),p=this._fieldIds[u],h=new Set(f).size;this.removeFieldLength(l,p,this._documentCount,h);for(let m of f){let g=n(m,u);if(Array.isArray(g))for(let y of g)this.removeTerm(p,l,y);else g&&this.removeTerm(p,l,g)}}this._storedFields.delete(l),this._documentIds.delete(l),this._idToShortId.delete(c),this._fieldLength.delete(l),this._documentCount-=1}removeAll(e){if(e)for(let r of e)this.remove(r);else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new Wd,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}}discard(e){let r=this._idToShortId.get(e);if(r==null)throw new Error(`MiniSearch: cannot discard document with ID ${e}: it is not in the index`);this._idToShortId.delete(e),this._documentIds.delete(r),this._storedFields.delete(r),(this._fieldLength.get(r)||[]).forEach((n,i)=>{this.removeFieldLength(r,i,this._documentCount,n)}),this._fieldLength.delete(r),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()}maybeAutoVacuum(){if(this._options.autoVacuum===!1)return;let{minDirtFactor:e,minDirtCount:r,batchSize:n,batchWait:i}=this._options.autoVacuum;this.conditionalVacuum({batchSize:n,batchWait:i},{minDirtCount:r,minDirtFactor:e})}discardAll(e){let r=this._options.autoVacuum;try{this._options.autoVacuum=!1;for(let n of e)this.discard(n)}finally{this._options.autoVacuum=r}this.maybeAutoVacuum()}replace(e){let{idField:r,extractField:n}=this._options,i=n(e,r);this.discard(i),this.add(e)}vacuum(e={}){return this.conditionalVacuum(e)}conditionalVacuum(e,r){return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&r,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(()=>{let n=this._enqueuedVacuumConditions;return this._enqueuedVacuumConditions=Cv,this.performVacuuming(e,n)}),this._enqueuedVacuum)):this.vacuumConditionsMet(r)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)}async performVacuuming(e,r){let n=this._dirtCount;if(this.vacuumConditionsMet(r)){let i=e.batchSize||Nv.batchSize,o=e.batchWait||Nv.batchWait,s=1;for(let[a,c]of this._index){for(let[l,u]of c)for(let[d]of u)this._documentIds.has(d)||(u.size<=1?c.delete(l):u.delete(d));this._index.get(a).size===0&&this._index.delete(a),s%i===0&&await new Promise(l=>setTimeout(l,o)),s+=1}this._dirtCount-=n}await null,this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null}vacuumConditionsMet(e){if(e==null)return!0;let{minDirtCount:r,minDirtFactor:n}=e;return r=r||Av.minDirtCount,n=n||Av.minDirtFactor,this.dirtCount>=r&&this.dirtFactor>=n}get isVacuuming(){return this._currentVacuum!=null}get dirtCount(){return this._dirtCount}get dirtFactor(){return this._dirtCount/(1+this._documentCount+this._dirtCount)}has(e){return this._idToShortId.has(e)}getStoredFields(e){let r=this._idToShortId.get(e);if(r!=null)return this._storedFields.get(r)}search(e,r={}){let{searchOptions:n}=this._options,i={...n,...r},o=this.executeQuery(e,r),s=[];for(let[a,{score:c,terms:l,match:u}]of o){let d=l.length||1,f={id:this._documentIds.get(a),score:c*d,terms:Object.keys(u),queryTerms:l,match:u};Object.assign(f,this._storedFields.get(a)),(i.filter==null||i.filter(f))&&s.push(f)}return e===t.wildcard&&i.boostDocument==null||s.sort(wP),s}autoSuggest(e,r={}){r={...this._options.autoSuggestOptions,...r};let n=new Map;for(let{score:o,terms:s}of this.search(e,r)){let a=s.join(" "),c=n.get(a);c!=null?(c.score+=o,c.count+=1):n.set(a,{score:o,terms:s,count:1})}let i=[];for(let[o,{score:s,terms:a,count:c}]of n)i.push({suggestion:o,terms:a,score:s/c});return i.sort(wP),i}get documentCount(){return this._documentCount}get termCount(){return this._index.size}static loadJSON(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)}static async loadJSONAsync(e,r){if(r==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJSAsync(JSON.parse(e),r)}static getDefault(e){if(Tv.hasOwnProperty(e))return Pv(Tv,e);throw new Error(`MiniSearch: unknown option "${e}"`)}static loadJS(e,r){let{index:n,documentIds:i,fieldLength:o,storedFields:s,serializationVersion:a}=e,c=this.instantiateMiniSearch(e,r);c._documentIds=Lh(i),c._fieldLength=Lh(o),c._storedFields=Lh(s);for(let[l,u]of c._documentIds)c._idToShortId.set(u,l);for(let[l,u]of n){let d=new Map;for(let f of Object.keys(u)){let p=u[f];a===1&&(p=p.ds),d.set(parseInt(f,10),Lh(p))}c._index.set(l,d)}return c}static async loadJSAsync(e,r){let{index:n,documentIds:i,fieldLength:o,storedFields:s,serializationVersion:a}=e,c=this.instantiateMiniSearch(e,r);c._documentIds=await Uh(i),c._fieldLength=await Uh(o),c._storedFields=await Uh(s);for(let[u,d]of c._documentIds)c._idToShortId.set(d,u);let l=0;for(let[u,d]of n){let f=new Map;for(let p of Object.keys(d)){let h=d[p];a===1&&(h=h.ds),f.set(parseInt(p,10),await Uh(h))}++l%1e3===0&&await TP(0),c._index.set(u,f)}return c}static instantiateMiniSearch(e,r){let{documentCount:n,nextId:i,fieldIds:o,averageFieldLength:s,dirtCount:a,serializationVersion:c}=e;if(c!==1&&c!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");let l=new t(r);return l._documentCount=n,l._nextId=i,l._idToShortId=new Map,l._fieldIds=o,l._avgFieldLength=s,l._dirtCount=a||0,l._index=new Wd,l}executeQuery(e,r={}){if(e===t.wildcard)return this.executeWildcardQuery(r);if(typeof e!="string"){let f={...r,...e,queries:void 0},p=e.queries.map(h=>this.executeQuery(h,f));return this.combineResults(p,f.combineWith)}let{tokenize:n,processTerm:i,searchOptions:o}=this._options,s={tokenize:n,processTerm:i,...o,...r},{tokenize:a,processTerm:c}=s,d=a(e).flatMap(f=>c(f)).filter(f=>!!f).map(jL(s)).map(f=>this.executeQuerySpec(f,s));return this.combineResults(d,s.combineWith)}executeQuerySpec(e,r){let n={...this._options.searchOptions,...r},i=(n.fields||this._options.fields).reduce((m,g)=>({...m,[g]:Pv(n.boost,g)||1}),{}),{boostDocument:o,weights:s,maxFuzzy:a,bm25:c}=n,{fuzzy:l,prefix:u}={...bP.weights,...s},d=this._index.get(e.term),f=this.termResults(e.term,e.term,1,e.termBoost,d,i,o,c),p,h;if(e.prefix&&(p=this._index.atPrefix(e.term)),e.fuzzy){let m=e.fuzzy===!0?.2:e.fuzzy,g=m<1?Math.min(a,Math.round(e.term.length*m)):m;g&&(h=this._index.fuzzyGet(e.term,g))}if(p)for(let[m,g]of p){let y=m.length-e.term.length;if(!y)continue;h?.delete(m);let b=u*m.length/(m.length+.3*y);this.termResults(e.term,m,b,e.termBoost,g,i,o,c,f)}if(h)for(let m of h.keys()){let[g,y]=h.get(m);if(!y)continue;let b=l*m.length/(m.length+y);this.termResults(e.term,m,b,e.termBoost,g,i,o,c,f)}return f}executeWildcardQuery(e){let r=new Map,n={...this._options.searchOptions,...e};for(let[i,o]of this._documentIds){let s=n.boostDocument?n.boostDocument(o,"",this._storedFields.get(i)):1;r.set(i,{score:s,terms:[],match:{}})}return r}combineResults(e,r=Rv){if(e.length===0)return new Map;let n=r.toLowerCase(),i=OL[n];if(!i)throw new Error(`Invalid combination operator: ${r}`);return e.reduce(i)||new Map}toJSON(){let e=[];for(let[r,n]of this._index){let i={};for(let[o,s]of n)i[o]=Object.fromEntries(s);e.push([r,i])}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:e,serializationVersion:2}}termResults(e,r,n,i,o,s,a,c,l=new Map){if(o==null)return l;for(let u of Object.keys(s)){let d=s[u],f=this._fieldIds[u],p=o.get(f);if(p==null)continue;let h=p.size,m=this._avgFieldLength[f];for(let g of p.keys()){if(!this._documentIds.has(g)){this.removeTerm(f,g,r),h-=1;continue}let y=a?a(this._documentIds.get(g),r,this._storedFields.get(g)):1;if(!y)continue;let b=p.get(g),$=this._fieldLength.get(g)[f],R=ML(b,h,this._documentCount,$,m,c),T=n*i*d*y*R,P=l.get(g);if(P){P.score+=T,LL(P.terms,e);let F=Pv(P.match,r);F?F.push(u):P.match[r]=[u]}else l.set(g,{score:T,terms:[e],match:{[r]:[u]}})}}return l}addTerm(e,r,n){let i=this._index.fetch(n,xP),o=i.get(e);if(o==null)o=new Map,o.set(r,1),i.set(e,o);else{let s=o.get(r);o.set(r,(s||0)+1)}}removeTerm(e,r,n){if(!this._index.has(n)){this.warnDocumentChanged(r,e,n);return}let i=this._index.fetch(n,xP),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)}warnDocumentChanged(e,r,n){for(let i of Object.keys(this._fieldIds))if(this._fieldIds[i]===r){this._options.logger("warn",`MiniSearch: document with ID ${this._documentIds.get(e)} has changed before removal: term "${n}" was not present in field "${i}". Removing a document after it has changed can corrupt the index!`,"version_conflict");return}}addDocumentId(e){let r=this._nextId;return this._idToShortId.set(e,r),this._documentIds.set(r,e),this._documentCount+=1,this._nextId+=1,r}addFields(e){for(let r=0;r<e.length;r++)this._fieldIds[e[r]]=r}addFieldLength(e,r,n,i){let o=this._fieldLength.get(e);o==null&&this._fieldLength.set(e,o=[]),o[r]=i;let a=(this._avgFieldLength[r]||0)*n+i;this._avgFieldLength[r]=a/(n+1)}removeFieldLength(e,r,n,i){if(n===1){this._avgFieldLength[r]=0;return}let o=this._avgFieldLength[r]*n-i;this._avgFieldLength[r]=o/(n-1)}saveStoredFields(e,r){let{storeFields:n,extractField:i}=this._options;if(n==null||n.length===0)return;let o=this._storedFields.get(e);o==null&&this._storedFields.set(e,o={});for(let s of n){let a=i(r,s);a!==void 0&&(o[s]=a)}}};Gd.wildcard=Symbol("*");var Pv=(t,e)=>Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0,OL={[Rv]:(t,e)=>{for(let r of e.keys()){let n=t.get(r);if(n==null)t.set(r,e.get(r));else{let{score:i,terms:o,match:s}=e.get(r);n.score=n.score+i,n.match=Object.assign(n.match,s),vP(n.terms,o)}}return t},[PP]:(t,e)=>{let r=new Map;for(let n of e.keys()){let i=t.get(n);if(i==null)continue;let{score:o,terms:s,match:a}=e.get(n);vP(i.terms,s),r.set(n,{score:i.score+o,terms:i.terms,match:Object.assign(i.match,a)})}return r},[CL]:(t,e)=>{for(let r of e.keys())t.delete(r);return t}},RL={k:1.2,b:.7,d:.5},ML=(t,e,r,n,i,o)=>{let{k:s,b:a,d:c}=o;return Math.log(1+(r-e+.5)/(e+.5))*(c+t*(s+1)/(t+s*(1-a+a*n/i)))},jL=t=>(e,r,n)=>{let 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,s=typeof t.boostTerm=="function"?t.boostTerm(e,r,n):1;return{term:e,fuzzy:i,prefix:o,termBoost:s}},Tv={idField:"id",extractField:(t,e)=>t[e],stringifyField:(t,e)=>t.toString(),tokenize:t=>t.split(UL),processTerm:t=>t.toLowerCase(),fields:void 0,searchOptions:void 0,storeFields:[],logger:(t,e)=>{typeof console?.[t]=="function"&&console[t](e)},autoVacuum:!0},bP={combineWith:Rv,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:RL},DL={combineWith:PP,prefix:(t,e,r)=>e===r.length-1},Nv={batchSize:1e3,batchWait:10},Cv={minDirtFactor:.1,minDirtCount:20},Av={...Nv,...Cv},LL=(t,e)=>{t.includes(e)||t.push(e)},vP=(t,e)=>{for(let r of e)t.includes(r)||t.push(r)},wP=({score:t},{score:e})=>e-t,xP=()=>new Map,Lh=t=>{let e=new Map;for(let r of Object.keys(t))e.set(parseInt(r,10),t[r]);return e},Uh=async t=>{let e=new Map,r=0;for(let n of Object.keys(t))e.set(parseInt(n,10),t[n]),++r%1e3===0&&await TP(0);return e},TP=t=>new Promise(e=>setTimeout(e,t)),UL=/[\n\r\p{Z}\p{P}]+/u;var AP=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(`
83
+ `);this.baseURL=o.baseURL,this.timeout=o.timeout??Iv.DEFAULT_TIMEOUT,this.logger=o.logger??console;let s="warn";this.logLevel=s,this.logLevel=nv(o.logLevel,"ClientOptions.logLevel",this)??nv(qd("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??s,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??L1(),B(this,jh,Z1,"f"),this._options=o,this.apiKey=typeof r=="string"?r:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return ve([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return ve([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return ve([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new ee(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Yo}`}defaultIdempotencyKey(){return`stainless-node-retry-${Yb()}`}makeStatusError(e,r,n,i){return Jt.generate(e,r,n,i)}buildURL(e,r,n){let i=!E(this,Sv,"m",hP).call(this)&&n||this.baseURL,o=T1(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return A1(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new ee("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new la(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,o=i.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(i);let{req:s,url:a,timeout:c}=await this.buildRequest(i,{retryCount:o-r});await this.prepareRequest(s,{url:a,options:i});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Yt(this).debug(`[${l}] sending request`,no({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:s.headers})),i.signal?.aborted)throw new ar;let f=new AbortController,p=await this.fetchWithTimeout(a,s,c,f).catch(vd),h=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new ar;let b=to(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Yt(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${y}`),Yt(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${y})`,no({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),this.retryRequest(i,r,n??l);throw Yt(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),Yt(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,no({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),b?new cl:new Jo({cause:p})}let m=[...p.headers.entries()].filter(([y])=>y==="request-id").map(([y,b])=>", "+y+": "+JSON.stringify(b)).join(""),g=`[${l}${u}${m}] ${s.method} ${a} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${h-d}ms`;if(!p.ok){let y=await this.shouldRetry(p);if(r&&y){let F=`retrying, ${r} attempts remaining`;return await U1(p.body),Yt(this).info(`${g} - ${F}`),Yt(this).debug(`[${l}] response error (${F})`,no({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),this.retryRequest(i,r,n??l,p.headers)}let b=y?"error; no more retries left":"error; not retryable";Yt(this).info(`${g} - ${b}`);let $=await p.text().catch(F=>vd(F).message),R=uh($),T=R?void 0:$;throw Yt(this).debug(`[${l}] response error (${b})`,no({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:T,durationMs:Date.now()-d})),this.makeStatusError(p.status,R,T,p.headers)}return Yt(this).info(g),Yt(this).debug(`[${l}] response start`,no({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),{response:p,options:i,controller:f,requestLogID:l,retryOfRequestLogID:n,startTime:d}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Id(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:o,method:s,...a}=r||{},c=this._makeAbort(i);o&&o.addEventListener("abort",c,{once:!0});let l=setTimeout(c,n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...a};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let o,s=i?.get("retry-after-ms");if(s){let c=parseFloat(s);Number.isNaN(c)||(o=c)}let a=i?.get("retry-after");if(a&&!o){let c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(!(o&&0<=o&&o<60*1e3)){let c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,c)}return await C1(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}calculateNonstreamingTimeout(e,r){if(36e5*e/128e3>6e5||r!=null&&e>r)throw new ee("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:o,query:s,defaultBaseURL:a}=n,c=this.buildURL(o,s,a);"timeout"in n&&N1("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:l,retryCount:r});return{req:{method:i,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let s=ve([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...D1(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=ve([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:dh(e)}:E(this,jh,"f").call(this,{body:e,headers:n})}};Iv=Pt,jh=new WeakMap,Sv=new WeakSet,hP=function(){return this.baseURL!=="https://api.anthropic.com"};Pt.Anthropic=Iv;Pt.HUMAN_PROMPT=gP;Pt.AI_PROMPT=yP;Pt.DEFAULT_TIMEOUT=6e5;Pt.AnthropicError=ee;Pt.APIError=Jt;Pt.APIConnectionError=Jo;Pt.APIConnectionTimeoutError=cl;Pt.APIUserAbortError=ar;Pt.NotFoundError=pl;Pt.ConflictError=fl;Pt.RateLimitError=hl;Pt.BadRequestError=ll;Pt.AuthenticationError=ul;Pt.InternalServerError=gl;Pt.PermissionDeniedError=dl;Pt.UnprocessableEntityError=ml;Pt.toFile=yh;var ki=class extends Pt{constructor(){super(...arguments),this.completions=new ha(this),this.messages=new rs(this),this.models=new ya(this),this.beta=new Kn(this)}};ki.Completions=ha;ki.Messages=rs;ki.Models=ya;ki.Beta=Kn;var _P=new Ce("AnthropicChat"),Dh=class extends sl{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 ki({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),i=!0,o=[];for(;i;){i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),_P.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,f)=>{let p=this.parseMessageBlock(f,!0);this.config.onAIMessage?.([...o,p],!0),r?.([...o,p])});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(_P.debug("Message received",a),a.content?.length){let u=this.messageGroup.add(this.parseMessageBlock(a,!1));o.push(u)}let c=[],l=[];if(await Promise.all(a.content.map(async u=>{if(u.type!="tool_use")return;let d=this.findToolBySafeName(u.name);try{let f=await this.executeTool(d,u.input);l.push({type:"tool_result",tool_use_id:u.id,content:f}),c.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolSuccessResponse:f,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}catch(f){let p=f?.message||"An unknown error occurred";l.push({type:"tool_result",tool_use_id:u.id,content:`Error performing tool call ${u.name}: ${p}`}),c.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolErrorResponse:p,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}})),l.length>0){let u=this.messageGroup.add({id:"msg-"+sr(),sections:c,data:{role:"user",content:l}});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,r){let n=[];for(let i of e.content)if(i.type=="thinking")n.push({type:"thinking",text:i.thinking||""});else if(i.type=="text")n.push({type:"text",text:i.text||""});else if(i.type=="tool_use"){let o=this.findToolBySafeName(i.name);n.push({type:"tool_call",toolName:i.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:i.input,toolCallInstanceID:i.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:e.id,data:{role:e.role,content:e.content},sections:n,source:"assistant",streamingInProgress:r,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 AL="ENTRIES",kP="KEYS",$P="VALUES";var Bd=class{constructor(e,r){let n=e._tree,i=Array.from(n.keys());this.set=e,this._type=r,this._path=i.length>0?[{node:n,keys:i}]:[]}next(){let e=this.dive();return this.backtrack(),e}dive(){if(this._path.length===0)return{done:!0,value:void 0};let{node:e,keys:r}=Al(this._path);if(Al(r)==="")return{done:!1,value:this.result()};let n=e.get(Al(r));return this._path.push({node:n,keys:Array.from(n.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;let e=Al(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}key(){return this.set._prefix+this._path.map(({keys:e})=>Al(e)).filter(e=>e!=="").join("")}value(){return Al(this._path).node.get("")}result(){switch(this._type){case $P:return this.value();case kP:return this.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){return this}},Al=t=>t[t.length-1],zL=(t,e,r)=>{let n=new Map;if(e===void 0)return n;let i=e.length+1,o=i+r,s=new Uint8Array(o*i).fill(r+1);for(let a=0;a<i;++a)s[a]=a;for(let a=1;a<o;++a)s[a*i]=a;return SP(t,e,r,n,s,1,i,""),n},SP=(t,e,r,n,i,o,s,a)=>{let c=o*s;e:for(let l of t.keys())if(l===""){let u=i[c-1];u<=r&&n.set(a,[t.get(l),u])}else{let u=o;for(let d=0;d<l.length;++d,++u){let f=l[d],p=s*u,h=p-s,m=i[p],g=Math.max(0,u-r-1),y=Math.min(s-1,u+r);for(let b=g;b<y;++b){let $=f!==e[b],R=i[h+b]+ +$,T=i[h+b+1]+1,P=i[p+b]+1,F=i[p+b+1]=Math.min(R,T,P);F<m&&(m=F)}if(m>r)continue e}SP(t.get(l),e,r,n,i,u,s,a+l)}},Wd=class t{constructor(e=new Map,r=""){this._size=void 0,this._tree=e,this._prefix=r}atPrefix(e){if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");let[r,n]=Zh(this._tree,e.slice(this._prefix.length));if(r===void 0){let[i,o]=Ov(n);for(let s of i.keys())if(s!==""&&s.startsWith(o)){let a=new Map;return a.set(s.slice(o.length),i.get(s)),new t(a,e)}}return new t(r,e)}clear(){this._size=void 0,this._tree.clear()}delete(e){return this._size=void 0,NL(this._tree,e)}entries(){return new Bd(this,AL)}forEach(e){for(let[r,n]of this)e(r,n,this)}fuzzyGet(e,r){return zL(this._tree,e,r)}get(e){let r=zv(this._tree,e);return r!==void 0?r.get(""):void 0}has(e){let r=zv(this._tree,e);return r!==void 0&&r.has("")}keys(){return new Bd(this,kP)}set(e,r){if(typeof e!="string")throw new Error("key must be a string");return this._size=void 0,Ev(this._tree,e).set("",r),this}get size(){if(this._size)return this._size;this._size=0;let e=this.entries();for(;!e.next().done;)this._size+=1;return this._size}update(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;let n=Ev(this._tree,e);return n.set("",r(n.get(""))),this}fetch(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;let n=Ev(this._tree,e),i=n.get("");return i===void 0&&n.set("",i=r()),i}values(){return new Bd(this,$P)}[Symbol.iterator](){return this.entries()}static from(e){let r=new t;for(let[n,i]of e)r.set(n,i);return r}static fromObject(e){return t.from(Object.entries(e))}},Zh=(t,e,r=[])=>{if(e.length===0||t==null)return[t,r];for(let n of t.keys())if(n!==""&&e.startsWith(n))return r.push([t,n]),Zh(t.get(n),e.slice(n.length),r);return r.push([t,e]),Zh(void 0,"",r)},zv=(t,e)=>{if(e.length===0||t==null)return t;for(let r of t.keys())if(r!==""&&e.startsWith(r))return zv(t.get(r),e.slice(r.length))},Ev=(t,e)=>{let r=e.length;e:for(let n=0;t&&n<r;){for(let o of t.keys())if(o!==""&&e[n]===o[0]){let s=Math.min(r-n,o.length),a=1;for(;a<s&&e[n+a]===o[a];)++a;let c=t.get(o);if(a===o.length)t=c;else{let l=new Map;l.set(o.slice(a),c),t.set(e.slice(n,n+a),l),t.delete(o),t=l}n+=a;continue e}let i=new Map;return t.set(e.slice(n),i),i}return t},NL=(t,e)=>{let[r,n]=Zh(t,e);if(r!==void 0){if(r.delete(""),r.size===0)IP(n);else if(r.size===1){let[i,o]=r.entries().next().value;EP(n,i,o)}}},IP=t=>{if(t.length===0)return;let[e,r]=Ov(t);if(e.delete(r),e.size===0)IP(t.slice(0,-1));else if(e.size===1){let[n,i]=e.entries().next().value;n!==""&&EP(t.slice(0,-1),n,i)}},EP=(t,e,r)=>{if(t.length===0)return;let[n,i]=Ov(t);n.set(i+e,r),n.delete(i)},Ov=t=>t[t.length-1],Rv="or",PP="and",CL="and_not",Gd=class t{constructor(e){if(e?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');let r=e.autoVacuum==null||e.autoVacuum===!0?Av:e.autoVacuum;this._options={...Tv,...e,autoVacuum:r,searchOptions:{...bP,...e.searchOptions||{}},autoSuggestOptions:{...DL,...e.autoSuggestOptions||{}}},this._index=new Wd,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=Cv,this.addFields(this._options.fields)}add(e){let{extractField:r,stringifyField:n,tokenize:i,processTerm:o,fields:s,idField:a}=this._options,c=r(e,a);if(c==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);if(this._idToShortId.has(c))throw new Error(`MiniSearch: duplicate ID ${c}`);let l=this.addDocumentId(c);this.saveStoredFields(l,e);for(let u of s){let d=r(e,u);if(d==null)continue;let f=i(n(d,u),u),p=this._fieldIds[u],h=new Set(f).size;this.addFieldLength(l,p,this._documentCount-1,h);for(let m of f){let g=o(m,u);if(Array.isArray(g))for(let y of g)this.addTerm(p,l,y);else g&&this.addTerm(p,l,g)}}}addAll(e){for(let r of e)this.add(r)}addAllAsync(e,r={}){let{chunkSize:n=10}=r,i={chunk:[],promise:Promise.resolve()},{chunk:o,promise:s}=e.reduce(({chunk:a,promise:c},l,u)=>(a.push(l),(u+1)%n===0?{chunk:[],promise:c.then(()=>new Promise(d=>setTimeout(d,0))).then(()=>this.addAll(a))}:{chunk:a,promise:c}),i);return s.then(()=>this.addAll(o))}remove(e){let{tokenize:r,processTerm:n,extractField:i,stringifyField:o,fields:s,idField:a}=this._options,c=i(e,a);if(c==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);let l=this._idToShortId.get(c);if(l==null)throw new Error(`MiniSearch: cannot remove document with ID ${c}: it is not in the index`);for(let u of s){let d=i(e,u);if(d==null)continue;let f=r(o(d,u),u),p=this._fieldIds[u],h=new Set(f).size;this.removeFieldLength(l,p,this._documentCount,h);for(let m of f){let g=n(m,u);if(Array.isArray(g))for(let y of g)this.removeTerm(p,l,y);else g&&this.removeTerm(p,l,g)}}this._storedFields.delete(l),this._documentIds.delete(l),this._idToShortId.delete(c),this._fieldLength.delete(l),this._documentCount-=1}removeAll(e){if(e)for(let r of e)this.remove(r);else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new Wd,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}}discard(e){let r=this._idToShortId.get(e);if(r==null)throw new Error(`MiniSearch: cannot discard document with ID ${e}: it is not in the index`);this._idToShortId.delete(e),this._documentIds.delete(r),this._storedFields.delete(r),(this._fieldLength.get(r)||[]).forEach((n,i)=>{this.removeFieldLength(r,i,this._documentCount,n)}),this._fieldLength.delete(r),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()}maybeAutoVacuum(){if(this._options.autoVacuum===!1)return;let{minDirtFactor:e,minDirtCount:r,batchSize:n,batchWait:i}=this._options.autoVacuum;this.conditionalVacuum({batchSize:n,batchWait:i},{minDirtCount:r,minDirtFactor:e})}discardAll(e){let r=this._options.autoVacuum;try{this._options.autoVacuum=!1;for(let n of e)this.discard(n)}finally{this._options.autoVacuum=r}this.maybeAutoVacuum()}replace(e){let{idField:r,extractField:n}=this._options,i=n(e,r);this.discard(i),this.add(e)}vacuum(e={}){return this.conditionalVacuum(e)}conditionalVacuum(e,r){return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&r,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(()=>{let n=this._enqueuedVacuumConditions;return this._enqueuedVacuumConditions=Cv,this.performVacuuming(e,n)}),this._enqueuedVacuum)):this.vacuumConditionsMet(r)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)}async performVacuuming(e,r){let n=this._dirtCount;if(this.vacuumConditionsMet(r)){let i=e.batchSize||Nv.batchSize,o=e.batchWait||Nv.batchWait,s=1;for(let[a,c]of this._index){for(let[l,u]of c)for(let[d]of u)this._documentIds.has(d)||(u.size<=1?c.delete(l):u.delete(d));this._index.get(a).size===0&&this._index.delete(a),s%i===0&&await new Promise(l=>setTimeout(l,o)),s+=1}this._dirtCount-=n}await null,this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null}vacuumConditionsMet(e){if(e==null)return!0;let{minDirtCount:r,minDirtFactor:n}=e;return r=r||Av.minDirtCount,n=n||Av.minDirtFactor,this.dirtCount>=r&&this.dirtFactor>=n}get isVacuuming(){return this._currentVacuum!=null}get dirtCount(){return this._dirtCount}get dirtFactor(){return this._dirtCount/(1+this._documentCount+this._dirtCount)}has(e){return this._idToShortId.has(e)}getStoredFields(e){let r=this._idToShortId.get(e);if(r!=null)return this._storedFields.get(r)}search(e,r={}){let{searchOptions:n}=this._options,i={...n,...r},o=this.executeQuery(e,r),s=[];for(let[a,{score:c,terms:l,match:u}]of o){let d=l.length||1,f={id:this._documentIds.get(a),score:c*d,terms:Object.keys(u),queryTerms:l,match:u};Object.assign(f,this._storedFields.get(a)),(i.filter==null||i.filter(f))&&s.push(f)}return e===t.wildcard&&i.boostDocument==null||s.sort(wP),s}autoSuggest(e,r={}){r={...this._options.autoSuggestOptions,...r};let n=new Map;for(let{score:o,terms:s}of this.search(e,r)){let a=s.join(" "),c=n.get(a);c!=null?(c.score+=o,c.count+=1):n.set(a,{score:o,terms:s,count:1})}let i=[];for(let[o,{score:s,terms:a,count:c}]of n)i.push({suggestion:o,terms:a,score:s/c});return i.sort(wP),i}get documentCount(){return this._documentCount}get termCount(){return this._index.size}static loadJSON(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)}static async loadJSONAsync(e,r){if(r==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJSAsync(JSON.parse(e),r)}static getDefault(e){if(Tv.hasOwnProperty(e))return Pv(Tv,e);throw new Error(`MiniSearch: unknown option "${e}"`)}static loadJS(e,r){let{index:n,documentIds:i,fieldLength:o,storedFields:s,serializationVersion:a}=e,c=this.instantiateMiniSearch(e,r);c._documentIds=Lh(i),c._fieldLength=Lh(o),c._storedFields=Lh(s);for(let[l,u]of c._documentIds)c._idToShortId.set(u,l);for(let[l,u]of n){let d=new Map;for(let f of Object.keys(u)){let p=u[f];a===1&&(p=p.ds),d.set(parseInt(f,10),Lh(p))}c._index.set(l,d)}return c}static async loadJSAsync(e,r){let{index:n,documentIds:i,fieldLength:o,storedFields:s,serializationVersion:a}=e,c=this.instantiateMiniSearch(e,r);c._documentIds=await Uh(i),c._fieldLength=await Uh(o),c._storedFields=await Uh(s);for(let[u,d]of c._documentIds)c._idToShortId.set(d,u);let l=0;for(let[u,d]of n){let f=new Map;for(let p of Object.keys(d)){let h=d[p];a===1&&(h=h.ds),f.set(parseInt(p,10),await Uh(h))}++l%1e3===0&&await TP(0),c._index.set(u,f)}return c}static instantiateMiniSearch(e,r){let{documentCount:n,nextId:i,fieldIds:o,averageFieldLength:s,dirtCount:a,serializationVersion:c}=e;if(c!==1&&c!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");let l=new t(r);return l._documentCount=n,l._nextId=i,l._idToShortId=new Map,l._fieldIds=o,l._avgFieldLength=s,l._dirtCount=a||0,l._index=new Wd,l}executeQuery(e,r={}){if(e===t.wildcard)return this.executeWildcardQuery(r);if(typeof e!="string"){let f={...r,...e,queries:void 0},p=e.queries.map(h=>this.executeQuery(h,f));return this.combineResults(p,f.combineWith)}let{tokenize:n,processTerm:i,searchOptions:o}=this._options,s={tokenize:n,processTerm:i,...o,...r},{tokenize:a,processTerm:c}=s,d=a(e).flatMap(f=>c(f)).filter(f=>!!f).map(jL(s)).map(f=>this.executeQuerySpec(f,s));return this.combineResults(d,s.combineWith)}executeQuerySpec(e,r){let n={...this._options.searchOptions,...r},i=(n.fields||this._options.fields).reduce((m,g)=>({...m,[g]:Pv(n.boost,g)||1}),{}),{boostDocument:o,weights:s,maxFuzzy:a,bm25:c}=n,{fuzzy:l,prefix:u}={...bP.weights,...s},d=this._index.get(e.term),f=this.termResults(e.term,e.term,1,e.termBoost,d,i,o,c),p,h;if(e.prefix&&(p=this._index.atPrefix(e.term)),e.fuzzy){let m=e.fuzzy===!0?.2:e.fuzzy,g=m<1?Math.min(a,Math.round(e.term.length*m)):m;g&&(h=this._index.fuzzyGet(e.term,g))}if(p)for(let[m,g]of p){let y=m.length-e.term.length;if(!y)continue;h?.delete(m);let b=u*m.length/(m.length+.3*y);this.termResults(e.term,m,b,e.termBoost,g,i,o,c,f)}if(h)for(let m of h.keys()){let[g,y]=h.get(m);if(!y)continue;let b=l*m.length/(m.length+y);this.termResults(e.term,m,b,e.termBoost,g,i,o,c,f)}return f}executeWildcardQuery(e){let r=new Map,n={...this._options.searchOptions,...e};for(let[i,o]of this._documentIds){let s=n.boostDocument?n.boostDocument(o,"",this._storedFields.get(i)):1;r.set(i,{score:s,terms:[],match:{}})}return r}combineResults(e,r=Rv){if(e.length===0)return new Map;let n=r.toLowerCase(),i=OL[n];if(!i)throw new Error(`Invalid combination operator: ${r}`);return e.reduce(i)||new Map}toJSON(){let e=[];for(let[r,n]of this._index){let i={};for(let[o,s]of n)i[o]=Object.fromEntries(s);e.push([r,i])}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:e,serializationVersion:2}}termResults(e,r,n,i,o,s,a,c,l=new Map){if(o==null)return l;for(let u of Object.keys(s)){let d=s[u],f=this._fieldIds[u],p=o.get(f);if(p==null)continue;let h=p.size,m=this._avgFieldLength[f];for(let g of p.keys()){if(!this._documentIds.has(g)){this.removeTerm(f,g,r),h-=1;continue}let y=a?a(this._documentIds.get(g),r,this._storedFields.get(g)):1;if(!y)continue;let b=p.get(g),$=this._fieldLength.get(g)[f],R=ML(b,h,this._documentCount,$,m,c),T=n*i*d*y*R,P=l.get(g);if(P){P.score+=T,LL(P.terms,e);let F=Pv(P.match,r);F?F.push(u):P.match[r]=[u]}else l.set(g,{score:T,terms:[e],match:{[r]:[u]}})}}return l}addTerm(e,r,n){let i=this._index.fetch(n,xP),o=i.get(e);if(o==null)o=new Map,o.set(r,1),i.set(e,o);else{let s=o.get(r);o.set(r,(s||0)+1)}}removeTerm(e,r,n){if(!this._index.has(n)){this.warnDocumentChanged(r,e,n);return}let i=this._index.fetch(n,xP),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)}warnDocumentChanged(e,r,n){for(let i of Object.keys(this._fieldIds))if(this._fieldIds[i]===r){this._options.logger("warn",`MiniSearch: document with ID ${this._documentIds.get(e)} has changed before removal: term "${n}" was not present in field "${i}". Removing a document after it has changed can corrupt the index!`,"version_conflict");return}}addDocumentId(e){let r=this._nextId;return this._idToShortId.set(e,r),this._documentIds.set(r,e),this._documentCount+=1,this._nextId+=1,r}addFields(e){for(let r=0;r<e.length;r++)this._fieldIds[e[r]]=r}addFieldLength(e,r,n,i){let o=this._fieldLength.get(e);o==null&&this._fieldLength.set(e,o=[]),o[r]=i;let a=(this._avgFieldLength[r]||0)*n+i;this._avgFieldLength[r]=a/(n+1)}removeFieldLength(e,r,n,i){if(n===1){this._avgFieldLength[r]=0;return}let o=this._avgFieldLength[r]*n-i;this._avgFieldLength[r]=o/(n-1)}saveStoredFields(e,r){let{storeFields:n,extractField:i}=this._options;if(n==null||n.length===0)return;let o=this._storedFields.get(e);o==null&&this._storedFields.set(e,o={});for(let s of n){let a=i(r,s);a!==void 0&&(o[s]=a)}}};Gd.wildcard=Symbol("*");var Pv=(t,e)=>Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0,OL={[Rv]:(t,e)=>{for(let r of e.keys()){let n=t.get(r);if(n==null)t.set(r,e.get(r));else{let{score:i,terms:o,match:s}=e.get(r);n.score=n.score+i,n.match=Object.assign(n.match,s),vP(n.terms,o)}}return t},[PP]:(t,e)=>{let r=new Map;for(let n of e.keys()){let i=t.get(n);if(i==null)continue;let{score:o,terms:s,match:a}=e.get(n);vP(i.terms,s),r.set(n,{score:i.score+o,terms:i.terms,match:Object.assign(i.match,a)})}return r},[CL]:(t,e)=>{for(let r of e.keys())t.delete(r);return t}},RL={k:1.2,b:.7,d:.5},ML=(t,e,r,n,i,o)=>{let{k:s,b:a,d:c}=o;return Math.log(1+(r-e+.5)/(e+.5))*(c+t*(s+1)/(t+s*(1-a+a*n/i)))},jL=t=>(e,r,n)=>{let 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,s=typeof t.boostTerm=="function"?t.boostTerm(e,r,n):1;return{term:e,fuzzy:i,prefix:o,termBoost:s}},Tv={idField:"id",extractField:(t,e)=>t[e],stringifyField:(t,e)=>t.toString(),tokenize:t=>t.split(UL),processTerm:t=>t.toLowerCase(),fields:void 0,searchOptions:void 0,storeFields:[],logger:(t,e)=>{typeof console?.[t]=="function"&&console[t](e)},autoVacuum:!0},bP={combineWith:Rv,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:RL},DL={combineWith:PP,prefix:(t,e,r)=>e===r.length-1},Nv={batchSize:1e3,batchWait:10},Cv={minDirtFactor:.1,minDirtCount:20},Av={...Nv,...Cv},LL=(t,e)=>{t.includes(e)||t.push(e)},vP=(t,e)=>{for(let r of e)t.includes(r)||t.push(r)},wP=({score:t},{score:e})=>e-t,xP=()=>new Map,Lh=t=>{let e=new Map;for(let r of Object.keys(t))e.set(parseInt(r,10),t[r]);return e},Uh=async t=>{let e=new Map,r=0;for(let n of Object.keys(t))e.set(parseInt(n,10),t[n]),++r%1e3===0&&await TP(0);return e},TP=t=>new Promise(e=>setTimeout(e,t)),UL=/[\n\r\p{Z}\p{P}]+/u;var AP=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",disabled:!t?.knowledgeBase?.allowRagSearch,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(`
84
84
  `)||"- (none)",s=n.filter(a=>a.type=="action").map(a=>"- "+a._functionID).join(`
85
85
  `)||"- (none)";return`Search complete, context has been updated.
86
86
  New information found:
@@ -110,7 +110,7 @@ ${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"ope
110
110
  `;break;case"id":a=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?n(parseInt(g,10)):r(new n_(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:y}));break;default:r(new n_(`Unknown field "${m.length>20?`${m.slice(0,20)}\u2026`:m}"`,{type:"unknown-field",field:m,value:g,line:y}));break}}function p(){c.length>0&&e({id:a,event:l||void 0,data:c.endsWith(`
111
111
  `)?c.slice(0,-1):c}),a=void 0,c="",l=""}function h(m={}){o&&m.consume&&d(o),s=!0,a=void 0,c="",l="",o=""}return{feed:u,reset:h}}function $J(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
112
112
  `,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]===`
113
- `&&n++}}return[e,r]}var i_=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=NM({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 SJ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Is=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},o_=class{constructor(e,r){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=bM(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??SJ}async _authThenStart(){if(!this._authProvider)throw new Eo("No auth provider");let e;try{e=await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Eo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=r_(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let i=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Is(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_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){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},i)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,c=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new i_({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:h}=await u.read();if(h)break;if(p.id&&(s=p.id,a=!0,i?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let m=Pg.parse(JSON.parse(p.data));Sa(m)&&(c=!0,o!==void 0&&(m.id=o)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}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 Eo("No auth provider");if(await qf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Eo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:i}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:_p(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,s),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Is(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:p,scope:h}=nI(a);if(this._resourceMetadataUrl=p,this._scope=h,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Eo;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:p,scope:h,error:m}=nI(a);if(m==="insufficient_scope"){let g=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===g)throw new Is(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=g??void 0,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Eo;return this.send(e)}}throw new Is(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),iz(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let u=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:i},!1);else if(d?.includes("application/json")){let f=await a.json(),p=Array.isArray(f)?f.map(h=>Pg.parse(h)):[Pg.parse(f)];for(let h of p)this.onmessage?.(h)}else throw await a.body?.cancel(),new Is(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Is(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Es={name:"@intelliweave/embedded",version:"2.0.72-beta.10",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.95","@types/lodash":"^4.17.23","@types/react":"^18.3.12",bestzip:"^2.2.1","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.17",vitest:"^4.0.18"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.74.0","@modelcontextprotocol/sdk":"^1.26.0","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.22.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};var er=new Ce("MCPKnowledgeClient"),EJ="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",s_=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(){er.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=r.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",r=new URL(this.config.proxy.url||EJ));let i=new t_({name:Es.name,version:Es.version}),o=new o_(r,{requestInit:{headers:n}});return await i.connect(o),er.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=e,e.onerror=r=>{er.error(`MCP client error: ${r.message}`)},e.onclose=()=>{er.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(b0,r=>{r.params.level=="critical"?er.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?er.error(`[Server] ${r.params.data}`):r.params.level=="error"?er.error(`[Server] ${r.params.data}`):r.params.level=="warning"?er.warn(`[Server] ${r.params.data}`):r.params.level=="info"?er.info(`[Server] ${r.params.data}`):r.params.level=="debug"?er.debug(`[Server] ${r.params.data}`):er.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Sp,r=>{er.debug("Tool list changed",r),this.fetchTools()}),er.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})}er.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,er.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 er.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(),er.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 er.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 PJ=new Ce("Statistics"),Bf=[];async function Dr(t,e){let r={...e,event_id:sr(),event_date:new Date().toISOString(),sdk_version:Es.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Bf.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Bf.length===0))return;let n=Bf.slice();Bf.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){PJ.warn("Failed to submit analytics event:",i),Bf.push(...n);return}}var Ya=new Ce("KnowledgeBase"),sI=1,a_=class t{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>AP(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${sI++}`),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 this.allowGlobalConfigSources&&ht().knowledgeBaseSources&&(e=e.concat(ht().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Ya.debug(`Searching knowledge base for: ${e}`);let r=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async l=>{try{let u=Date.now(),d=await l.query(e);return Ya.debug(`Source '${l.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Ya.warn(`Knowledge source '${l.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&ht().knowledgeBase&&(o=o.concat(ht().knowledgeBase)),o=o.filter(l=>l&&!l.disabled);for(let l=0;l<o.length;l++){let u=o[l];u.id=u.id||`temp.${l}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new Gd({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let c=s.search(e).map(l=>o.find(u=>u.id==l.id));for(let l of o)l.isContext&&(c.find(u=>u.id===l.id)||c.push(l));return this.lastResults=c,Dr(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Ya.debug("Found results:",c),c}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${sI++}`),Ya.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(c,l)=>{Ya.debug(`Calling remote knowledge base action: ${c.id}`);let u={type:"action",userID:this.ai.userID,actionID:c.id,parameters:l},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 f=await d.json();return a(f.updateItems||[]),f.response},a=c=>{for(let l of c){if(!l.id){Ya.warn("KB item skipped since it has no ID.",l);continue}let u=n.find(d=>d.id==l.id);if(u){u.name=l.name||u.name||"",u.content=l.content||u.content||"",u.disabled=l.disabled??u.disabled,u.isContext=l.isContext??u.isContext,u.parameters=l.parameters||u.parameters||[],u.tags=l.tags||u.tags,u.type=l.type||u.type;continue}n.push({...l,action:d=>s(l,d)})}};this.registerSource(r,async c=>{if(o&&i.includes(c))return n;let l={type:"search",userID:this.ai?.userID||"",query:c},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(c)||i.push(c),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.ensureInternalKnowledge(),e}registerMCPSource(e){e.id||(e.id=`external.${sI++}`);let r=new s_(e);return this.registerSource(e.id,n=>r.search(n)),r}};var c_=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
113
+ `&&n++}}return[e,r]}var i_=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=NM({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 SJ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Is=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},o_=class{constructor(e,r){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=bM(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??SJ}async _authThenStart(){if(!this._authProvider)throw new Eo("No auth provider");let e;try{e=await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Eo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=r_(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let i=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Is(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_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){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},i)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,c=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new i_({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:h}=await u.read();if(h)break;if(p.id&&(s=p.id,a=!0,i?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let m=Pg.parse(JSON.parse(p.data));Sa(m)&&(c=!0,o!==void 0&&(m.id=o)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}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 Eo("No auth provider");if(await qf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Eo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:i}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:_p(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,s),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Is(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:p,scope:h}=nI(a);if(this._resourceMetadataUrl=p,this._scope=h,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Eo;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:p,scope:h,error:m}=nI(a);if(m==="insufficient_scope"){let g=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===g)throw new Is(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=g??void 0,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Eo;return this.send(e)}}throw new Is(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),iz(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let u=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:i},!1);else if(d?.includes("application/json")){let f=await a.json(),p=Array.isArray(f)?f.map(h=>Pg.parse(h)):[Pg.parse(f)];for(let h of p)this.onmessage?.(h)}else throw await a.body?.cancel(),new Is(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Is(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Es={name:"@intelliweave/embedded",version:"2.0.72-beta.11",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.95","@types/lodash":"^4.17.23","@types/react":"^18.3.12",bestzip:"^2.2.1","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.17",vitest:"^4.0.18"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.74.0","@modelcontextprotocol/sdk":"^1.26.0","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.22.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};var er=new Ce("MCPKnowledgeClient"),EJ="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",s_=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(){er.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=r.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",r=new URL(this.config.proxy.url||EJ));let i=new t_({name:Es.name,version:Es.version}),o=new o_(r,{requestInit:{headers:n}});return await i.connect(o),er.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=e,e.onerror=r=>{er.error(`MCP client error: ${r.message}`)},e.onclose=()=>{er.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(b0,r=>{r.params.level=="critical"?er.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?er.error(`[Server] ${r.params.data}`):r.params.level=="error"?er.error(`[Server] ${r.params.data}`):r.params.level=="warning"?er.warn(`[Server] ${r.params.data}`):r.params.level=="info"?er.info(`[Server] ${r.params.data}`):r.params.level=="debug"?er.debug(`[Server] ${r.params.data}`):er.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Sp,r=>{er.debug("Tool list changed",r),this.fetchTools()}),er.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})}er.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,er.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 er.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(),er.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 er.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 PJ=new Ce("Statistics"),Bf=[];async function Dr(t,e){let r={...e,event_id:sr(),event_date:new Date().toISOString(),sdk_version:Es.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Bf.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Bf.length===0))return;let n=Bf.slice();Bf.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){PJ.warn("Failed to submit analytics event:",i),Bf.push(...n);return}}var Ya=new Ce("KnowledgeBase"),sI=1,a_=class t{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>AP(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${sI++}`),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 this.allowGlobalConfigSources&&ht().knowledgeBaseSources&&(e=e.concat(ht().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Ya.debug(`Searching knowledge base for: ${e}`);let r=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async l=>{try{let u=Date.now(),d=await l.query(e);return Ya.debug(`Source '${l.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Ya.warn(`Knowledge source '${l.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&ht().knowledgeBase&&(o=o.concat(ht().knowledgeBase)),o=o.filter(l=>l&&!l.disabled);for(let l=0;l<o.length;l++){let u=o[l];u.id=u.id||`temp.${l}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new Gd({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let c=s.search(e).map(l=>o.find(u=>u.id==l.id));for(let l of o)l.isContext&&(c.find(u=>u.id===l.id)||c.push(l));return this.lastResults=c,Dr(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Ya.debug("Found results:",c),c}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${sI++}`),Ya.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(c,l)=>{Ya.debug(`Calling remote knowledge base action: ${c.id}`);let u={type:"action",userID:this.ai.userID,actionID:c.id,parameters:l},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 f=await d.json();return a(f.updateItems||[]),f.response},a=c=>{for(let l of c){if(!l.id){Ya.warn("KB item skipped since it has no ID.",l);continue}let u=n.find(d=>d.id==l.id);if(u){u.name=l.name||u.name||"",u.content=l.content||u.content||"",u.disabled=l.disabled??u.disabled,u.isContext=l.isContext??u.isContext,u.parameters=l.parameters||u.parameters||[],u.tags=l.tags||u.tags,u.type=l.type||u.type;continue}n.push({...l,action:d=>s(l,d)})}};this.registerSource(r,async c=>{if(o&&i.includes(c))return n;let l={type:"search",userID:this.ai?.userID||"",query:c},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(c)||i.push(c),a(d.items),n})}clone(e){let r=new t(e);return r._sources=this._sources.slice(),r._windowSources=this._windowSources.slice(),r.manualEntries=this.manualEntries.slice(),r.allowGlobalConfigSources=this.allowGlobalConfigSources,r.allowWindowSources=this.allowWindowSources,r.allowRagSearch=this.allowRagSearch,r.ensureInternalKnowledge(),r}registerMCPSource(e){e.id||(e.id=`external.${sI++}`);let r=new s_(e);return this.registerSource(e.id,n=>r.search(n)),r}};var c_=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
114
114
 
115
115
  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}
116
116
 
@@ -129,7 +129,7 @@ ${e.extractions.map(i=>`- ${i.name} (${i.type}): ${i.description||"No descriptio
129
129
  `,n=await this.instruct({...e,instruction:r});if(n=n.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),e.allowMultiple){let i=n.split(`
130
130
  `).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of i)try{o.push(JSON.parse(s))}catch(a){console.error("Failed to parse line as JSON:",s,a.message)}return o}else return[JSON.parse(n.trim())]}async generateMarkdown(e){return this.instruct({...e,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(e){let r=this.ai.clone();return r.resetConversation(),r.getContextPrefix=async()=>e.instruction,e.callback&&r.addEventListener("output",n=>{e.callback(n.detail.message)}),e.allowKB||(r.knowledgeBase._sources=[]),await r.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(n=>n.text())}};var zu=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>e?.text||"")?.filter(e=>!!e)?.join(`
131
131
 
132
- `)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,r)=>e+(r.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(r=>r.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(r=>r.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(r=>!!r)[0]||null}};var l_=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(r=>r.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,r=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(n,i)=>await this.runQuery(e,n.query)}])}remove(e){this.subagents=this.subagents.filter(r=>r.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,r){let n=e.apiKey||this.ai.apiKey,i=this.cachedSubagents[n];return i||(i=new Nu,await i.load(n,e.config),this.cachedSubagents[n]=i),i=i.clone(),i.knowledgeBase.allowGlobalConfigSources=!1,i.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&i.knowledgeBase.reset(),e.knowledge&&i.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(i),(await i.sendMessage(r)).text()}};var Ln=new Ce("Main"),CM=new Set,Qa=class Qa extends EventTarget{constructor(){super(...arguments);this.conversationID=sr();this.knowledgeBase=new a_(this);this.subAgents=new l_(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new c_(this);this.userID=I1();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:Qa.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(r,n){if(this.apiKey=r,!r)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{Ln.debug("Loading configuration...");let i=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r})});if(!i.ok)throw new Error(`Failed to load configuration: ${i.status} ${i.statusText}`);try{this.config=await i.json(),Ln.debug("Config loaded successfully:",this.config),n&&(this.config={...this.config,...n}),this.config&&Ln.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){Ln.error("Failed to parse JSON response:",o);try{let s=await i.clone().text();Ln.error("Raw response that failed parsing:",s)}catch{Ln.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let i=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!i.ok)throw new Error(`Failed to load VAD model: ${i.status} ${i.statusText}`);this.vadModel=await i.blob()}catch(i){Ln.warn(`Failed to load VAD model, some features will be unavailable. ${i.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let i of this.config.knowledge||[])i.url&&i.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:i.id,searchToolName:i.mcpSearchToolName,baseURL:i.url}):i.url&&this.knowledgeBase.registerSourceFromURL(i.url);for(let i of this.config.knowledge||[])i.entries?.length&&this.knowledgeBase.registerSource(i.id,()=>i.entries||[]);if(this.config.mcpServers)for(let i of this.config.mcpServers)this.knowledgeBase.registerMCPSource(i);for(let i of this.config.subagents||[])this.subAgents.register(i);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(i){throw Ln.warn("Failed to load:",i),this.error=i,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:i}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:i}})),i}}setModel(r){let n=this.models.find(o=>o.id==r);if(!n)throw new Error(`Model with ID "${r}" not found.`);let i={...n.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(i):n.config.providerID==="anthropic"?this.currentModel=new Dh(i):this.currentModel=new ch(i),this.currentModel.id=n.id,this.currentModel.metadata=n}async getContextPrefix(){let r=ht().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof r=="function"&&(r=await r()),r}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let r=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let n=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:n}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,data:sh(`
132
+ `)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,r)=>e+(r.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(r=>r.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(r=>r.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(r=>!!r)[0]||null}};var l_=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(r=>r.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,r=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(n,i)=>await this.runQuery(e,n.query)}])}remove(e){this.subagents=this.subagents.filter(r=>r.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,r){let n=e.apiKey||this.ai.apiKey,i=this.cachedSubagents[n];return i||(i=new Nu,await i.load(n,e.config),this.cachedSubagents[n]=i),i=i.clone(),i.knowledgeBase.allowGlobalConfigSources=!1,i.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&i.knowledgeBase.reset(),i.knowledgeBase.allowRagSearch=!e.disableRagSearch,e.knowledge&&i.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(i),(await i.sendMessage(r)).text()}};var Ln=new Ce("Main"),CM=new Set,Qa=class Qa extends EventTarget{constructor(){super(...arguments);this.conversationID=sr();this.knowledgeBase=new a_(this);this.subAgents=new l_(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new c_(this);this.userID=I1();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:Qa.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(r,n){if(this.apiKey=r,!r)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{Ln.debug("Loading configuration...");let i=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r})});if(!i.ok)throw new Error(`Failed to load configuration: ${i.status} ${i.statusText}`);try{this.config=await i.json(),Ln.debug("Config loaded successfully:",this.config),n&&(this.config={...this.config,...n}),this.config&&Ln.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){Ln.error("Failed to parse JSON response:",o);try{let s=await i.clone().text();Ln.error("Raw response that failed parsing:",s)}catch{Ln.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let i=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!i.ok)throw new Error(`Failed to load VAD model: ${i.status} ${i.statusText}`);this.vadModel=await i.blob()}catch(i){Ln.warn(`Failed to load VAD model, some features will be unavailable. ${i.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let i of this.config.knowledge||[])i.url&&i.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:i.id,searchToolName:i.mcpSearchToolName,baseURL:i.url}):i.url&&this.knowledgeBase.registerSourceFromURL(i.url);for(let i of this.config.knowledge||[])i.entries?.length&&this.knowledgeBase.registerSource(i.id,()=>i.entries||[]);if(this.config.mcpServers)for(let i of this.config.mcpServers)this.knowledgeBase.registerMCPSource(i);for(let i of this.config.subagents||[])this.subAgents.register(i);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(i){throw Ln.warn("Failed to load:",i),this.error=i,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:i}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:i}})),i}}setModel(r){let n=this.models.find(o=>o.id==r);if(!n)throw new Error(`Model with ID "${r}" not found.`);let i={...n.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(i):n.config.providerID==="anthropic"?this.currentModel=new Dh(i):this.currentModel=new ch(i),this.currentModel.id=n.id,this.currentModel.metadata=n}async getContextPrefix(){let r=ht().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof r=="function"&&(r=await r()),r}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let r=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let n=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:n}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,data:sh(`
133
133
  # RAG search
134
134
  Use the \`search\` tool proactively as much as possible to find missing information or tools.
135
135
  Use the \`search\` tool when you are unsure about specific details or actions to take.
@@ -150,7 +150,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
150
150
  === TOOLS ===
151
151
 
152
152
  `+this.currentModel.toolGroup.getAll().map(l=>"- "+l.data?.name).join(`
153
- `),this._lastSystemMsg!=c&&(this._lastSystemMsg=c,this.submitAnalyticsEvent({type:"system-msg",txt:c}));for(let l of o)for(let u of l.sections||[])if(u.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:u.text||""});else if(u.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:u.text||""});else if(u.type=="tool_call"){let d=s.toolResult(u.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:u.toolKbID||"",actionName:u.toolKbName||"",value:u.toolParameters,result:d?.toolErrorResponse||d?.toolSuccessResponse,isError:!!d?.toolErrorResponse})}else u.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(r,n){let i=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:r,input:n,ai:this}}));let o=await r.action(n,this),s=Date.now()-i;return Dr(this,{event_type:"tool_call",value_str:r.id||"",event_properties:{tool_args:n,execution_time_ms:s,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:r,input:n,ai:this,result:o}})),o}catch(o){let s=Date.now()-i;throw Dr(this,{event_type:"tool_call",value_str:r.id||"",event_properties:{tool_args:n,execution_time_ms:s,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:r,input:n,ai:this,error:o}})),o}}submitAnalyticsEvent(r){if(ht().analytics===!1||this.config?.analytics===!1)return;let n=fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(i=>{Ln.debug("Failed to submit analytics event:",i)});this.activeAnalyticsPromises.push(n),n.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(i=>i!==n)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=sr(),this._lastSystemMsg="")}insertAssistantMessage(r){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(r)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(r){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(r?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${r.type}`);this.conversationID=r.conversationID;for(let n of r.messages)this.currentModel.messageGroup.add(n)}clone(){let r=new Qa;return r.apiKey=this.apiKey,r.config=this.config,r.models=this.models,this.config?.id&&r.setModel(this.config.id),r.audio=this.audio,r.vadModel=this.vadModel,r.userID=this.userID,r.knowledgeBase=this.knowledgeBase.clone(),r}get messages(){return this.currentModel?.messageGroup.items||[]}};Qa.version=Es.version,Qa.builtInActionsVersion="1.0.0",Ln.debug(`Loaded: version=${Es.version} builtInActionsVersion=${Qa.builtInActionsVersion}`);var Nu=Qa;var yn=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(r={},n=""){this.register();let i=document.createElement(this.tagName);for(let o in r)i.setAttribute(o,r[o]);return i.onBeforeCreate(),i.innerHTML=n,i}static add(r={},n=""){this.register();let i=o=>o.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;");return`<${this.tagName} ${Object.keys(r).map(o=>`${o}="${i(r[o]+"")}"`).join(" ")}>${n}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(r,n,i){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(r,n)=>this.getAttribute(n.toString())||"",set:(r,n,i)=>(this.getAttribute(n.toString())===i||(i?this.setAttribute(n.toString(),i):this.removeAttribute(n.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(r,n)=>this._state[n],set:(r,n,i)=>(this._state[n]=i,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(r){return!!this.root?.getElementById(r)}child(r){let n=this.root?.getElementById(r);if(!n)throw new Error(`Child with ID ${r} not found`);return n}};yn.observedAttributes=[],yn.tagName="",yn._isRegistered=!1;var OM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var RM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var MM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Wf=class extends yn{constructor(){super(...arguments);this.html=()=>`
153
+ `),this._lastSystemMsg!=c&&(this._lastSystemMsg=c,this.submitAnalyticsEvent({type:"system-msg",txt:c}));for(let l of o)for(let u of l.sections||[])if(u.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:u.text||""});else if(u.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:u.text||""});else if(u.type=="tool_call"){let d=s.toolResult(u.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:u.toolKbID||"",actionName:u.toolKbName||"",value:u.toolParameters,result:d?.toolErrorResponse||d?.toolSuccessResponse,isError:!!d?.toolErrorResponse})}else u.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(r,n){let i=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:r,input:n,ai:this}}));let o=await r.action(n,this),s=Date.now()-i;return Dr(this,{event_type:"tool_call",value_str:r.id||"",event_properties:{tool_args:n,execution_time_ms:s,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:r,input:n,ai:this,result:o}})),o}catch(o){let s=Date.now()-i;throw Dr(this,{event_type:"tool_call",value_str:r.id||"",event_properties:{tool_args:n,execution_time_ms:s,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:r,input:n,ai:this,error:o}})),o}}submitAnalyticsEvent(r){if(ht().analytics===!1||this.config?.analytics===!1)return;let n=fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(i=>{Ln.debug("Failed to submit analytics event:",i)});this.activeAnalyticsPromises.push(n),n.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(i=>i!==n)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=sr(),this._lastSystemMsg="")}insertAssistantMessage(r){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(r)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(r){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(r?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${r.type}`);this.conversationID=r.conversationID;for(let n of r.messages)this.currentModel.messageGroup.add(n)}clone(){let r=new Qa;return r.apiKey=this.apiKey,r.config=this.config,r.models=this.models,this.config?.id&&r.setModel(this.config.id),r.audio=this.audio,r.vadModel=this.vadModel,r.userID=this.userID,r.knowledgeBase=this.knowledgeBase.clone(r),r}get messages(){return this.currentModel?.messageGroup.items||[]}};Qa.version=Es.version,Qa.builtInActionsVersion="1.0.0",Ln.debug(`Loaded: version=${Es.version} builtInActionsVersion=${Qa.builtInActionsVersion}`);var Nu=Qa;var yn=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(r={},n=""){this.register();let i=document.createElement(this.tagName);for(let o in r)i.setAttribute(o,r[o]);return i.onBeforeCreate(),i.innerHTML=n,i}static add(r={},n=""){this.register();let i=o=>o.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;");return`<${this.tagName} ${Object.keys(r).map(o=>`${o}="${i(r[o]+"")}"`).join(" ")}>${n}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(r,n,i){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(r,n)=>this.getAttribute(n.toString())||"",set:(r,n,i)=>(this.getAttribute(n.toString())===i||(i?this.setAttribute(n.toString(),i):this.removeAttribute(n.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(r,n)=>this._state[n],set:(r,n,i)=>(this._state[n]=i,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(r){return!!this.root?.getElementById(r)}child(r){let n=this.root?.getElementById(r);if(!n)throw new Error(`Child with ID ${r} not found`);return n}};yn.observedAttributes=[],yn.tagName="",yn._isRegistered=!1;var OM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var RM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var MM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Wf=class extends yn{constructor(){super(...arguments);this.html=()=>`
154
154
 
155
155
  <!-- Styling -->
156
156
  <style>
Binary file
@@ -1334,6 +1334,8 @@ interface SubAgentConfig {
1334
1334
  usageInstructions?: string;
1335
1335
  /** If true, will remove all Persona knowledge entries */
1336
1336
  clearExistingKnowledge?: boolean;
1337
+ /** Disable RAG search for subagents. If true, only KB entries with isContext=true will be used. */
1338
+ disableRagSearch?: boolean;
1337
1339
  /** Extra knowledge base sources for the sub-agent */
1338
1340
  knowledge?: KnowledgeFetcher;
1339
1341
  /** Optional extra configuration for the subagent instance */
@@ -1550,6 +1552,8 @@ declare class KnowledgeBase {
1550
1552
  allowWindowSources: boolean;
1551
1553
  /** If true, allows using knowledge specified in the global configuration object */
1552
1554
  allowGlobalConfigSources: boolean;
1555
+ /** If true, allows the AI to search the knowledge base. If false, essentially disables RAG lookup. */
1556
+ allowRagSearch: boolean;
1553
1557
  /** Constructor */
1554
1558
  constructor(ai: IntelliWeave);
1555
1559
  /** Ensures the internal knowledge is set correctly */
@@ -1578,7 +1582,7 @@ declare class KnowledgeBase {
1578
1582
  /** Create and register an external knowledge base source from a URL */
1579
1583
  registerSourceFromURL(url: string, id?: string): void;
1580
1584
  /** Clone this instance */
1581
- clone(): KnowledgeBase;
1585
+ clone(newIW: IntelliWeave): KnowledgeBase;
1582
1586
  /** Registers an MCP server as a knowledge base source */
1583
1587
  registerMCPSource(config: MCPKnowledgeClient['config']): MCPKnowledgeClient;
1584
1588
  }