@intelliweave/embedded 2.0.72-beta.12 → 2.0.72-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/component/component.d.ts +4 -0
- package/dist/component/component.js +4 -4
- package/dist/intelliweave-wordpress.zip +0 -0
- package/dist/node/node.d.ts +4 -0
- package/dist/node/node.js +5 -5
- package/dist/react/react.d.ts +4 -0
- package/dist/react/react.js +9 -9
- package/dist/script-tag/script-tag.js +4 -4
- package/dist/webpack/index.d.ts +4 -0
- package/dist/webpack/index.js +4 -4
- package/package.json +1 -1
|
@@ -60,6 +60,8 @@ declare class TokenWindowGroup<DataType> {
|
|
|
60
60
|
recalculateTokens(): void;
|
|
61
61
|
/** Add an item to the group */
|
|
62
62
|
add(item: string | TokenWindowGroupItemParams<DataType>): TokenWindowGroupItem<DataType>;
|
|
63
|
+
/** Manually remove an item */
|
|
64
|
+
remove(itemId: string): boolean;
|
|
63
65
|
/** Get all items as a string */
|
|
64
66
|
getAllAsString(): string;
|
|
65
67
|
/** Get all items. Doesn't return disabled items. */
|
|
@@ -1248,6 +1250,8 @@ declare class IntelliWeave extends EventTarget {
|
|
|
1248
1250
|
private _lastSystemMsg;
|
|
1249
1251
|
/** Get the system message prefix, before the KB entries are added */
|
|
1250
1252
|
getContextPrefix(): Promise<string>;
|
|
1253
|
+
/** KB items added in the last run */
|
|
1254
|
+
private lastKBItems;
|
|
1251
1255
|
/** Get system message to send to the AI */
|
|
1252
1256
|
onBeforeMessageProcessing(): Promise<void>;
|
|
1253
1257
|
/** @private Process incoming message(s) from the AI. Can be used to respond to encoded actions in the text response. */
|
|
@@ -37,7 +37,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
|
37
37
|
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Wb.DEFAULT_TIMEOUT,this.logger=a.logger??console;let c="warn";this.logLevel=c,this.logLevel=wb(a.logLevel,"ClientOptions.logLevel",this)??wb(Zo("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??CE(),se(this,oh,RE,"f"),this._options=a,this.apiKey=typeof r=="string"?r:"Missing Key",this.organization=n,this.project=i,this.webhookSecret=o}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,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){}async authHeaders(e){return U([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return bb(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Ro}`}defaultIdempotencyKey(){return`stainless-node-retry-${lb()}`}makeStatusError(e,r,n,i){return Bt.generate(e,r,n,i)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof X?n:new X(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new X(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let i=!I(this,Bb,"m",$1).call(this)&&n||this.baseURL,o=kE(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return $E(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(e){await this._callApiKey()}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 Us(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(Ot(this).debug(`[${l}] sending request`,qi({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:s.headers})),i.signal?.aborted)throw new qt;let f=new AbortController,p=await this.fetchWithTimeout(a,s,c,f).catch(ed),h=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new qt;let b=Qu(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Ot(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${y}`),Ot(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${y})`,qi({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),this.retryRequest(i,r,n??l);throw Ot(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),Ot(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,qi({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),b?new Oo:new Co({cause:p})}let m=[...p.headers.entries()].filter(([y])=>y==="x-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 OE(p.body),Ot(this).info(`${g} - ${F}`),Ot(this).debug(`[${l}] response error (${F})`,qi({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";Ot(this).info(`${g} - ${b}`);let $=await p.text().catch(F=>ed(F).message),R=EE($),T=R?void 0:$;throw Ot(this).debug(`[${l}] response error (${b})`,qi({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 Ot(this).info(g),Ot(this).debug(`[${l}] response start`,qi({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 sd(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 gi(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}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&&IE("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=U([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))}:{},...NE(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},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=U([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:zm(e)}:I(this,oh,"f").call(this,{body:e,headers:n})}};Wb=be,oh=new WeakMap,Bb=new WeakSet,$1=function(){return this.baseURL!=="https://api.openai.com/v1"};be.OpenAI=Wb;be.DEFAULT_TIMEOUT=6e5;be.OpenAIError=X;be.APIError=Bt;be.APIConnectionError=Co;be.APIConnectionTimeoutError=Oo;be.APIUserAbortError=qt;be.NotFoundError=yc;be.ConflictError=_c;be.RateLimitError=vc;be.BadRequestError=mc;be.AuthenticationError=hc;be.InternalServerError=wc;be.PermissionDeniedError=gc;be.UnprocessableEntityError=bc;be.InvalidWebhookSignatureError=hi;be.toFile=Um;be.Completions=Xs;be.Chat=Do;be.Embeddings=Js;be.Files=Qs;be.Images=na;be.Audio=vi;be.Moderations=oa;be.Models=ia;be.FineTuning=Xn;be.Graders=Wo;be.VectorStores=eo;be.Webhooks=ca;be.Beta=Hn;be.Batches=qs;be.Uploads=Ho;be.Responses=Yi;be.Realtime=Ji;be.Conversations=qo;be.Evals=Bo;be.Containers=Vo;be.Skills=Qi;be.Videos=aa;var or=[];for(let t=0;t<256;++t)or.push((t+256).toString(16).slice(1));function S1(t,e=0){return(or[t[e+0]]+or[t[e+1]]+or[t[e+2]]+or[t[e+3]]+"-"+or[t[e+4]]+or[t[e+5]]+"-"+or[t[e+6]]+or[t[e+7]]+"-"+or[t[e+8]]+or[t[e+9]]+"-"+or[t[e+10]]+or[t[e+11]]+or[t[e+12]]+or[t[e+13]]+or[t[e+14]]+or[t[e+15]]).toLowerCase()}var Gb,U2=new Uint8Array(16);function Hb(){if(!Gb){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Gb=crypto.getRandomValues.bind(crypto)}return Gb(U2)}var Z2=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Xb={randomUUID:Z2};function F2(t,e,r){t=t||{};let n=t.random??t.rng?.()??Hb();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[r+i]=n[i];return e}return S1(n)}function V2(t,e,r){return Xb.randomUUID&&!e&&!t?Xb.randomUUID():F2(t,e,r)}var sr=V2;var Xo=class{constructor(){this.size=4096;this.groups=[]}createGroup(e){let r=new Kb;return r.id=e,this.groups.push(r),r}group(e){return this.groups.find(r=>r.id===e)}static countTokensInText(e){return e==null?e="":typeof e=="number"?e=e+"":typeof e!="string"&&(e=JSON.stringify(e)),Math.ceil(e.length/3)}countTokens(){return this.groups.reduce((e,r)=>e+r.tokenCount,0)}removeOverflow(){let e=this.countTokens(),r=this.groups.reduce((n,i)=>n+i.weight,0);for(;e>this.size;){let n=this.groups.slice().sort((o,s)=>{let a=Math.floor(o.weight/r*this.size),c=Math.floor(s.weight/r*this.size),l=o.tokenCount-a;return s.tokenCount-c-l}),i=this.removeOneItem(n);if(!i)throw new Error("Too many items in the token window that cannot be removed.");e-=i.tokenCount}}removeOneItem(e){for(let r of e){let n=r.items.findIndex(o=>!o.cannotRemove);if(n===-1)continue;let i=r.items[n];return r.items.splice(n,1),r.tokenCount-=i.tokenCount,i}return null}},Kb=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
38
38
|
`;this.itemPadding=0;this.sortFunction=(e,r)=>e.sortOrder!==r.sortOrder?e.sortOrder-r.sortOrder:e.dateAdded!==r.dateAdded?e.dateAdded-r.dateAdded:0}setItemPadding(e){return this.itemPadding=e,this.recalculateTokens(),this}sortBy(e){return this.sortFunction=e,this.items.sort(this.sortFunction),this}setSeparator(e){return this.separator==e?this:(this.separator=e,this.recalculateTokens(),this)}setWeight(e){return this.weight=e,this}recalculateTokens(){this.tokenCount=this.items.reduce((e,r)=>(r.tokenCount=Xo.countTokensInText(typeof r.data=="string"?r.data:JSON.stringify(r.data))+Xo.countTokensInText(this.separator)+this.itemPadding,e+r.tokenCount),0)}add(e){typeof e=="string"&&(e={source:"user",data:e});let r=e;r.id===void 0&&(r.id=sr()),!r.sections?.length&&typeof r.data=="string"?r.text=r.data:r.text=r.sections?.map(i=>{if(i.type==="text")return i.text||"";if(i.type==="tool_call")return`[Tool Call: ${i.toolKbName||i.toolName}] `;if(i.type==="tool_result"&&i.toolErrorResponse)return`[Tool Error: ${i.toolErrorResponse}] `}).filter(i=>!!i).join(`
|
|
39
39
|
|
|
40
|
-
`)||"";let n=this.items.find(i=>i.id===r.id);return n?(this.tokenCount-=n.tokenCount,Object.assign(n,r),r=n):this.items.push(r),r.dateAdded===void 0&&(r.dateAdded=Date.now()),r.sortOrder===void 0&&(r.sortOrder=0),r.disabled===void 0&&(r.disabled=!1),r.source===void 0&&(r.source="user"),r.sections===void 0&&(r.sections=[]),r.tokenCount=r.disabled?0:Xo.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+Xo.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=r.tokenCount,this.items.sort(this.sortFunction),r}getAllAsString(){return this.getAll().map(e=>e.text).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}};function sh(t){let e=(t||"").split(`
|
|
40
|
+
`)||"";let n=this.items.find(i=>i.id===r.id);return n?(this.tokenCount-=n.tokenCount,Object.assign(n,r),r=n):this.items.push(r),r.dateAdded===void 0&&(r.dateAdded=Date.now()),r.sortOrder===void 0&&(r.sortOrder=0),r.disabled===void 0&&(r.disabled=!1),r.source===void 0&&(r.source="user"),r.sections===void 0&&(r.sections=[]),r.tokenCount=r.disabled?0:Xo.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+Xo.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=r.tokenCount,this.items.sort(this.sortFunction),r}remove(e){let r=this.items.findIndex(n=>n.id===e);return r===-1?!1:(this.tokenCount-=this.items[r].tokenCount||0,this.items.splice(r,1),!0)}getAllAsString(){return this.getAll().map(e=>e.text).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}};function sh(t){let e=(t||"").split(`
|
|
41
41
|
`);for(;e.length>0&&e[0].trim()=="";)e.shift();for(;e.length>0&&e[e.length-1].trim()=="";)e.pop();let r=1/0;for(let n of e){let i=n.match(/^\s*/)?.[0].length||0;r=Math.min(r,i)}return r>0&&r<1/0&&(e=e.map(n=>n.substring(r))),e.join(`
|
|
42
42
|
`)}var q2={};function Ko(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:q2}function ht(){return Ko().intelliweave=Ko().intelliweave||Ko().webWeaver||{},Ko().intelliweave}function I1(){if(ht().userID)return ht().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let t=localStorage.getItem("intelliweave.uid")||"";return t||(t=sr(),localStorage.setItem("intelliweave.uid",t),t)}else return sr()}function E1(t){let e=t;if(e?.type=="object"&&e.properties)return t;let r={type:"object",properties:{},required:[]};if(t&&Array.isArray(t)){let n=t;for(let i of n)r.properties[i.name]={type:i.type||"string",description:i.description||""}}return r}var ah=class ah{constructor(e){this.module="IntelliWeave";this.module=e}get debugEnabled(){return ah.debug?!0:typeof window<"u"&&ht().debug}log(...e){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...e)}debug(...e){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...e)}info(...e){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...e)}warn(...e){console.warn(`[IntelliWeave > ${this.module}]`,...e)}error(...e){console.error(`[IntelliWeave > ${this.module}]`,...e)}timer(e,...r){let n=Date.now();return this.debug(`[${e} 0ms] Started`,...r),(...i)=>this.debug(`[${e} ${Math.floor(Date.now()-n)}ms]`,...i)}};ah.debug=!1;var Ce=ah;var P1=new Ce("ChatBase"),sl=class{constructor(e){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let e=new Xo;return e.createGroup("context").setSeparator(`
|
|
43
43
|
|
|
@@ -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.12",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}
|
|
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.13",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(),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,disabled:!this.knowledgeBase.allowRagSearch,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.lastKBItems=[];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,disabled:!this.knowledgeBase.allowRagSearch,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.
|
|
@@ -145,7 +145,7 @@ attachments:
|
|
|
145
145
|
mimetype: "${a.mimeType||""}"
|
|
146
146
|
url: "${a.url}"
|
|
147
147
|
`);s||(o+="```\n"),this.currentModel.contextGroup.add({id:i.id,data:`## ${i.type}: ${i.name}
|
|
148
|
-
${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="function"?i.disabled(this):i.disabled})}else if(i.type=="action"){let o={name:i._functionID,description:sh(i.content),params:E1(i.parameters||[{name:"value",type:"string",description:"Input"}]),callback:s=>this.toolRunKBAction(i,s),canRemove:!i.isContext,kbItem:i};this.currentModel.registerTool(o)}else continue}processIncomingMessage(r,n){if(!n){let i=this.currentModel?.stats?.tokensUsed||0,o=r.reduce((s,a)=>s+(a.usage?.totalTokens||0),0);Dr(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:i}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:n,messages:r}})),this.onAIMessage?.(r,!!n)}async sendMessage(r,n){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),CM.has(this.conversationID)||(CM.add(this.conversationID),Dr(this,{event_type:"session_start"})),Dr(this,{event_type:"message_send",value_str:"",event_properties:{message_length:r.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:r}})),this.submitAnalyticsEvent({type:"message",role:"user",message:r});let i=Date.now(),o=await this.currentModel.sendMessage(r),s=new zu(o);(this._voiceTracker||Ln.debug.bind(Ln))(`LLM response took ${Date.now()-i}ms`);let c=this.currentModel.contextGroup.getAllAsString();c+=`
|
|
148
|
+
${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="function"?i.disabled(this):i.disabled})}else if(i.type=="action"){let o={name:i._functionID,description:sh(i.content),params:E1(i.parameters||[{name:"value",type:"string",description:"Input"}]),callback:s=>this.toolRunKBAction(i,s),canRemove:!i.isContext,kbItem:i};this.currentModel.registerTool(o)}else continue;for(let i of this.lastKBItems)!i.isContext||!i.id||r.find(s=>s.id==i.id)||(this.currentModel.contextGroup.remove(i.id),i._functionID&&this.currentModel.toolGroup.remove(i._functionID));this.lastKBItems=r}processIncomingMessage(r,n){if(!n){let i=this.currentModel?.stats?.tokensUsed||0,o=r.reduce((s,a)=>s+(a.usage?.totalTokens||0),0);Dr(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:i}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:n,messages:r}})),this.onAIMessage?.(r,!!n)}async sendMessage(r,n){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),CM.has(this.conversationID)||(CM.add(this.conversationID),Dr(this,{event_type:"session_start"})),Dr(this,{event_type:"message_send",value_str:"",event_properties:{message_length:r.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:r}})),this.submitAnalyticsEvent({type:"message",role:"user",message:r});let i=Date.now(),o=await this.currentModel.sendMessage(r),s=new zu(o);(this._voiceTracker||Ln.debug.bind(Ln))(`LLM response took ${Date.now()-i}ms`);let c=this.currentModel.contextGroup.getAllAsString();c+=`
|
|
149
149
|
|
|
150
150
|
=== TOOLS ===
|
|
151
151
|
|
|
Binary file
|
package/dist/node/node.d.ts
CHANGED
|
@@ -447,6 +447,8 @@ declare class TokenWindowGroup<DataType> {
|
|
|
447
447
|
recalculateTokens(): void;
|
|
448
448
|
/** Add an item to the group */
|
|
449
449
|
add(item: string | TokenWindowGroupItemParams<DataType>): TokenWindowGroupItem<DataType>;
|
|
450
|
+
/** Manually remove an item */
|
|
451
|
+
remove(itemId: string): boolean;
|
|
450
452
|
/** Get all items as a string */
|
|
451
453
|
getAllAsString(): string;
|
|
452
454
|
/** Get all items. Doesn't return disabled items. */
|
|
@@ -1501,6 +1503,8 @@ declare class IntelliWeave extends EventTarget {
|
|
|
1501
1503
|
private _lastSystemMsg;
|
|
1502
1504
|
/** Get the system message prefix, before the KB entries are added */
|
|
1503
1505
|
getContextPrefix(): Promise<string>;
|
|
1506
|
+
/** KB items added in the last run */
|
|
1507
|
+
private lastKBItems;
|
|
1504
1508
|
/** Get system message to send to the AI */
|
|
1505
1509
|
onBeforeMessageProcessing(): Promise<void>;
|
|
1506
1510
|
/** @private Process incoming message(s) from the AI. Can be used to respond to encoded actions in the text response. */
|
package/dist/node/node.js
CHANGED
|
@@ -9,7 +9,7 @@ import{v4 as j}from"uuid";function A(d){let e=(d||"").split(`
|
|
|
9
9
|
`,yield*t()}function F(){if(y().userID)return y().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let d=localStorage.getItem("intelliweave.uid")||"";return d||(d=j(),localStorage.setItem("intelliweave.uid",d),d)}else return j()}function q(d){let e=d;if(e?.type=="object"&&e.properties)return d;let t={type:"object",properties:{},required:[]};if(d&&Array.isArray(d)){let s=d;for(let n of s)t.properties[n.name]={type:n.type||"string",description:n.description||""}}return t}var E=class E{constructor(e){this.module="IntelliWeave";this.module=e}get debugEnabled(){return E.debug?!0:typeof window<"u"&&y().debug}log(...e){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...e)}debug(...e){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...e)}info(...e){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...e)}warn(...e){console.warn(`[IntelliWeave > ${this.module}]`,...e)}error(...e){console.error(`[IntelliWeave > ${this.module}]`,...e)}timer(e,...t){let s=Date.now();return this.debug(`[${e} 0ms] Started`,...t),(...n)=>this.debug(`[${e} ${Math.floor(Date.now()-s)}ms]`,...n)}};E.debug=!1;var g=E;var S=new g("ONNXModel"),J=class d{constructor(e){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=e,S.debug(`Model input parameters: ${e.inputNames.join(", ")}`),S.debug(`Model output parameters: ${e.outputNames.join(", ")}`)}static isSupported(){return!!d.lib}static async load(e){if(!d.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(S.debug("Loading ONNX runtime"),this.onnx=await d.lib()),S.debug(`Loading model: ${e}`);let t=await this.onnx.InferenceSession.create(e);return new d(t)}makeTensor(e,t,s=0){let n=1;for(let r of t)n*=r;let o;if(e=="float32")o=new d.onnx.Tensor(new Float32Array(n),t);else if(e=="int8")o=new d.onnx.Tensor(new Int8Array(n),t);else if(e=="int16")o=new d.onnx.Tensor(new Int16Array(n),t);else if(e=="int32")o=new d.onnx.Tensor(new Int32Array(n),t);else if(e=="int64")o=new d.onnx.Tensor(new BigInt64Array(n),t);else if(e=="uint8")o=new d.onnx.Tensor(new Uint8Array(n),t);else if(e=="uint16")o=new d.onnx.Tensor(new Uint16Array(n),t);else if(e=="uint32")o=new d.onnx.Tensor(new Uint32Array(n),t);else if(e=="uint64")o=new d.onnx.Tensor(new BigUint64Array(n),t);else throw new Error(`Invalid type: ${e}`);return s!==0&&(e=="int64"||e=="uint64")?o.data.fill(BigInt(s)):s!==0&&o.data.fill(s),o}registerConstant(e,t){if(!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);return this.constantTensors[e]=t,t}makeConstant(e,t,s,n=0){return this.registerConstant(e,this.makeTensor(t,s,n))}registerState(e,t,s){if(t||(t=e),!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);if(!this.session.outputNames.includes(t))throw new Error(`Model does not have an output named: ${t}`);return this.stateTensors[e]={outputName:t,tensor:s},s}makeState(e,t,s,n,o=0){return this.registerState(e,t,this.makeTensor(s,n,o))}async run(e={}){if(this._runActive&&this.ignoreIfBusy)return S.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let t in this.stateTensors)e[t]=this.stateTensors[t].tensor;for(let t in this.constantTensors)e[t]=this.constantTensors[t];try{let t=await this.session.run(e);for(let s in this.stateTensors){let n=t[this.stateTensors[s].outputName];this.stateTensors[s].tensor=n}return t}finally{this._runActive=!1}}resetState(){S.debug("Resetting state tensors");for(let e in this.stateTensors)this.stateTensors[e].tensor.data.fill(0)}};function xe(d,e){let t=e.reduce((a,c)=>a+c.byteLength,0),s=new DataView(new ArrayBuffer(44));s.setUint8(0,82),s.setUint8(1,73),s.setUint8(2,70),s.setUint8(3,70),s.setUint32(4,44+t,!0),s.setUint8(8,87),s.setUint8(9,65),s.setUint8(10,86),s.setUint8(11,69);let n=1,o=32,r=n*o/8,u=d*r;return s.setUint8(12,102),s.setUint8(13,109),s.setUint8(14,116),s.setUint8(15,32),s.setUint32(16,16,!0),s.setUint16(20,3,!0),s.setUint16(22,n,!0),s.setUint32(24,d,!0),s.setUint32(28,u,!0),s.setUint16(32,r,!0),s.setUint16(34,o,!0),s.setUint8(36,100),s.setUint8(37,97),s.setUint8(38,116),s.setUint8(39,97),s.setUint32(40,t,!0),new File([s,...e],"audio.wav",{type:"audio/wav"})}var z=class extends WebSocket{constructor(t){super(t);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(t){this.readyState==WebSocket.OPEN?super.send(t):this.pendingData.push(t)}_onOpen(){for(let t of this.pendingData)super.send(t);this.pendingData=[]}};var V=class{constructor(e,t){this.outputBufferSize=0;this.partialBuffers=[];this.partialBufferOffset=0;if(!e)throw new Error(`Invalid array class: ${e}`);if(!t||t<=0)throw new Error(`Invalid output buffer size: ${t}`);this.ArrayClass=e,this.outputBufferSize=t}get queuedSize(){return this.partialBuffers.reduce((e,t)=>e+t.length,0)}feed(e){this.partialBuffers.push(e)}get canDrain(){return this.partialBuffers.reduce((t,s)=>t+s.length,0)-this.partialBufferOffset>=this.outputBufferSize}drain(){if(!this.canDrain)return null;let e=this.ArrayClass,t=new e(this.outputBufferSize),s=0;for(;s!=t.length;){if(s>t.length)throw new Error(`Buffer overflow: ${s} > ${t.length}`);let n=t.length-s,o=this.partialBuffers[0],r=o.length-this.partialBufferOffset;r<n?(t.set(o.subarray(this.partialBufferOffset),s),s+=r,this.partialBuffers.shift(),this.partialBufferOffset=0):(t.set(o.subarray(this.partialBufferOffset,this.partialBufferOffset+n),s),s+=n,this.partialBufferOffset+=n)}return t}pad(){let e=this.queuedSize%this.outputBufferSize;if(e==0)return;let t=this.ArrayClass,s=new t(e);this.feed(s)}};var H=class{constructor(e,t,s,n){if(!e||!t||!s)throw new Error("Invalid settings specified for the resampler.");this.resampler=null,this.fromSampleRate=e,this.toSampleRate=t,this.channels=s||0,this.inputBufferSize=n,this.initialize()}initialize(){this.fromSampleRate==this.toSampleRate?(this.resampler=e=>e,this.ratioWeight=1):(this.fromSampleRate<this.toSampleRate?(this.linearInterpolation(),this.lastWeight=1):(this.multiTap(),this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate)}bufferSlice(e){try{return this.outputBuffer.subarray(0,e)}catch{try{return this.outputBuffer.length=e,this.outputBuffer}catch{return this.outputBuffer.slice(0,e)}}}initializeBuffers(){this.outputBufferSize=Math.ceil(this.inputBufferSize*this.toSampleRate/this.fromSampleRate/this.channels*1.0000004768371582)+this.channels+this.channels;try{this.outputBuffer=new Float32Array(this.outputBufferSize),this.lastOutput=new Float32Array(this.channels)}catch{this.outputBuffer=[],this.lastOutput=[]}}linearInterpolation(){this.resampler=e=>{let t=e.length,s=this.channels,n,o,r,u,a,c,i,l,p;if(t%s!==0)throw new Error("Buffer was of incorrect sample length.");if(t<=0)return[];for(n=this.outputBufferSize,o=this.ratioWeight,r=this.lastWeight,u=0,a=0,c=0,i=0,l=this.outputBuffer;r<1;r+=o)for(a=r%1,u=1-a,this.lastWeight=r%1,p=0;p<this.channels;++p)l[i++]=this.lastOutput[p]*u+e[p]*a;for(r-=1,t-=s,c=Math.floor(r)*s;i<n&&c<t;){for(a=r%1,u=1-a,p=0;p<this.channels;++p)l[i++]=e[c+(p>0?p:0)]*u+e[c+(s+p)]*a;r+=o,c=Math.floor(r)*s}for(p=0;p<s;++p)this.lastOutput[p]=e[c++];return this.bufferSlice(i)}}multiTap(){this.resampler=e=>{let t=e.length,s,n,o=this.channels,r,u,a,c,i,l,p,h,f;if(t%o!==0)throw new Error("Buffer was of incorrect sample length.");if(t<=0)return[];for(s=this.outputBufferSize,n=[],r=this.ratioWeight,u=0,c=0,i=0,l=!this.tailExists,this.tailExists=!1,p=this.outputBuffer,h=0,f=0,a=0;a<o;++a)n[a]=0;do{if(l)for(u=r,a=0;a<o;++a)n[a]=0;else{for(u=this.lastWeight,a=0;a<o;++a)n[a]=this.lastOutput[a];l=!0}for(;u>0&&c<t;)if(i=1+c-f,u>=i){for(a=0;a<o;++a)n[a]+=e[c++]*i;f=c,u-=i}else{for(a=0;a<o;++a)n[a]+=e[c+(a>0?a:0)]*u;f+=u,u=0;break}if(u===0)for(a=0;a<o;++a)p[h++]=n[a]/r;else{for(this.lastWeight=u,a=0;a<o;++a)this.lastOutput[a]=n[a];this.tailExists=!0;break}}while(c<t&&h<s);return this.bufferSlice(h)}}resample(e){return this.fromSampleRate==this.toSampleRate?this.ratioWeight=1:(this.fromSampleRate<this.toSampleRate?this.lastWeight=1:(this.tailExists=!1,this.lastWeight=0),this.initializeBuffers(),this.ratioWeight=this.fromSampleRate/this.toSampleRate),this.resampler(e)}};function Ae(d){let e=d.length,t=new Int16Array(e);for(;e--;){let s=Math.max(-1,Math.min(1,d[e]));t[e]=s<0?s*32768:s*32767}return t}function Ee(d){let e=d.length,t=new BigInt64Array(e);for(;e--;){let s=Math.max(-1,Math.min(1,d[e]));t[e]=BigInt(Math.floor(s<0?s*32768:s*32767))*0x100000000000n}return t}function Me(d){let e=d.length,t=new Float32Array(e);for(;e--;){let s=d[e];t[e]=s>=32768?-(65536-s)/32768:s/32767}return t}import ie from"openai";import{v4 as ne}from"uuid";var b=class{constructor(){this.size=4096;this.groups=[]}createGroup(e){let t=new U;return t.id=e,this.groups.push(t),t}group(e){return this.groups.find(t=>t.id===e)}static countTokensInText(e){return e==null?e="":typeof e=="number"?e=e+"":typeof e!="string"&&(e=JSON.stringify(e)),Math.ceil(e.length/3)}countTokens(){return this.groups.reduce((e,t)=>e+t.tokenCount,0)}removeOverflow(){let e=this.countTokens(),t=this.groups.reduce((s,n)=>s+n.weight,0);for(;e>this.size;){let s=this.groups.slice().sort((o,r)=>{let u=Math.floor(o.weight/t*this.size),a=Math.floor(r.weight/t*this.size),c=o.tokenCount-u;return r.tokenCount-a-c}),n=this.removeOneItem(s);if(!n)throw new Error("Too many items in the token window that cannot be removed.");e-=n.tokenCount}}removeOneItem(e){for(let t of e){let s=t.items.findIndex(o=>!o.cannotRemove);if(s===-1)continue;let n=t.items[s];return t.items.splice(s,1),t.tokenCount-=n.tokenCount,n}return null}},U=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
|
|
10
10
|
`;this.itemPadding=0;this.sortFunction=(e,t)=>e.sortOrder!==t.sortOrder?e.sortOrder-t.sortOrder:e.dateAdded!==t.dateAdded?e.dateAdded-t.dateAdded:0}setItemPadding(e){return this.itemPadding=e,this.recalculateTokens(),this}sortBy(e){return this.sortFunction=e,this.items.sort(this.sortFunction),this}setSeparator(e){return this.separator==e?this:(this.separator=e,this.recalculateTokens(),this)}setWeight(e){return this.weight=e,this}recalculateTokens(){this.tokenCount=this.items.reduce((e,t)=>(t.tokenCount=b.countTokensInText(typeof t.data=="string"?t.data:JSON.stringify(t.data))+b.countTokensInText(this.separator)+this.itemPadding,e+t.tokenCount),0)}add(e){typeof e=="string"&&(e={source:"user",data:e});let t=e;t.id===void 0&&(t.id=ne()),!t.sections?.length&&typeof t.data=="string"?t.text=t.data:t.text=t.sections?.map(n=>{if(n.type==="text")return n.text||"";if(n.type==="tool_call")return`[Tool Call: ${n.toolKbName||n.toolName}] `;if(n.type==="tool_result"&&n.toolErrorResponse)return`[Tool Error: ${n.toolErrorResponse}] `}).filter(n=>!!n).join(`
|
|
11
11
|
|
|
12
|
-
`)||"";let s=this.items.find(n=>n.id===t.id);return s?(this.tokenCount-=s.tokenCount,Object.assign(s,t),t=s):this.items.push(t),t.dateAdded===void 0&&(t.dateAdded=Date.now()),t.sortOrder===void 0&&(t.sortOrder=0),t.disabled===void 0&&(t.disabled=!1),t.source===void 0&&(t.source="user"),t.sections===void 0&&(t.sections=[]),t.tokenCount=t.disabled?0:b.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+b.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=t.tokenCount,this.items.sort(this.sortFunction),t}getAllAsString(){return this.getAll().map(e=>e.text).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}},x=(o=>(o.Text="text",o.ToolCall="tool_call",o.ToolResult="tool_result",o.Thinking="thinking",o.Other="other",o))(x||{});import{v4 as oe}from"uuid";var X=new g("ChatBase"),C=class{constructor(e){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let e=new b;return e.createGroup("context").setSeparator(`
|
|
12
|
+
`)||"";let s=this.items.find(n=>n.id===t.id);return s?(this.tokenCount-=s.tokenCount,Object.assign(s,t),t=s):this.items.push(t),t.dateAdded===void 0&&(t.dateAdded=Date.now()),t.sortOrder===void 0&&(t.sortOrder=0),t.disabled===void 0&&(t.disabled=!1),t.source===void 0&&(t.source="user"),t.sections===void 0&&(t.sections=[]),t.tokenCount=t.disabled?0:b.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+b.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=t.tokenCount,this.items.sort(this.sortFunction),t}remove(e){let t=this.items.findIndex(s=>s.id===e);return t===-1?!1:(this.tokenCount-=this.items[t].tokenCount||0,this.items.splice(t,1),!0)}getAllAsString(){return this.getAll().map(e=>e.text).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}},x=(o=>(o.Text="text",o.ToolCall="tool_call",o.ToolResult="tool_result",o.Thinking="thinking",o.Other="other",o))(x||{});import{v4 as oe}from"uuid";var X=new g("ChatBase"),C=class{constructor(e){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let e=new b;return e.createGroup("context").setSeparator(`
|
|
13
13
|
|
|
14
14
|
`),e.createGroup("actions").setItemPadding(25),e.createGroup("messages").setItemPadding(10),e})();this.config=e,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}getBaseURL(){if(!this.config.endpoint)return;let e=this.config.endpoint;return e.endsWith("/chat/completions")&&(e=e.substring(0,e.length-17)),e}async sendMessage(e,t){throw new Error("Not implemented")}addUserMessage(e){throw new Error("Not implemented")}addAssistantMessage(e){throw new Error("Not implemented")}addTextMessage(e,t,s){this.messageGroup.add({id:"msg-"+oe(),source:t,data:s,sections:[{type:"text",text:e}]})}onBeforeIncomingMessage(e){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(e){return this.toolGroup.add({id:e.name,data:e,cannotRemove:!e.canRemove,sortOrder:101,disabled:!!e.kbItem?.disabled})}findToolBySafeName(e){return this.toolGroup.getAll().find(t=>t.id==e||t.data?.kbItem?.name==e)?.data}async executeTool(e,t){if(!e)throw new Error("Tool not found");X.debug(`Executing tool '${e.name}'`,t,e),this.config.onAIToolStart?.(e.kbItem?.name||e.name,t);let s;try{s=await e.callback(t)}catch(n){throw X.error(`Error executing tool '${e.name}'`,n),n}return typeof s!="string"&&(s=JSON.stringify(s)||""),(s===""||s==="undefined")&&(s="success"),s}};import{v4 as re}from"uuid";var $=new g("ChatGPT"),M=class extends C{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}createOpenAIClient(){return new ie({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(e,t){this.addUserMessage(e);let s=this.createOpenAIClient(),n=!0,o=[];for(;n;){let r="msg-"+re();n=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),$.debug("Before processing state",{messages:this.messageGroup.getAll().map(l=>l.data),tools:this.toolGroup.getAll().map(l=>l.data),context:this.contextGroup.getAll().map(l=>l.text)});let u=this.toolGroup.getAll().filter(l=>!!l?.data).map(l=>({type:"function",function:{name:l.data.name,description:l.data.description||"",parameters:{type:"object",...l.data?.params}}})),a,c;if(this.config.stream){let l=s.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:u,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let p of l){let h=l.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!h)continue;let f=this.parseMessageBlock(r,h,void 0,!0);this.config.onAIMessage?.([...o,f],!0),t?.([...o,f])}a=await l.finalMessage(),c=await l.totalUsage()}else{let l=await s.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:u,parallel_tool_calls:!0});a=l.choices[0].message,c=l.usage}a.role=="assistant"&&!a.content&&!a.tool_calls?.length&&(a.content=""),$.debug("Message received",a);let i=this.messageGroup.add(this.parseMessageBlock(r,a,c,!1));o.push(i),await Promise.all((a.tool_calls||[]).map(async l=>{if(l.type!="function")return;let p=this.findToolBySafeName(l.function.name);try{let h=null;try{h=l.function.arguments?JSON.parse(l.function.arguments):null}catch(te){throw new Error(`The AI provided invalid JSON arguments for tool call ${l.function.name}: ${te.message}`)}let f=await this.executeTool(p,h),N=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:l.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolSuccessResponse:f,toolCallInstanceID:l.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:l.id,content:f}});o.push(N)}catch(h){let f=h?.message||"An unknown error occurred",N=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:l.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolErrorResponse:f,toolCallInstanceID:l.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:l.id,content:`Error performing tool call ${l.function.name}: ${f}`}});o.push(N)}n=!0,this.config.onAIMessage?.(o,!0),t?.(o)})),this.stats.tokensUsed+=c?.total_tokens||0}return this.config.onAIMessage?.(o,!1),t?.(o),o}parseMessageBlock(e,t,s,n){let o=[];t.reasoning&&o.push({type:"thinking",text:t.reasoning});for(let r of t.tool_calls||[]){if(r.type!="function")continue;let u=this.findToolBySafeName(r.function.name),a=null;if(r.function.arguments)try{a=JSON.parse(r.function.arguments)}catch(c){n||$.error(`Failed to parse tool parameters for tool call ${r.function.name}:`,c)}o.push({type:"tool_call",toolName:r.function.name,toolKbID:u?.kbItem?.id,toolKbName:u?.kbItem?.name,toolCallInstanceID:r.id,toolCallHiddenInUI:u?.kbItem?.hideActionInUI,toolParameters:a})}return typeof t.content=="string"&&o.push({type:"text",text:t.content||""}),{id:e,data:t,sections:o,source:"assistant",streamingInProgress:n,usage:{inputTokens:s?.prompt_tokens||0,outputTokens:s?.completion_tokens||0,cachedInputTokens:0,totalTokens:(s?.prompt_tokens||0)+(s?.completion_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].data?.role=="tool";)this.messageGroup.items.shift()}};import ae from"@anthropic-ai/sdk";import{v4 as le}from"uuid";var Y=new g("AnthropicChat"),P=class extends C{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}async sendMessage(e,t){this.addUserMessage(e);let s=new ae({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),n=!0,o=[];for(;n;){n=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),Y.debug("Before processing state",{messages:this.messageGroup.getAll().map(i=>i.data),tools:this.toolGroup.getAll().map(i=>i.data),context:this.contextGroup.getAll().map(i=>i.text)});let r=this.toolGroup.getAll().map(i=>({name:i.data?.name||"",description:i.data?.description||"",input_schema:{...i.data?.params,type:"object"}})),u;if(this.config.stream){let i=s.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(l=>l.data),tools:r,stream:!0});i.on("streamEvent",(l,p)=>{let h=this.parseMessageBlock(p,!0);this.config.onAIMessage?.([...o,h],!0),t?.([...o,h])});try{u=await i.finalMessage()}catch(l){throw l?.error?.error?.message?l.error.error:l}}else try{u=await s.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(i=>i.data),tools:r})}catch(i){throw i?.error?.error?.message?i.error.error:i}if(Y.debug("Message received",u),u.content?.length){let i=this.messageGroup.add(this.parseMessageBlock(u,!1));o.push(i)}let a=[],c=[];if(await Promise.all(u.content.map(async i=>{if(i.type!="tool_use")return;let l=this.findToolBySafeName(i.name);try{let p=await this.executeTool(l,i.input);c.push({type:"tool_result",tool_use_id:i.id,content:p}),a.push({type:"tool_result",toolKbID:l?.kbItem?.id,toolKbName:l?.kbItem?.name,toolName:i.name,toolSuccessResponse:p,toolCallInstanceID:i.id,toolCallHiddenInUI:l?.kbItem?.hideActionInUI})}catch(p){let h=p?.message||"An unknown error occurred";c.push({type:"tool_result",tool_use_id:i.id,content:`Error performing tool call ${i.name}: ${h}`}),a.push({type:"tool_result",toolKbID:l?.kbItem?.id,toolKbName:l?.kbItem?.name,toolName:i.name,toolErrorResponse:h,toolCallInstanceID:i.id,toolCallHiddenInUI:l?.kbItem?.hideActionInUI})}})),c.length>0){let i=this.messageGroup.add({id:"msg-"+le(),sections:a,data:{role:"user",content:c}});o.push(i),n=!0,this.config.onAIMessage?.(o,!0),t?.(o)}this.stats.tokensUsed+=u.usage.input_tokens+u.usage.output_tokens}return this.config.onAIMessage?.(o,!1),t?.(o),o}parseMessageBlock(e,t){let s=[];for(let n of e.content)if(n.type=="thinking")s.push({type:"thinking",text:n.thinking||""});else if(n.type=="text")s.push({type:"text",text:n.text||""});else if(n.type=="tool_use"){let o=this.findToolBySafeName(n.name);s.push({type:"tool_call",toolName:n.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:n.input,toolCallInstanceID:n.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:e.id,data:{role:e.role,content:e.content},sections:s,source:"assistant",streamingInProgress:t,usage:{inputTokens:e.usage?.input_tokens||0,outputTokens:e.usage?.output_tokens||0,cachedInputTokens:e.usage?.cache_read_input_tokens||0,totalTokens:(e.usage?.input_tokens||0)+(e.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import we from"minisearch";var Q=d=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,hideActionInUI:"after-complete",disabled:!d?.knowledgeBase?.allowRagSearch,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,t)=>{let s=await t.knowledgeBase.search(e.query),n=t;n._lastKBsearch=e.query,n._nextRequestUseKBitems=s;let o=s.filter(u=>u.type!="action").map(u=>"- "+u.name).join(`
|
|
15
15
|
`)||"- (none)",r=s.filter(u=>u.type=="action").map(u=>"- "+u._functionID).join(`
|
|
@@ -18,9 +18,9 @@ New information found:
|
|
|
18
18
|
${o}
|
|
19
19
|
|
|
20
20
|
New tools available:
|
|
21
|
-
${r}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!d?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!d?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let s=new URL(e.path,window.location.origin).pathname;return window.location.href=s,`Changed route to: ${s}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!d?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let s=encodeURIComponent(e.email_address),n=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),r=`mailto:${s}?subject=${n}&body=${o}`;try{window.location.href=r}catch(u){throw new Error(`Failed to open email client: ${u instanceof Error?u.message:String(u)}`)}return`Email opened in default mail client. Recipient: ${e.email_address}, Subject: ${e.subject}`}}];import{Client as ue}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as de}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var v={name:"@intelliweave/embedded",version:"2.0.72-beta.12",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"}};import{LoggingMessageNotificationSchema as pe,ToolListChangedNotificationSchema as he}from"@modelcontextprotocol/sdk/types.js";var m=new g("MCPKnowledgeClient"),ge="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",W=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){m.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new URL(this.config.baseURL),s={};this.config.headers&&(s={...s,...this.config.headers}),this.config.proxy?.enabled&&(s["Mcp-Target-Url"]=t.toString(),s["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",t=new URL(this.config.proxy.url||ge));let n=new ue({name:v.name,version:v.version}),o=new de(t,{requestInit:{headers:s}});return await n.connect(o),m.debug("Connected with HTTP streaming mode"),n});return await this.disconnect(),this.client=e,e.onerror=t=>{m.error(`MCP client error: ${t.message}`)},e.onclose=()=>{m.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(pe,t=>{t.params.level=="critical"?m.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?m.error(`[Server] ${t.params.data}`):t.params.level=="error"?m.error(`[Server] ${t.params.data}`):t.params.level=="warning"?m.warn(`[Server] ${t.params.data}`):t.params.level=="info"?m.info(`[Server] ${t.params.data}`):t.params.level=="debug"?m.debug(`[Server] ${t.params.data}`):m.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(he,t=>{m.debug("Tool list changed",t),this.fetchTools()}),m.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],t;for(;;){let n=await this.client.listTools({cursor:t});t=n.nextCursor;for(let o of n.tools||[])e.push(o);if(!n?.tools?.length||!t)break}let s=[];for(let n of e){let o=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:r=>this.performToolCall(n.name,r),disabled:o})}m.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=s}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),s=await this.performSearchCall(e);return t=t.concat(s),this.lastSearchQuery=e,this.lastSearchResults=t,m.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let s=this.tools.find(o=>o.name==this.config.searchToolName);if(!s)return m.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let n;if(s.inputSchema.required?.length==1){let o=s.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let o=Object.keys(s.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[o]:e})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let o=0;o<n.length;o++){let r=n[o];t.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof r=="string"?r:JSON.stringify(r)})}else t.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return t}async performToolCall(e,t){await this.connect(),m.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let s=await this.client.callTool({name:e,arguments:t});if(s.isError){let n=s.content?.[0]?.text||"Unknown error";throw m.error(`Error calling tool ${e}: ${n}`),new Error(`Error calling tool ${e}: ${n}`)}if(Array.isArray(s.content)&&s.content.length==1&&s.content[0].type=="text")try{return JSON.parse(s.content[0].text)}catch{}return s.content||[]}};import{v4 as me}from"uuid";var fe=new g("Statistics"),_=[];async function I(d,e){let t={...e,event_id:me(),event_date:new Date().toISOString(),sdk_version:v.version,conversation_id:d?.conversationID||"",api_key:d?.apiKey||"",user_id:d?.userID||""};if(_.push(t),!d||(await new Promise(n=>setTimeout(n,5e3)),_.length===0))return;let s=_.slice();_.length=0;try{let n=await fetch(d.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){fe.warn("Failed to submit analytics event:",n),_.push(...s);return}}var k=new g("KnowledgeBase"),L=1,R=class d{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>Q(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,t){let s=e;return typeof e=="function"&&(t=e,s=`source.${L++}`),this._sources.push({id:s,query:t}),s}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&y().knowledgeBaseSources&&(e=e.concat(y().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(t=>!t.disabled),e}async search(e){k.debug(`Searching knowledge base for: ${e}`);let t=Date.now(),s=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});s.query=e,s.entries=[],s.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(s),this._windowSources=s.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async c=>{try{let i=Date.now(),l=await c.query(e);return k.debug(`Source '${c.id}' took ${Date.now()-i}ms`),l||[]}catch(i){return k.warn(`Knowledge source '${c.id}' failed:`,i),[]}}))).flat();o=o.concat(s.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&y().knowledgeBase&&(o=o.concat(y().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);for(let c=0;c<o.length;c++){let i=o[c];i.id=i.id||`temp.${c}`,i._functionID=i.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let r=new we({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});r.addAll(o);let a=r.search(e).map(c=>o.find(i=>i.id==c.id));for(let c of o)c.isContext&&(a.find(i=>i.id===c.id)||a.push(c));return this.lastResults=a,I(this.ai,{event_type:"kb_search",value:a.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),k.debug("Found results:",a),a}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${L++}`),k.debug(`Registering remote knowledge base source: ${e}`);let s=[],n=[],o=!0,r=async(a,c)=>{k.debug(`Calling remote knowledge base action: ${a.id}`);let i={type:"action",userID:this.ai.userID,actionID:a.id,parameters:c},l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let p=await l.json();return u(p.updateItems||[]),p.response},u=a=>{for(let c of a){if(!c.id){k.warn("KB item skipped since it has no ID.",c);continue}let i=s.find(l=>l.id==c.id);if(i){i.name=c.name||i.name||"",i.content=c.content||i.content||"",i.disabled=c.disabled??i.disabled,i.isContext=c.isContext??i.isContext,i.parameters=c.parameters||i.parameters||[],i.tags=c.tags||i.tags,i.type=c.type||i.type;continue}s.push({...c,action:l=>r(c,l)})}};this.registerSource(t,async a=>{if(o&&n.includes(a))return s;let c={type:"search",userID:this.ai?.userID||"",query:a},i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let l=await i.json();return o=!l.noCache,n.includes(a)||n.push(a),u(l.items),s})}clone(e){let t=new d(e);return t._sources=this._sources.slice(),t._windowSources=this._windowSources.slice(),t.manualEntries=this.manualEntries.slice(),t.allowGlobalConfigSources=this.allowGlobalConfigSources,t.allowWindowSources=this.allowWindowSources,t.allowRagSearch=this.allowRagSearch,t.ensureInternalKnowledge(),t}registerMCPSource(e){e.id||(e.id=`external.${L++}`);let t=new W(e);return this.registerSource(e.id,s=>t.search(s)),t}};var D=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(`
|
|
21
|
+
${r}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!d?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!d?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let s=new URL(e.path,window.location.origin).pathname;return window.location.href=s,`Changed route to: ${s}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!d?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(e,t)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!t.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let s=encodeURIComponent(e.email_address),n=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),r=`mailto:${s}?subject=${n}&body=${o}`;try{window.location.href=r}catch(u){throw new Error(`Failed to open email client: ${u instanceof Error?u.message:String(u)}`)}return`Email opened in default mail client. Recipient: ${e.email_address}, Subject: ${e.subject}`}}];import{Client as ue}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as de}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var v={name:"@intelliweave/embedded",version:"2.0.72-beta.13",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"}};import{LoggingMessageNotificationSchema as pe,ToolListChangedNotificationSchema as he}from"@modelcontextprotocol/sdk/types.js";var m=new g("MCPKnowledgeClient"),ge="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",W=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){m.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let t=new URL(this.config.baseURL),s={};this.config.headers&&(s={...s,...this.config.headers}),this.config.proxy?.enabled&&(s["Mcp-Target-Url"]=t.toString(),s["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",t=new URL(this.config.proxy.url||ge));let n=new ue({name:v.name,version:v.version}),o=new de(t,{requestInit:{headers:s}});return await n.connect(o),m.debug("Connected with HTTP streaming mode"),n});return await this.disconnect(),this.client=e,e.onerror=t=>{m.error(`MCP client error: ${t.message}`)},e.onclose=()=>{m.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(pe,t=>{t.params.level=="critical"?m.error(`[Server] ${t.params.data}`):t.params.level=="emergency"?m.error(`[Server] ${t.params.data}`):t.params.level=="error"?m.error(`[Server] ${t.params.data}`):t.params.level=="warning"?m.warn(`[Server] ${t.params.data}`):t.params.level=="info"?m.info(`[Server] ${t.params.data}`):t.params.level=="debug"?m.debug(`[Server] ${t.params.data}`):m.log(`[Server] ${t.params.data}`)}),e.setNotificationHandler(he,t=>{m.debug("Tool list changed",t),this.fetchTools()}),m.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],t;for(;;){let n=await this.client.listTools({cursor:t});t=n.nextCursor;for(let o of n.tools||[])e.push(o);if(!n?.tools?.length||!t)break}let s=[];for(let n of e){let o=!!(this.config.searchToolName&&n.name==this.config.searchToolName&&!this.config.searchToolVisible);s.push({id:n.name,name:n.name,content:n.description||"",type:"action",isContext:!0,parameters:n.inputSchema,action:r=>this.performToolCall(n.name,r),disabled:o})}m.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=s}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let t=this.iwActions.slice(),s=await this.performSearchCall(e);return t=t.concat(s),this.lastSearchQuery=e,this.lastSearchResults=t,m.debug(`Search completed, found ${t.length} items.`),t}async performSearchCall(e){let t=[];if(!this.config.searchToolName)return t;let s=this.tools.find(o=>o.name==this.config.searchToolName);if(!s)return m.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),t;let n;if(s.inputSchema.required?.length==1){let o=s.inputSchema.required[0];n=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(s.inputSchema.properties&&Object.keys(s.inputSchema.properties).length==1){let o=Object.keys(s.inputSchema.properties)[0];n=await this.performToolCall(this.config.searchToolName,{[o]:e})}else n=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(n))for(let o=0;o<n.length;o++){let r=n[o];t.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof r=="string"?r:JSON.stringify(r)})}else t.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)});return t}async performToolCall(e,t){await this.connect(),m.debug(`Performing tool call for ${e} with params:`,t),this.stats.toolsCalled+=1;let s=await this.client.callTool({name:e,arguments:t});if(s.isError){let n=s.content?.[0]?.text||"Unknown error";throw m.error(`Error calling tool ${e}: ${n}`),new Error(`Error calling tool ${e}: ${n}`)}if(Array.isArray(s.content)&&s.content.length==1&&s.content[0].type=="text")try{return JSON.parse(s.content[0].text)}catch{}return s.content||[]}};import{v4 as me}from"uuid";var fe=new g("Statistics"),_=[];async function I(d,e){let t={...e,event_id:me(),event_date:new Date().toISOString(),sdk_version:v.version,conversation_id:d?.conversationID||"",api_key:d?.apiKey||"",user_id:d?.userID||""};if(_.push(t),!d||(await new Promise(n=>setTimeout(n,5e3)),_.length===0))return;let s=_.slice();_.length=0;try{let n=await fetch(d.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s})});if(!n.ok)throw new Error(`Analytics submission failed: ${n.status} ${n.statusText}`)}catch(n){fe.warn("Failed to submit analytics event:",n),_.push(...s);return}}var k=new g("KnowledgeBase"),L=1,R=class d{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.allowRagSearch=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>Q(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,t){let s=e;return typeof e=="function"&&(t=e,s=`source.${L++}`),this._sources.push({id:s,query:t}),s}removeSource(e){this._sources=this.sources.filter(t=>t.id!==e&&t.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(t=>t.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&y().knowledgeBaseSources&&(e=e.concat(y().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(t=>!t.disabled),e}async search(e){k.debug(`Searching knowledge base for: ${e}`);let t=Date.now(),s=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});s.query=e,s.entries=[],s.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(s),this._windowSources=s.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async c=>{try{let i=Date.now(),l=await c.query(e);return k.debug(`Source '${c.id}' took ${Date.now()-i}ms`),l||[]}catch(i){return k.warn(`Knowledge source '${c.id}' failed:`,i),[]}}))).flat();o=o.concat(s.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&y().knowledgeBase&&(o=o.concat(y().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);for(let c=0;c<o.length;c++){let i=o[c];i.id=i.id||`temp.${c}`,i._functionID=i.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let r=new we({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});r.addAll(o);let a=r.search(e).map(c=>o.find(i=>i.id==c.id));for(let c of o)c.isContext&&(a.find(i=>i.id===c.id)||a.push(c));return this.lastResults=a,I(this.ai,{event_type:"kb_search",value:a.length,value_str:"",event_properties:{search_time_ms:Date.now()-t,sources_searched:this.sources.length}}),k.debug("Found results:",a),a}getCachedEntry(e){return this.lastResults.find(t=>t.id==e||t._functionID==e)}registerSourceFromURL(e,t){t||(t=`external.${L++}`),k.debug(`Registering remote knowledge base source: ${e}`);let s=[],n=[],o=!0,r=async(a,c)=>{k.debug(`Calling remote knowledge base action: ${a.id}`);let i={type:"action",userID:this.ai.userID,actionID:a.id,parameters:c},l=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!l.ok)throw new Error(`HTTP Error ${l.status} ${l.statusText}`);let p=await l.json();return u(p.updateItems||[]),p.response},u=a=>{for(let c of a){if(!c.id){k.warn("KB item skipped since it has no ID.",c);continue}let i=s.find(l=>l.id==c.id);if(i){i.name=c.name||i.name||"",i.content=c.content||i.content||"",i.disabled=c.disabled??i.disabled,i.isContext=c.isContext??i.isContext,i.parameters=c.parameters||i.parameters||[],i.tags=c.tags||i.tags,i.type=c.type||i.type;continue}s.push({...c,action:l=>r(c,l)})}};this.registerSource(t,async a=>{if(o&&n.includes(a))return s;let c={type:"search",userID:this.ai?.userID||"",query:a},i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!i.ok)throw new Error(`HTTP Error ${i.status} ${i.statusText}`);let l=await i.json();return o=!l.noCache,n.includes(a)||n.push(a),u(l.items),s})}clone(e){let t=new d(e);return t._sources=this._sources.slice(),t._windowSources=this._windowSources.slice(),t.manualEntries=this.manualEntries.slice(),t.allowGlobalConfigSources=this.allowGlobalConfigSources,t.allowWindowSources=this.allowWindowSources,t.allowRagSearch=this.allowRagSearch,t.ensureInternalKnowledge(),t}registerMCPSource(e){e.id||(e.id=`external.${L++}`);let t=new W(e);return this.registerSource(e.id,s=>t.search(s)),t}};var D=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(`
|
|
22
22
|
|
|
23
|
-
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,t)=>e+(t.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(t=>t.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(t=>t.sections?.find(s=>s.type=="tool_result"&&s.toolCallInstanceID==e)).filter(t=>!!t)[0]||null}};import{v4 as Z}from"uuid";var
|
|
23
|
+
`)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,t)=>e+(t.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,t)=>e+(t.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(t=>t.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(t=>t.sections?.find(s=>s.type=="tool_result"&&s.toolCallInstanceID==e)).filter(t=>!!t)[0]||null}};import{v4 as Z}from"uuid";var K=class{constructor(e){this.ai=e}async boolean(e){let t=await this.instruct({...e,instruction:`${e.instruction}
|
|
24
24
|
|
|
25
25
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(t.toLowerCase().includes("true"))return!0;if(t.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+t)}async choose(e){let t=await this.instruct({...e,instruction:`${e.instruction}
|
|
26
26
|
|
|
@@ -37,7 +37,7 @@ Objects should have the following keys:
|
|
|
37
37
|
${e.extractions.map(n=>`- ${n.name} (${n.type}): ${n.description||"No description provided."}`).join(`
|
|
38
38
|
`)}
|
|
39
39
|
`,s=await this.instruct({...e,instruction:t});if(s=s.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),e.allowMultiple){let n=s.split(`
|
|
40
|
-
`).map(r=>r.trim()).filter(r=>!!r.trim()),o=[];for(let r of n)try{o.push(JSON.parse(r))}catch(u){console.error("Failed to parse line as JSON:",r,u.message)}return o}else return[JSON.parse(s.trim())]}async generateMarkdown(e){return this.instruct({...e,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(e){let t=this.ai.clone();return t.resetConversation(),t.getContextPrefix=async()=>e.instruction,e.callback&&t.addEventListener("output",s=>{e.callback(s.detail.message)}),e.allowKB||(t.knowledgeBase._sources=[]),await t.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(s=>s.text())}};var
|
|
40
|
+
`).map(r=>r.trim()).filter(r=>!!r.trim()),o=[];for(let r of n)try{o.push(JSON.parse(r))}catch(u){console.error("Failed to parse line as JSON:",r,u.message)}return o}else return[JSON.parse(s.trim())]}async generateMarkdown(e){return this.instruct({...e,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(e){let t=this.ai.clone();return t.resetConversation(),t.getContextPrefix=async()=>e.instruction,e.callback&&t.addEventListener("output",s=>{e.callback(s.detail.message)}),e.allowKB||(t.knowledgeBase._sources=[]),await t.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(s=>s.text())}};var O=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(t=>t.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,t=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(s,n)=>await this.runQuery(e,s.query)}])}remove(e){this.subagents=this.subagents.filter(t=>t.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,t){let s=e.apiKey||this.ai.apiKey,n=this.cachedSubagents[s];return n||(n=new G,await n.load(s,e.config),this.cachedSubagents[s]=n),n=n.clone(),n.knowledgeBase.allowGlobalConfigSources=!1,n.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&n.knowledgeBase.reset(),n.knowledgeBase.allowRagSearch=!e.disableRagSearch,e.knowledge&&n.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(n),(await n.sendMessage(t)).text()}};var w=new g("Main"),ee=new Set,T=class T extends EventTarget{constructor(){super(...arguments);this.conversationID=Z();this.knowledgeBase=new R(this);this.subAgents=new O(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new K(this);this.userID=F();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.lastKBItems=[];this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:T.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(t,s){if(this.apiKey=t,!t)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{w.debug("Loading configuration...");let n=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t})});if(!n.ok)throw new Error(`Failed to load configuration: ${n.status} ${n.statusText}`);try{this.config=await n.json(),w.debug("Config loaded successfully:",this.config),s&&(this.config={...this.config,...s}),this.config&&w.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){w.error("Failed to parse JSON response:",o);try{let r=await n.clone().text();w.error("Raw response that failed parsing:",r)}catch{w.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let n=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!n.ok)throw new Error(`Failed to load VAD model: ${n.status} ${n.statusText}`);this.vadModel=await n.blob()}catch(n){w.warn(`Failed to load VAD model, some features will be unavailable. ${n.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let n of this.config.knowledge||[])n.url&&n.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:n.id,searchToolName:n.mcpSearchToolName,baseURL:n.url}):n.url&&this.knowledgeBase.registerSourceFromURL(n.url);for(let n of this.config.knowledge||[])n.entries?.length&&this.knowledgeBase.registerSource(n.id,()=>n.entries||[]);if(this.config.mcpServers)for(let n of this.config.mcpServers)this.knowledgeBase.registerMCPSource(n);for(let n of this.config.subagents||[])this.subAgents.register(n);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(n){throw w.warn("Failed to load:",n),this.error=n,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:n}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:n}})),n}}setModel(t){let s=this.models.find(o=>o.id==t);if(!s)throw new Error(`Model with ID "${t}" not found.`);let n={...s.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,r)=>{let u=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(u?.id||o,r)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(n):s.config.providerID==="anthropic"?this.currentModel=new P(n):this.currentModel=new M(n),this.currentModel.id=s.id,this.currentModel.metadata=s}async getContextPrefix(){let t=y().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof t=="function"&&(t=await t()),t}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let t=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let s=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:s}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,disabled:!this.knowledgeBase.allowRagSearch,data:A(`
|
|
41
41
|
# RAG search
|
|
42
42
|
Use the \`search\` tool proactively as much as possible to find missing information or tools.
|
|
43
43
|
Use the \`search\` tool when you are unsure about specific details or actions to take.
|
|
@@ -53,7 +53,7 @@ attachments:
|
|
|
53
53
|
mimetype: "${u.mimeType||""}"
|
|
54
54
|
url: "${u.url}"
|
|
55
55
|
`);r||(o+="```\n"),this.currentModel.contextGroup.add({id:n.id,data:`## ${n.type}: ${n.name}
|
|
56
|
-
${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="function"?n.disabled(this):n.disabled})}else if(n.type=="action"){let o={name:n._functionID,description:A(n.content),params:q(n.parameters||[{name:"value",type:"string",description:"Input"}]),callback:r=>this.toolRunKBAction(n,r),canRemove:!n.isContext,kbItem:n};this.currentModel.registerTool(o)}else continue}processIncomingMessage(t,s){if(!s){let n=this.currentModel?.stats?.tokensUsed||0,o=t.reduce((r,u)=>r+(u.usage?.totalTokens||0),0);I(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:n}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:s,messages:t}})),this.onAIMessage?.(t,!!s)}async sendMessage(t,s){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),ee.has(this.conversationID)||(ee.add(this.conversationID),I(this,{event_type:"session_start"})),I(this,{event_type:"message_send",value_str:"",event_properties:{message_length:t.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:t}})),this.submitAnalyticsEvent({type:"message",role:"user",message:t});let n=Date.now(),o=await this.currentModel.sendMessage(t),r=new D(o);(this._voiceTracker||w.debug.bind(w))(`LLM response took ${Date.now()-n}ms`);let a=this.currentModel.contextGroup.getAllAsString();a+=`
|
|
56
|
+
${o}`,cannotRemove:n.isContext,sortOrder:101,disabled:typeof n.disabled=="function"?n.disabled(this):n.disabled})}else if(n.type=="action"){let o={name:n._functionID,description:A(n.content),params:q(n.parameters||[{name:"value",type:"string",description:"Input"}]),callback:r=>this.toolRunKBAction(n,r),canRemove:!n.isContext,kbItem:n};this.currentModel.registerTool(o)}else continue;for(let n of this.lastKBItems)!n.isContext||!n.id||t.find(r=>r.id==n.id)||(this.currentModel.contextGroup.remove(n.id),n._functionID&&this.currentModel.toolGroup.remove(n._functionID));this.lastKBItems=t}processIncomingMessage(t,s){if(!s){let n=this.currentModel?.stats?.tokensUsed||0,o=t.reduce((r,u)=>r+(u.usage?.totalTokens||0),0);I(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:n}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:s,messages:t}})),this.onAIMessage?.(t,!!s)}async sendMessage(t,s){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),ee.has(this.conversationID)||(ee.add(this.conversationID),I(this,{event_type:"session_start"})),I(this,{event_type:"message_send",value_str:"",event_properties:{message_length:t.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:t}})),this.submitAnalyticsEvent({type:"message",role:"user",message:t});let n=Date.now(),o=await this.currentModel.sendMessage(t),r=new D(o);(this._voiceTracker||w.debug.bind(w))(`LLM response took ${Date.now()-n}ms`);let a=this.currentModel.contextGroup.getAllAsString();a+=`
|
|
57
57
|
|
|
58
58
|
=== TOOLS ===
|
|
59
59
|
|
package/dist/react/react.d.ts
CHANGED
|
@@ -61,6 +61,8 @@ declare class TokenWindowGroup<DataType> {
|
|
|
61
61
|
recalculateTokens(): void;
|
|
62
62
|
/** Add an item to the group */
|
|
63
63
|
add(item: string | TokenWindowGroupItemParams<DataType>): TokenWindowGroupItem<DataType>;
|
|
64
|
+
/** Manually remove an item */
|
|
65
|
+
remove(itemId: string): boolean;
|
|
64
66
|
/** Get all items as a string */
|
|
65
67
|
getAllAsString(): string;
|
|
66
68
|
/** Get all items. Doesn't return disabled items. */
|
|
@@ -1115,6 +1117,8 @@ declare class IntelliWeave extends EventTarget {
|
|
|
1115
1117
|
private _lastSystemMsg;
|
|
1116
1118
|
/** Get the system message prefix, before the KB entries are added */
|
|
1117
1119
|
getContextPrefix(): Promise<string>;
|
|
1120
|
+
/** KB items added in the last run */
|
|
1121
|
+
private lastKBItems;
|
|
1118
1122
|
/** Get system message to send to the AI */
|
|
1119
1123
|
onBeforeMessageProcessing(): Promise<void>;
|
|
1120
1124
|
/** @private Process incoming message(s) from the AI. Can be used to respond to encoded actions in the text response. */
|